Home›Design›Store orders and inventory
Course · Whole systemsLesson 33 of 330 read
Design doc · Orders and inventory

Online store: orders and inventory

Where should an online store keep its orders, carts and stock counts?

Applications like this: a shop, a marketplace checkout, a food-ordering app. This page is written the way I write a database design doc: the workload first, then where each kind of data goes and why, then how it grows, what breaks, and what I rejected.

The short answerOrders, order lines, payments references and stock live in one relational database, PostgreSQL or MySQL. Carts can live in Redis. Product search goes to a search engine, and reporting goes to a column store.
1 · The workload

What the application asks of the database

DimensionThis application
WritesBursty. Quiet most of the day, then 10 to 50 times normal during a sale.
ReadsMostly by key: an order, a customer's orders, a product's stock.
Read to writeAround 10 to 1 on the order tables, much higher on the catalog.
ConsistencyStrict for stock and orders. Two customers must not buy the last item.
LatencyCheckout under a few hundred milliseconds end to end.
GrowthSteady. Orders are rarely deleted, so the tables only grow.
Connected

Real failures behind this design

These incidents are why the choices below matter. Each one is written up with its numbers and sources.

2 · What goes where

Each kind of data, its store, and why

ApplicationOrders, order lines, customers, stockPostgreSQL or MySQLSOURCE OF TRUTHCarts and sessionsRedis or Valkey, or the same databaseCAN BE LOSTProduct searchElasticsearch or OpenSearchCOPYSales reportsA column store, fed by change data captureCOPY

Solid arrows: the application writes there. Dashed arrows: a copy fed from the source of truth (change data capture, an outbox, or a cache fill), which can be rebuilt from it.

DataWhere it goesWhy
Orders, order lines, customers, stockPostgreSQL or MySQLTransactions across several tables, foreign keys, and a check that stock never goes below zero. This is what a relational database is built for.
Carts and sessionsRedis or Valkey, or the same databaseA cart is read and rewritten on every click and can be rebuilt if lost. Keeping it out of the order tables keeps them small and hot.
Product searchElasticsearch or OpenSearchFull-text search with filters. The database stays the source of truth; the index is a copy.
Sales reportsA column store, fed by change data captureReports scan millions of order lines. Running them on the primary competes with checkout.

How each family of store behaves under traffic: Database families.

3 · Data model

The core tables and the queries they serve

CREATE TABLE orders (
  id          bigint PRIMARY KEY,
  customer_id bigint NOT NULL REFERENCES customers(id),
  status      text   NOT NULL,          -- placed, paid, shipped, refunded
  created_at  timestamptz NOT NULL DEFAULT now(),
  total_cents bigint NOT NULL
);
CREATE INDEX ON orders (customer_id, created_at DESC);

CREATE TABLE stock (
  sku       text PRIMARY KEY,
  available int  NOT NULL CHECK (available >= 0)
);

-- reserve stock inside the checkout transaction
UPDATE stock SET available = available - 1
WHERE sku = $1 AND available >= 1;   -- 0 rows updated = sold out
Step through it

One request, followed through the design

Step through checkout, then the race for the last item. Press Play, or use the arrows.

Try it · real PostgreSQL in your browser

Run it: two shoppers, one lamp left

One product with one unit in stock. The checkout takes stock with a conditional UPDATE, so it never has to read first and hope nothing changed.

  1. Shopper A buys it
    UPDATE products SET stock = stock - 1
    WHERE id = 1 AND stock > 0
    RETURNING id, stock;
  2. Shopper B tries the same
    UPDATE products SET stock = stock - 1
    WHERE id = 1 AND stock > 0
    RETURNING id, stock;
  3. Without the condition
    UPDATE products SET stock = stock - 1 WHERE id = 1;
4 · How it grows

Start simple, change one thing at a time

  1. One primary and a standbyEverything in one database. Add a read replica only when reads, not writes, saturate the primary.
  2. Sales get bigger than the primaryMove carts to Redis, product reads to a cache, and reports to a column store. Put a connection pooler in front of the database.
  3. Writes outgrow one primaryShard by customer_id or by region. Orders for one customer stay on one shard, so their transactions stay local.

Scale it: watch this design grow

Pick a stage, then throw something at it. The numbers are a model to show the shape of each change, not a measurement; the measured numbers are in the lab notebooks.

5 · What breaks first

The failures to plan for

Units sold of a 1,000-unit stock, 1,600 attempts

Sixteen clients at once. Measured in Notebook 6.

Read, then write the new valueUPDATE ... WHERE available >= 1
05001,0001,5002,000PostgreSQLPostgreSQL, Read, then write the new value: 1,6001,600PostgreSQL, Conditional update: 1,0001,000MySQLMySQL, Read, then write the new value: 1,6001,600MySQL, Conditional update: 1,0001,000MongoDBMongoDB, Read, then write the new value: 1,6001,600MongoDB, Conditional update: 1,0001,000stock: 1,000
What happensWhat you seeWhat I do
The hot SKU during a saleLock waits on one stock row, connection pool exhaustedKeep the stock transaction short, and reserve stock before payment, with a timeout to release it. See the lock pile-up lab.
Reports on the primaryCPU spikes at the top of the hour, checkout latency followsMove reports to a replica or a column store.
OFFSET paging in the admin order listPage 1 is fast, page 500 times outPage by key. See paging.
6 · Alternatives

What I considered and did not pick

Cost. Most of the bill is the primary and its standby. A read replica that nobody reads, and reports running on the primary, are the usual waste. See the cost page.

How this page was writtenFrom the engines' documentation and common practice. Measured on real servers: the last item in stock, sold by read-then-write against a conditional update, in the notebooks. Before you build: check the anti-patterns, size it with the capacity calculator, and write your own version from the design doc template. Want a second opinion? Submit it for review.
7 · Where to run it

On-prem, managed, EC2 or Kubernetes

StageWhere it runs
Where I would startManaged relational with a standby in another zone
When it growsCloud-native managed (Aurora, AlloyDB) for read replicas, or self-managed on VMs if the steady bill justifies a team

For a team without a dedicated database team. Who does which job in each option, and the full-cost comparison: Where to run the database.

8 · Estimate it

The numbers, worked live

The back-of-the-envelope numbers I would want before choosing anything. Move the assumptions to match your application. The link keeps your numbers, so a colleague sees the same ones.

Part 3 of 4 · Design · 24 pagesAll pages

Which database does my application need? What kind of application data goes in which database, and why, as design docs, plus the anti-patterns and the decisions behind them.