The Problem#
You open an app at 9 pm and want ice cream, a phone charger and some paracetamol, delivered within the hour. Services like Gopuff, DoorDash (including its DashMart convenience stores), Instacart, Getir, Blinkit, Zepto and Swiggy Instamart make this possible. They stock goods in micro distribution centres (DCs), also called dark stores: small warehouses spread across a city, each close enough to its customers that a courier can deliver within minutes. Restaurant-delivery platforms such as DoorDash and Uber Eats solve a closely related problem in which the "warehouse" is a restaurant kitchen.
The app has to answer two questions, and answer them correctly:
- "What can I get, right now, delivered to where I am?" The answer is the inventory of every DC that can reach the customer within the delivery promise, combined. That is not "within 5 km as the crow flies": a DC across a river with one bridge may be 2 km away and 40 minutes by road.
- "Can I order these five items?" Placing an order must be strongly consistent. If one tub of a particular ice cream is left on the shelf, two customers must not both be told they bought it. Overselling means a courier arrives with an incomplete order, an apology and a refund, which quickly erodes trust.
The shape of the traffic makes this harder:
- Reads dwarf writes. Customers browse a homepage, search, open product pages and fill carts. Availability is queried on every screen, while only a small fraction of sessions end in an order. Availability must be fast (under about 100 ms, because it sits inside search and browse pages) and can tolerate slight staleness.
- Writes need transactions. An order touches several items, and possibly several DCs, and must succeed or fail as a whole.
- Demand is spiky and local. Dinner time, a rainy Friday evening, a big football match, or a heatwave sends demand up several times in specific cities at once.
- The physical world interferes. Items get damaged, misplaced or stolen, and the database count drifts from what is actually on the shelf.
Analogy. Picture a chain of corner shops, each with a stockroom, and a central phone operator. A caller says, "I'm at this address; what can you bring me within an hour?" The operator first works out which shops can reach that address in time, considering bridges, one-way streets and current traffic, not just a ruler on the map. Then they check those shops' stock lists, combine them, and read out the result. When the caller orders, the operator phones the chosen shop and asks the clerk to take the items off the shelf and set them aside right now, all five or none, before confirming, so no other caller can be promised the same tub of ice cream. During the dinner rush the operator keeps a quick-reference sheet of each shop's stock, refreshed every minute, instead of calling every shop for every question. Only the final "set it aside" step always goes to the real stockroom.
This problem is a favourite in interviews because it is small enough to finish in 45 minutes, yet it tests several core skills:
- Distinguishing catalogue items from physical inventory.
- Combining geospatial search with travel-time estimation.
- Getting transactions and locking right for multi-item orders (see Pattern: Dealing with Contention).
- Recognising a classic read-scaling problem and solving it with caches, replicas and region partitioning (see Pattern: Scaling Reads).
At staff level it opens into fulfilment allocation, inventory accuracy, courier dispatch, and surviving demand spikes.
Clarifying Questions#
| Question | Why it matters | Assumed answer |
|---|---|---|
| What is the delivery promise? | Defines "nearby". | Delivery within 1 hour of ordering; travel time from DC to customer must fit within it after picking and packing. |
| What does "available" mean for a customer? | Read semantics. | The union of inventory across all DCs that can deliver to the customer in time, summed per item. |
| Can one order be fulfilled from several DCs? | Ordering complexity. | Assume an order may draw from any serviceable DC; the simplest version fulfils from one DC. We discuss both. |
| How many DCs and items? | Sizing. | About 10,000 DCs and 100,000 catalogue items across them. |
| Order volume? | Write load. | On the order of 10 million orders per day. |
| Latency targets? | Caching and index choices. | Availability under 100 ms (it powers search and browse); ordering can take longer, around a second, as long as it is correct. |
| Consistency? | Locking design. | Ordering is strongly consistent: no two customers get the same physical unit. Availability may be slightly stale. |
| Payments, routing, catalogue search, cancellations? | Scope. | Out of scope for the core; we sketch how they attach. |
| Restaurants or only warehouses? | Variant. | Core design is warehouse inventory (Gopuff-style). We cover the restaurant marketplace variant (DoorDash-style) as a deep dive. |
Requirements#
Functional requirements#
- Query availability: customers can see which items are available to them, deliverable within 1 hour, based on their location. Effective availability is the union of the inventory of all nearby DCs.
- Place orders: customers can order multiple items at once. The order either fully succeeds or fails; it never takes items that are not there.
Below the line:
- Payments and purchases (we show where payment authorisation fits).
- Driver routing and delivery execution (we sketch dispatch).
- Search and catalogue APIs: the system is concerned with availability and ordering, not product search.
- Cancellations and returns.
Non-functional requirements#
- Fast availability: under 100 ms, so it can power search and browse pages.
- Strongly consistent ordering: two customers cannot buy the same physical item.
- Scale: 10,000 DCs, 100,000 catalogue items, about 10 million orders per day, and the read traffic that implies.
- Peak resilience: handle local demand spikes (dinner, weather, events) several times above average.
Below the line: privacy and security, disaster recovery. We touch on both later.
The headline to say out loud: reads are a high-volume, staleness-tolerant, geographically local problem; writes are a low-volume, correctness-critical transactional problem. Design each path for its own needs and keep them coupled only through the inventory data.
Capacity Estimation#
The estimate matters here because it reveals the bottleneck: availability reads, not orders. (See Back-of-the-Envelope Estimation.)
Orders (writes)#
- 10 million orders per day. Using the handy approximation of 100,000 seconds per day (the true value is 86,400; rounding up keeps the maths easy), that is about 100 orders per second on average.
- Demand clusters around lunch and dinner, and around evenings and weekends. A peak factor of 5 to 10 in the busiest hour gives 500 to 1,000 orders per second at peak.
- Each order has about 5 to 10 line items, so peak inventory decrements are about 5,000 to 10,000 row updates per second, spread across 10,000 DCs: about 1 update per DC per second on average, with hot DCs in dense cities perhaps 10 times that. That is easy for a well-provisioned relational database, especially when partitioned by region.
Availability queries (reads)#
Work backwards from orders:
- A purchasing customer views about 10 pages (home, search, category, product, cart) before buying, and each page queries availability.
- Only about 5 percent of sessions convert into an order; the rest are browsing.
- So availability queries ≈ (10M orders / 100,000 s) × 10 pages / 0.05 = 100 × 10 / 0.05 = 20,000 queries per second on average.
- With a peak factor of 3 to 5, that is 60,000 to 100,000 queries per second at peak.
The read:write ratio is around 200:1 per order and higher per inventory row. This is the core scaling problem.
Data sizes#
- DCs: 10,000 rows with id, location, region, hours and capacity. A few MB. Fits in every service's memory.
- Catalogue: 100,000 items with name, description, images and price. Perhaps 1 to 5 KB each without images, so 100 to 500 MB. Images live in object storage behind a CDN.
- Inventory: the theoretical worst case is 10,000 DCs × 100,000 items = 1 billion (DC, item) rows. Real micro-DCs stock a few thousand SKUs each (a small warehouse cannot hold 100,000 different products). With about 5,000 SKUs per DC, we get 50 million inventory rows. At about 50 to 100 bytes per row (DC id, item id, quantity, reserved quantity, version, timestamps), that is 2.5 to 5 GB, plus indexes. Small.
- Orders: 10M per day × about 1 KB (order plus line items) = 10 GB per day, about 3.6 TB per year. This is the only data set that grows meaningfully; old orders move to cheaper storage or an analytics warehouse after a few months.
What the numbers say#
- Inventory is small (single-digit GB) and fits in memory on a single machine. The difficulty is read throughput and transactional correctness, not storage volume.
- Availability reads at 20,000 to 100,000 QPS need caching, read replicas and partitioning. A single primary database would not cope with this alone if each query scans inventory across several DCs.
- Order writes at 500 to 1,000 per second are comfortable for a relational database with careful transaction design, especially when partitioned by region so each region's primary handles only its share.
- Every query is local. A customer in Chicago never needs Boston's inventory. That is the key to partitioning.
Core Entities#
The most important distinction in this problem is Item versus Inventory, like a class versus an instance in object-oriented programming.
- Item: a type of product in the catalogue, such as "Cheetos Flamin' Hot, 8 oz". This is what customers see and care about. It has an id, name, description, price and images.
- Inventory: the physical stock of an item at a specific DC. Either a row per (DC, item) with a quantity, or, in the most literal model, a row per physical unit with a status. Customers never see inventory directly; we sum inventory across nearby DCs to tell them how many of an item they can get.
- DistributionCenter (DC): a physical building where inventory is stored. It has an id, location (latitude and longitude), region, operating hours and capacity. DCs determine which inventory a customer can reach.
- Order: a customer's purchase: customer id, delivery location, status, totals, and the fulfilling DC or DCs. Shipping and billing details attach here.
- OrderItem: a line in an order: item id, quantity, price at purchase time, and the DC it is fulfilled from.
- Customer (supporting): id, addresses, payment methods (handled by a payment system).
A good habit, especially in product-style designs, is to start from the most concrete physical or business things (items, buildings, units on shelves) and work up to more abstract ones (orders, carts, reservations). That keeps you from missing an entity the rest of the design depends on.
API Design#
Two endpoints cover the core requirements: one for availability and one for ordering. (See API Design Best Practices.)
Query availability
GET /v1/availability?lat=41.8781&lng=-87.6298&keyword=ice%20cream&cursor=...&limit=50
→ 200 {
"items": [
{ "item_id": "itm_4411", "name": "Vanilla Bean Ice Cream, 1 pint",
"price_cents": 649, "available_qty": 7, "eta_minutes": 25 },
...
],
"next_cursor": "c_2"
}latandlngidentify where the customer is (or their saved address). Both APIs take location because availability depends entirely on which DCs can reach that point.keywordand category filters narrow results; full catalogue search is out of scope, but a simple filter keeps the API realistic.- Pagination with a cursor keeps responses small: a large DC set might expose thousands of available items.
- Many clients show "in stock" or "only 2 left" rather than exact counts; returning a capped quantity (for example, at most 10) also stops competitors from scraping precise stock levels.
Place an order
POST /v1/orders
Idempotency-Key: 6f1c... // client-generated, per checkout attempt
{
"lat": 41.8781, "lng": -87.6298,
"items": [ { "item_id": "itm_4411", "qty": 2 },
{ "item_id": "itm_0093", "qty": 1 } ],
"payment_method_id": "pm_..."
}
→ 201 { "order_id": "ord_9912", "status": "confirmed", "eta_minutes": 28 }
→ 409 { "error": "insufficient_inventory",
"unavailable": [ { "item_id": "itm_0093", "available_qty": 0 } ] }- The location is passed again because the backend must re-check that the inventory it reserves is at a DC close enough to deliver within the hour. Never trust the client's earlier availability response, which may be stale.
- The idempotency key makes retries safe: a client that times out and retries gets the same order rather than a duplicate (see Idempotency and Safe Retries).
- A 409 with details lets the client tell the customer exactly what went out of stock, instead of a generic failure.
Order status (supporting): GET /v1/orders/{order_id} returns status and ETA; live tracking can be pushed with server-sent events or WebSockets (see Polling, Long Polling, SSE, WebSockets and Webhooks).
High-Level Design#
We start with a design that meets the functional requirements simply, then use the deep dives to meet the non-functional ones: travel time, latency, scale and peaks.
1. Customers can query availability of items#
Availability is a two-step lookup:
- Find the DCs that can deliver to this location within 1 hour. All inventory lives in DCs, so finding the right DCs first means we never have to look at most of the inventory in the system.
- Read the inventory of those DCs, sum it per item, and return the result.
Both steps must be fast, because the whole request has a budget of about 100 ms.
Step 1: a Nearby Service. An internal API takes a latitude and longitude and returns the list of DCs that can serve it. The crudest version keeps a table of DCs with their coordinates and computes distance to the customer: Euclidean distance on latitude and longitude for a very rough answer, or the haversine formula, which accounts for the Earth's curvature. Any DC under a threshold (say 15 km) counts as "nearby". This gives distance as the crow flies, which does not really satisfy "deliverable within 1 hour". We will fix that in deep dive 1 with a travel-time service. Because DCs are buildings that almost never move, the Nearby Service can hold the entire DC list in memory (10,000 rows) and refresh it every few minutes.
Step 2: inventory lookup. With the DC ids in hand, the Availability Service queries the inventory table, joined to the items table for names and prices:
SELECT i.item_id, it.name, it.price_cents, SUM(i.quantity - i.reserved) AS available_qty
FROM inventory i
JOIN items it ON it.item_id = i.item_id
WHERE i.dc_id = ANY(:nearby_dc_ids)
AND i.quantity - i.reserved > 0
GROUP BY i.item_id, it.name, it.price_cents
ORDER BY it.name
LIMIT 50;An index on (dc_id, item_id) makes this a handful of index range scans, one per DC. We use PostgreSQL (see PostgreSQL in Practice) because the ordering path needs ACID transactions, and keeping inventory and orders in one database will pay off shortly.
In many e-commerce systems, the catalogue (item descriptions, images, categories) is stored separately from inventory because the workloads differ: the catalogue is read-mostly, rich and searched with a text engine; inventory is small, numeric and transactional. For this design we keep them in the same database for simplicity, and note that we would ideally split them and add a search index such as Elasticsearch for catalogue search.
Request walkthrough:
- The client calls the Availability Service with the customer's latitude and longitude and any filters.
- The Availability Service calls the Nearby Service with the location.
- The Nearby Service returns the DCs that can deliver to that location.
- The Availability Service queries the database for inventory at those DC ids.
- It sums quantities per item and returns the page to the client.
That meets the availability requirement, apart from travel time and scale, which we fix later.
2. Customers can order items#
Ordering needs strong consistency: we must check inventory, record the order and decrement inventory together, atomically, so no two customers are promised the same unit. Latency matters less here; customers accept a second at checkout far more readily than a slow homepage.
This is the classic double-booking problem that appears in ticketing, hotels and flash sales. Some form of locking or atomic conditional update is required: while one order checks and takes inventory, no other order may take the same units.
Good solution: two data stores with a distributed lock
Keep orders in one database (relational, for rich querying) and inventory in another (a key-value store, for fast counters). To place an order: acquire a distributed lock on each inventory record involved (for example with Redis), create the order record, decrement the inventory, release the locks. (See Distributed Locks.)
The appeal is using the best store for each workload. The problems are nasty failure modes:
- Crash between steps. If the service crashes after creating the order but before decrementing inventory, the next customer can buy the units already promised to the first. You need a sweeper that finds half-finished orders and either completes or reverses them.
- Deadlock. Customer 1 wants items A and B; customer 2 wants B and A. Customer 1 locks A, customer 2 locks B, and each waits forever for the other. You need consistent lock ordering (always lock items in sorted id order) or lock timeouts with retries.
- Lock expiry. A distributed lock with a TTL can expire while its holder is paused (garbage collection, network delay), letting a second process in. Fencing tokens help, but only if the inventory store checks them.
- Two systems to keep consistent, with no shared transaction between them.
It can be made to work, but every one of these failure modes must be handled explicitly.
Great solution: a single PostgreSQL transaction
Put orders and inventory in the same PostgreSQL database and use one ACID transaction. Atomicity means the order and the inventory decrement commit together or not at all. Isolation, via row locks or the SERIALIZABLE level, means two concurrent orders cannot both take the last unit: one of them is rejected and can be retried or reported as out of stock.
The order flow:
- The customer submits an order for items A, B and C to the Orders Service.
- The Orders Service runs a single transaction on the primary (leader) database that:
- checks that A, B and C each have enough available quantity at a serviceable DC;
- fails the whole transaction if any item is short;
- otherwise decrements the inventory for A, B and C (or marks the specific units as ordered);
- inserts a row into
ordersand rows intoorder_items; - commits.
- If the transaction succeeds, the service returns the order. If it fails for lack of stock, the service returns 409 with the items that are short.
The cost: we couple the scaling of orders and inventory in one database, and we cannot pick a specialised store for each. At 1,000 orders per second, partitioned by region, a relational database handles this comfortably, so the simplicity is worth it. As a general rule: when atomicity across two kinds of data is a hard requirement, co-locate that data in one ACID store. Cross-store transactions are possible (sagas, two-phase commit; see Distributed Transactions: 2PC, Sagas and Outbox), but they add complexity that is not the point of this problem.
All-or-nothing is a feature. If one item in an order is out of stock, the whole order fails. That may seem harsh, but succeeding with a partial order can make no sense to the customer: a device without its battery, or burger buns without the burgers. The right response is a clear message ("Vanilla ice cream just sold out; place the rest of the order?") and a one-tap retry without the missing item. Deep dive 3 shows exactly how to write this transaction.
The full high-level design#
Components:
- API Gateway: authentication, rate limiting and routing (see API Gateway and Backend-for-Frontend).
- Availability Service: stateless; resolves serviceable DCs via the Nearby Service, reads the availability cache, falls back to regional read replicas, and sums inventory per item.
- Orders Service: stateless; re-validates serviceable DCs, runs the atomic inventory-and-order transaction on the regional primary, handles payment authorisation and idempotency, and publishes order events.
- Nearby Service: holds all DCs in memory (refreshed every few minutes), prunes candidates by a generous radius, and calls the Travel Time Service for real drive times. Shared by both the read and write paths so they agree on what "nearby" means.
- Travel Time Service: external or internal routing engine that returns drive times, potentially including live traffic. Results are cached (deep dive 1).
- Availability cache (Redis): short-TTL cache of per-DC inventory snapshots or per-location availability pages, invalidated by the Orders Service on writes.
- Regional primary (PostgreSQL): source of truth for inventory and orders, partitioned by region, so each region's writes go to its own primary.
- Regional read replicas: serve availability queries; slight replication lag is acceptable for reads.
- Payment provider: authorises the payment; captured at fulfilment.
- Order events (Kafka): order created, cancelled and fulfilled events for downstream systems.
- Fulfilment: picking at the DC, courier dispatch and delivery tracking (sketched in deep dives 8 and 9).
- DC warehouse systems: receiving, stock counts and adjustments feeding inventory corrections (deep dive 7).
The design has three core services: Availability for reads, Orders for writes, and a shared Nearby Service for DC lookup. A single logical PostgreSQL database holds inventory and orders, partitioned by region. Availability reads go through a cache and read replicas; orders write to the primary with atomic transactions. That is a solid foundation; the deep dives make it accurate, fast and resilient.
Key Flows#
Flow 1: Availability for a location#
- The client calls
GET /v1/availability?lat=..&lng=..with optional filters. - The Availability Service asks the Nearby Service for serviceable DCs. The Nearby Service quantises the location to a small cell (for example an H3 cell about 0.1 km² in area), checks its cache of "cell to serviceable DCs with ETAs", and on a miss prunes candidate DCs by radius and calls the Travel Time Service.
- For each serviceable DC, the Availability Service reads a per-DC inventory snapshot from Redis (
inv:{dc_id}), and on a miss reads from a regional read replica and fills the cache. - It merges the snapshots: per item, the sum of available quantity across DCs, the best ETA, and filters by keyword or category.
- It returns the first page, with capped quantities.
Flow 2: Place an order#
- The client calls
POST /v1/orderswith the location, items and an idempotency key. - The Orders Service checks the idempotency key; if it has already been used, it returns the stored response.
- It asks the Nearby Service for the serviceable DCs (the same logic as reads, so both paths agree).
- It chooses a fulfilling DC (or DCs) that has every item, preferring the fastest ETA (deep dive 2).
- It runs one transaction on the region's primary: conditional decrements of each inventory row, plus inserts into
ordersandorder_items. If any decrement finds insufficient stock, the transaction rolls back and the service tries the next-best DC or returns 409. - After commit, it invalidates the affected per-DC snapshots in Redis and publishes an
order_createdevent (via an outbox row written in the same transaction). - It authorises payment. If authorisation fails, a compensating transaction releases the inventory and marks the order as failed. (Alternatively, authorise first and void on inventory failure; deep dive 3 compares them.)
- It returns 201 with the order id and ETA.
Data Model#
The source of truth is a regional PostgreSQL database holding DCs, items, inventory and orders, partitioned by region (deep dive 5). We need multi-row ACID transactions for ordering and simple indexed range reads for availability. (See Choosing a Database: A Decision Guide and Data Modeling.)
The order side of the model links customers, orders, line items and the DC that fulfils each line.
| Table | Key | Purpose | Notes |
|---|---|---|---|
distribution_centers | dc_id | DC location, region, hours, status | 10,000 rows; cached in memory by the Nearby Service. |
items | item_id | Catalogue | 100,000 rows; ideally a separate catalogue service with a search index. |
inventory | (dc_id, item_id) | Physical stock per DC | About 50M rows; partitioned by region_id; quantity is on-hand, reserved is held by unfulfilled orders; version for optimistic concurrency. |
orders | order_id; unique (customer_id, idempotency_key) | Orders | Partitioned by region_id and by time; about 10 GB per day. |
order_items | (order_id, item_id, dc_id) | Line items | Records which DC fulfils each line. |
outbox | event_id | Events written in the order transaction | Relayed to Kafka (see Change Data Capture and the Outbox Pattern). |
inventory_adjustments | adjustment_id | Audit log of every stock change | Receiving, picks, damage, counts; enables reconciliation. |
Modelling inventory: counters or units?
There are two reasonable models, and it is worth naming both:
- Quantity counters (one row per DC and item, with
quantityandreserved). Compact (50M rows), and an order is one conditionalUPDATEper line. Contention: concurrent orders for the same item at the same DC serialise on that row. At about 1 order per DC per second, that is negligible; a viral item at one DC might see tens per second, which is still fine with short transactions. - Per-unit rows (one row per physical unit, with a status such as available, ordered or picked). Ordering means "select N available units of item X at DC Y and mark them ordered". This mirrors the physical world exactly: units can carry expiry dates, lot numbers and shelf locations, and pickers can be told which unit to grab. But the table is much larger (every unit on every shelf), and selecting units needs
FOR UPDATE SKIP LOCKEDto avoid contention between concurrent orders.
For availability and ordering, counters are the default. Per-unit tracking belongs to the warehouse management system, which feeds adjusted counts back (deep dive 7). Grocery items with expiry dates, or high-value serialised goods such as electronics, are the cases where unit-level allocation at order time is worth the cost.
Why reserved as well as quantity? Between "order placed" and "item picked off the shelf", the unit is still physically on the shelf but promised. Keeping reserved separate means available = quantity - reserved. When the picker scans the item, both quantity and reserved decrement. This separation makes reconciliation with physical counts possible: a cycle count compares quantity with what is on the shelf, regardless of open orders.
Deep Dives#
1. Travel-time filtering: "deliverable within 1 hour", not "within 10 km"#
So far, "nearby" means straight-line distance. But a DC across a river, a mountain, a border or a motorway with no exit may be close on the map and far by road, and traffic changes drive times through the day. Since the requirement is 1 hour of delivery time, we need real travel times. There is a clear progression of solutions.
Bad solution: simple SQL distance
Store DC coordinates in a table and compute distance in the query, Euclidean for a crude answer or haversine for an accurate great-circle distance, with a threshold:
SELECT dc_id FROM distribution_centers
WHERE 6371 * 2 * asin(sqrt(
sin(radians(lat - :lat) / 2) ^ 2 +
cos(radians(:lat)) * cos(radians(lat)) *
sin(radians(lng - :lng) / 2) ^ 2)) < 15; -- kmIt is simple, and with 10,000 DCs it is even fast enough. But it ignores roads, rivers, traffic and time of day. It promises 1-hour delivery from a DC that needs 80 minutes, and hides a DC that is 18 km away along a fast road and could deliver in 25 minutes. Within a city with several DCs, it also cannot tell which of them is actually fastest.
Bad solution: travel-time service against all DCs
DCs are buildings and rarely change, so the Nearby Service can load the whole DC table into memory and refresh it every 5 minutes or so. For each request, it calls a travel-time estimation service (a routing engine such as an internal OSRM or Valhalla deployment, or a commercial API such as Google's Routes API or Mapbox's Matrix API) from the customer's location to every DC.
That fixes accuracy, but the request volume is absurd: 10,000 DCs per query at 20,000 queries per second is 200 million travel-time computations per second, almost all for DCs on other continents that could never deliver within an hour.
Great solution: prune with a radius, then estimate travel time for the candidates
Combine both ideas:
- Keep all DCs in memory, refreshed every few minutes, in a simple spatial index (a geohash grid, an H3 cell map or a k-d tree; with 10,000 points even a linear scan takes only microseconds).
- Prune candidates with a generous straight-line radius: the furthest any vehicle could plausibly travel in the time budget. For 1 hour, that is about 60 miles (about 100 km), the most optimistic distance driveable in an hour. In practice the drive-time budget is smaller than the full hour, because picking and packing take time, so the radius can be tighter.
- Send only the candidates, typically a handful to a few dozen in a city, to the travel-time service as a single matrix request (one origin, many destinations).
- Keep DCs whose estimated travel time plus picking time fits within the delivery promise.
Direction matters. Couriers drive from the DC to the customer, so request travel times in that direction. One-way streets and motorway ramps can make them differ from the reverse direction.
Making it fast and cheap: cache by cell. Twenty thousand matrix calls per second is still a lot for a routing engine, and external APIs charge per element. But travel time depends on where the customer is, not who they are, so:
- Quantise the customer's location to a cell, for example H3 resolution 9 (hexagons of about 0.1 km² with edges of about 175 m) or a geohash of length 7 (about 150 m).
- Cache
cell → [(dc_id, eta_minutes)]with a TTL of a few minutes. A cell is about one city block, and drive times from a DC to anywhere in it differ by a minute or less. - A city like Chicago covers about 600 km², roughly 6,000 H3 resolution-9 cells; realistically only the populated ones get queries. With a 5-minute TTL, each active cell costs one matrix call per 5 minutes: a few thousand matrix calls per 5 minutes per city instead of millions.
Precomputation: isochrones. An isochrone is the area reachable from a point within a given time. Many routing engines can compute isochrone polygons. Compute each DC's 45-minute isochrone for each time-of-day bucket (morning, midday, evening rush, night) and store them as polygons or as sets of H3 cells. Then "which DCs serve this customer?" becomes "which DCs' isochrones contain the customer's cell?", a pure lookup with no routing call on the read path at all. Recompute isochrones every few minutes during rush hours if live traffic matters, or hourly otherwise. This is how many delivery platforms think of delivery zones: precomputed, versioned service areas per store.
Fallbacks. If the travel-time service is slow or down, fall back to cached values, then to the precomputed isochrones, and finally to a conservative straight-line radius (for example 5 km in dense cities). Showing slightly fewer DCs is far better than failing the page. The Nearby Service should have a timeout of a few tens of milliseconds on travel-time calls on the read path.
Same logic on both paths. The Orders Service uses the same Nearby Service. If reads used isochrones and writes used live routing, a customer could see an item and then fail to order it. Using the same function, version and cache keeps the experience consistent. At order time, it is reasonable to use a fresher travel-time estimate because the call rate is 20 to 100 times lower.
How accurate is the estimate? The quoted delivery ETA has three parts: pick-and-pack time at the DC (often a few minutes, but rising when the DC is busy), courier assignment wait, and drive time. Drive time from a routing engine with live traffic is typically accurate within a few minutes over short urban trips. The other two depend on operational load, so production systems often learn the total ETA from history with a model trained on past orders, using drive time as one feature. For the "is it deliverable within an hour?" filter, a conservative estimate with a safety margin is enough.
2. Inventory availability from nearby warehouses#
Once we know the serviceable DCs, "what can this customer get?" is the union of their inventories. That sounds simple, but there are subtleties that separate a good answer from a great one.
Union semantics: summing per item
The simplest definition: available quantity of item X = the sum over serviceable DCs of quantity - reserved. If DC 1 has 3 tubs and DC 2 has 4, the customer sees 7.
But can the customer actually receive 7? Only if the system can fulfil one order from multiple DCs. This is a product decision with real system consequences:
- Single-DC fulfilment (one courier, one pick, cheapest operations): an order must be fully satisfiable by one DC. Then the honest availability for a basket is not the per-item sum; it is whether some single DC has every item in the cart.
- Multi-DC fulfilment (split orders): two couriers, or one courier with two stops. More expensive and slower, but the customer can get everything in the union.
A good compromise, used in some form by many quick-commerce operators:
- Browse and search show per-item availability as the union, possibly with the best ETA per item.
- The cart re-evaluates fulfilment: "Your cart can be delivered from DC 2 in 25 minutes" or "Item B ships separately in 40 minutes."
- Most customers are served by one primary DC (the nearest or fastest), and other DCs act as backup for items that DC is out of.
A worked example: what the union hides
A customer in Chicago's Lincoln Park has three serviceable DCs:
| DC | ETA | Ice cream | Charger | Paracetamol |
|---|---|---|---|---|
| DC 7 | 18 min | 2 | 0 | 5 |
| DC 12 | 27 min | 0 | 3 | 4 |
| DC 31 | 41 min | 6 | 1 | 0 |
The union shows ice cream 8, charger 4, paracetamol 9, and every item looks available. Now the customer puts all three in the cart:
- DC 7 cannot fulfil the basket (no charger).
- DC 12 cannot (no ice cream).
- DC 31 cannot (no paracetamol).
- No single DC has the whole basket. With single-DC fulfilment, the honest answer is "your cart cannot be delivered together". With split fulfilment, DC 7 sends ice cream and paracetamol in 18 minutes and DC 12 sends the charger in 27, using two couriers, or one courier with a pickup at each DC, arriving in perhaps 35 minutes.
The system design consequence: the cart endpoint must run a small basket feasibility check over the serviceable DCs. With 3 to 10 DCs and 5 to 20 items, enumerating single DCs and pairs of DCs is cheap (at most 10 + 45 combinations, each a few lookups in the per-DC snapshots). Choose the cheapest feasible plan that meets the promise: a single DC if possible, else the pair with the best ETA and cost. Show the customer the plan ("arrives in two bags") before checkout, so the order transaction is simply executing a plan they have already accepted. The same feasibility code drives the Orders Service's DC ranking (deep dive 11), so the cart and the checkout agree.
Assigning customers to a primary DC
Many quick-commerce operators simplify drastically: each delivery zone maps to exactly one primary DC. Availability is then just that DC's inventory, ordering always targets that DC, and there is no union to compute. The extra DCs serve only as overflow during outages or peaks. That gives predictable operations (pickers and couriers per DC, one-stop routes) at the cost of hiding items that a slightly farther DC has. The general design in this page supports both: a zone policy decides whether to show the union or the primary DC only.
Computing the union fast
Per request we need, for a few DCs, every in-stock item with its quantity, filtered and paginated. Two good representations:
- Per-DC snapshot in cache. For each DC, store a compact map
item_id → available_qty(a Redis hash, or a serialised blob of 5,000 entries × about 8 bytes ≈ 40 KB). A request fetches 1 to 5 snapshots with oneMGET, merges them in memory (microseconds for a few thousand entries), applies filters, and paginates. This is the workhorse. - Per-cell precomputed union. For hot cells, cache the merged result directly. That is faster, but invalidation fans out: one inventory change at a DC invalidates every cell it serves (perhaps hundreds). So keep per-cell results on a very short TTL, or skip them.
Merging with the catalogue. The availability response needs names, prices and images. Fetch those from an in-process catalogue cache (100,000 items × 1 KB = 100 MB, which fits in every service instance's memory, refreshed from a catalogue change stream). That avoids a join on the hot path.
Displayed quantity versus true quantity
- Low-stock thresholds: if the available quantity is at or below a safety buffer (say 1 unit), show "out of stock". The database count is often slightly wrong (deep dive 7), and showing the last unit invites an order that the picker cannot fulfil.
- Capping: show "10+" rather than exact counts above a threshold. Customers do not need exact numbers, and exact counts leak business data to competitors.
- Hot items during spikes: when an item is selling fast, the cached count is stale within seconds. The read path tolerates this because the write path re-checks atomically; the cost is an occasional 409 at checkout, which the client handles gracefully.
Substitutions
When an ordered item is short at picking time, quick-commerce and grocery apps often offer substitutions (a different brand of the same product) with customer consent captured at checkout. Modelling: a per-line substitution_preference and a category-based substitution graph. It reduces failed orders without loosening the consistency guarantee: a substitution is a new reservation of a different item, done atomically.
3. Consistent order placement: never sell the same unit twice#
This is the correctness core of the problem. We have chosen a single PostgreSQL transaction; now we write it properly and examine the alternatives, isolation levels, deadlocks and retries. (Background: Concurrency Control and Database Locking.)
Option A: conditional atomic decrement (recommended)
For each line item, decrement only if enough stock remains, and check that a row was actually updated:
BEGIN; -- default READ COMMITTED is enough for this pattern
-- lines sorted by item_id to keep lock order consistent
UPDATE inventory
SET reserved = reserved + :qty, version = version + 1
WHERE dc_id = :dc AND item_id = :item_a
AND quantity - reserved >= :qty; -- 1 row = success, 0 rows = short
UPDATE inventory
SET reserved = reserved + :qty, version = version + 1
WHERE dc_id = :dc AND item_id = :item_b
AND quantity - reserved >= :qty;
-- if any UPDATE affected 0 rows: ROLLBACK and report that item
INSERT INTO orders (order_id, customer_id, region_id, status, idempotency_key, ...)
VALUES (:oid, :cust, :region, 'confirmed', :idem, ...);
INSERT INTO order_items (order_id, item_id, dc_id, qty, unit_price_cents)
VALUES (:oid, :item_a, :dc, :qa, :pa), (:oid, :item_b, :dc, :qb, :pb);
INSERT INTO outbox (event_id, type, payload) VALUES (:eid, 'order_created', :json);
COMMIT;Why this is safe even at READ COMMITTED:
- The
UPDATEtakes a row lock on the inventory row. A concurrent transaction updating the same row waits. - When the waiting transaction proceeds, PostgreSQL re-evaluates the
WHEREclause against the newly committed row version. If the first order took the last unit,quantity - reserved >= :qtyis now false, zero rows are updated, and the second order learns the item is short. - There is no window between "check" and "decrement": the check is inside the update.
This is the same idea as a compare-and-set. It handles the most common race, two orders for the last unit, without any explicit locking code and without the overhead of serialisable isolation. A CHECK (quantity >= reserved AND reserved >= 0) constraint on the table adds a belt-and-braces guarantee.
Option B: SELECT ... FOR UPDATE, then check, then update
SELECT item_id, quantity, reserved FROM inventory
WHERE dc_id = :dc AND item_id = ANY(:items)
ORDER BY item_id
FOR UPDATE;
-- application checks each line, then UPDATEs and INSERTs, then COMMITThis is pessimistic locking: lock all the rows first, then decide. It is correct and makes complex decisions (substitutions, choosing among DCs) easy, because the application sees a stable snapshot of locked rows. The cost is holding locks across an application round trip. That is fine for short transactions, and dangerous if the application does slow work (such as calling a payment provider) while holding them.
Option C: SERIALIZABLE isolation
Run the transaction at SERIALIZABLE: read the inventory, check it in the application, update and insert. PostgreSQL's Serializable Snapshot Isolation (SSI; Cahill, Röhm and Fekete, "Serializable Isolation for Snapshot Databases", 2008, implemented in PostgreSQL 9.1 by Ports and Grittner) detects dangerous read-write dependency patterns between concurrent transactions and aborts one with a serialisation failure (SQLSTATE 40001). The application must retry aborted transactions.
- Pros: you can write naive "read, check, write" code and the database guarantees the outcome is equivalent to some serial order. That protects against subtle anomalies the developer did not think of.
- Cons: aborts under contention (hot items at peak) waste work and add latency; retries need care; and SSI tracks predicate locks, which adds overhead.
For this workload, Option A is the sharpest tool: simple, no retries needed for the common race, and minimal lock time. Option C is a valid answer as long as you mention retries on serialisation failures. Option B is useful when the decision logic is complex.
Optimistic concurrency with versions
If inventory lived in a store without multi-row transactions, or if you read inventory in one request and write in another, use the version column: read (available, version), then UPDATE ... SET reserved = reserved + :q, version = version + 1 WHERE dc_id = ? AND item_id = ? AND version = :v. If zero rows are updated, someone else changed the row; re-read and retry. This optimistic approach works well when conflicts are rare, which they are for most items.
Deadlocks and lock ordering
Two orders: one wants A then B, the other wants B then A. Each locks its first row and waits for the other: a deadlock. PostgreSQL detects deadlocks (after deadlock_timeout, 1 second by default) and aborts one transaction, but that is slow and wasteful. Always lock rows in a consistent order, for example by sorting line items by item_id before issuing updates. With a global order there can be no cycle in the waits-for graph, so no deadlock.
Multi-DC orders
If an order is split across two DCs in the same region, they share a primary, so the same single transaction covers both. If two DCs are in different regional databases (rare, near a region border), a single transaction is impossible. Options:
- Avoid it by design: assign each DC to exactly one region partition, and make the order's region the customer's region, so all serviceable DCs for a customer are almost always in one or two partitions (deep dive 5). If two partitions live in one database, one transaction still covers them.
- If not, use a saga: reserve at DC 1, reserve at DC 2, and on failure release DC 1's reservation as a compensating step. Reservations are cheap to undo because they only touch
reserved.
Reservations, payment and timeouts
Where does payment fit? Two orderings:
- Reserve inventory, then authorise payment. Inventory is held briefly; if payment fails, release the reservation (a compensating update). This is the common choice: inventory is the scarcer resource, and authorisation calls take 300 ms to 2 s, during which we must not hold database locks. The reservation is committed first, and payment happens outside the transaction.
- Authorise payment, then reserve. If inventory is short, void the authorisation. Avoids holding inventory for customers whose cards fail, but customers occasionally see a temporary authorisation for an order that never happened.
Either way, never call the payment provider inside the database transaction. Model the order as a small state machine (pending_payment, confirmed, failed, and so on) and, if needed, a durable workflow (see Pattern: Multi-Step Processes and Workflows). If the service crashes between reserving and paying, a sweeper finds orders stuck in pending_payment for more than, say, 2 minutes, and either completes or releases them. That is the same failure mode as the two-store design, but contained in one database and one state machine.
Cart holds. Some products hold inventory while an item sits in the cart. That is attractive for scarce items, but it leaks inventory to abandoned carts. Quick-commerce apps typically reserve only at checkout, because carts are abandoned frequently and stock turns over quickly. If cart holds are needed (limited drops), use short TTL reservations with an expiry sweeper, like ticketing systems.
Idempotency
A customer taps "Place order", the network drops, and the app retries. Without protection, that is two orders and double the inventory taken. The client sends an Idempotency-Key header, unique per checkout attempt. The orders table has a unique constraint on (customer_id, idempotency_key). A retry either finds the existing order and returns it, or collides on the constraint inside the transaction and rolls back its reservations. Store the original response for a few hours for exact replay (see Idempotency and Safe Retries).
4. Making availability fast: caching and read replicas#
At 20,000 queries per second on average and up to 100,000 at peak, each touching several DCs' inventory, the database cannot serve every request directly. Two complementary "great" solutions: a cache in front, and read replicas plus partitioning behind it.
Query inventory through a cache
Add Redis between the Availability Service and the database:
- On each request, look up the cache for the inputs; on a hit, return immediately.
- On a miss, query the database (a replica), write the result into the cache, and return it.
- Set a short TTL, for example 60 seconds, so results stay fresh even if an invalidation is missed.
- The Orders Service invalidates affected entries whenever it changes inventory.
What exactly should the key be? There are two options:
- Key by request (location cell plus filters plus page). It has a high hit rate for identical browsing, but every inventory change affects many keys, which makes invalidation impractical. Rely on the TTL.
- Key by DC (
inv:{dc_id}→ that DC's available quantities). A request reads a few DC snapshots and merges them. An order invalidates (or updates) exactly the DCs it touched, usually one. This is the better default, because invalidation is precise and the merge is cheap.
Write-through updates instead of deletes. Rather than deleting inv:{dc_id} after each order, which makes the next read miss and reload 5,000 rows, update just the changed fields: HINCRBY inv:{dc} {item} -2. Deleting is simpler and always correct; updating in place is more efficient but needs care, because a delayed HINCRBY racing with a reload could double-apply. A good compromise: delete on order, and let one request reload, protected by a short lock so that 500 concurrent requests do not all reload the same snapshot (see Cache Failure Modes: Stampedes, Hot Keys and Penetration).
Hit-rate maths. About 10,000 DCs each with a 40 KB snapshot is 400 MB, so every snapshot fits in a small Redis cluster. Each DC sees perhaps one order per second on average and is invalidated about once a second, while it is read by hundreds of requests per second (a dense-city DC serving many cells). So the hit rate per snapshot is well above 99 percent. Invalidations are frequent, but each costs one reload query.
Staleness is safe here. The cache may claim 1 unit when 0 remain. The customer then hits a 409 at checkout, which the client handles gracefully ("just sold out"). The reverse, the cache showing 0 when 1 remains, loses a sale. Both are bounded by the TTL and invalidation. The invariant that matters, no overselling, is enforced by the write path, never by the cache.
PostgreSQL read replicas and partitioning
Behind the cache:
- Read replicas serve availability queries. Replication lag of tens to hundreds of milliseconds is fine for reads. Orders must go to the primary (leader) because they need the latest state and must lock rows. (See Database Replication.)
- Partition inventory by region so each query touches one or two partitions rather than the whole table (deep dive 5).
- Size the replica fleet to the miss traffic: with a 99 percent cache hit rate, 100,000 peak QPS becomes 1,000 replica queries per second, each reading a few thousand rows from an index. A few replicas per region handle that.
The challenges are operational: keep replica counts matched to traffic, monitor lag, and keep partitions balanced so that no single replica is overloaded by one dense city.
5. Partitioning by region#
Every query in this system is geographically local. A customer in Chicago only ever needs Chicago-area DCs, and an order only ever touches inventory at DCs within an hour's drive. That locality is the most powerful scaling lever in the design. (See Partitioning and Sharding.)
Choosing a region key
Group DCs into regions and give each region an id. A simple, practical choice is the first three digits of the US ZIP code (the ZIP3, which corresponds roughly to a sectional mail-processing centre). There are about 900 ZIP3 areas in the US, and they align reasonably with metropolitan areas. Other countries would use postal-code prefixes or administrative regions. Alternatives:
- Metro areas defined by the business (operations already think in markets such as "Chicago", "Philadelphia").
- Geo cells such as H3 resolution 4 (about 1,770 km² per cell) or S2 level 7 or 8.
Requirements for a good region key:
- A DC belongs to exactly one region.
- A customer's serviceable DCs fall in one region, or at most two when the customer is near a boundary.
- Regions are reasonably balanced in load, or at least can be grouped onto shared hardware when small.
Partitioning inventory and orders
inventoryis partitioned byregion_id(PostgreSQL declarative partitioning, or separate databases per region group). An availability query for a Chicago customer touches only the Chicago partition.ordersis partitioned byregion_id(and by time within a region, for archiving).- Each region group (for example "US Midwest") has its own primary and replicas. Writes for that group go to its primary; other groups are unaffected.
Why this works so well:
- Transactions stay local. All DCs a customer can use are in one region group, so the order transaction runs on a single primary. No distributed transactions.
- Failures are contained. If the Northeast primary fails over, Chicago customers are unaffected.
- Hotspots are isolated. A snowstorm in Boston loads the Northeast group; capacity can be added there.
- Scaling is incremental. A growing metro can be split onto its own group without touching others.
Boundary customers. A customer near the edge of two regions may have serviceable DCs in both. The availability path can read both partitions (two cache lookups, cheap). The order path prefers a single DC, so it normally touches one partition. If an order must span two region groups, use the saga approach from deep dive 3, or forbid cross-group splits and let the order choose the best single group.
Hot regions. Regions are not equal: Manhattan dwarfs a rural ZIP3. Map many small regions onto one database group and give big regions dedicated groups. A lookup table from region id to database group lets you rebalance by moving a region (with a short write freeze or logical replication cutover) without changing application code.
Moving a region to a new database group. Growth eventually forces rebalancing: the Chicago metro outgrows the shared Midwest group and needs its own. Because routing goes through a region-to-group lookup table, the move is an operational procedure rather than a code change:
- Copy. Create the new group and start logical replication of the region's partitions (inventory, open orders, recent orders) from the old primary to the new one. The initial copy takes minutes for a few GB.
- Catch up. Let replication run until the lag is near zero. Reads can already be served from the new group's replicas for testing.
- Freeze writes briefly. Mark the region as "moving" in the routing table. The Orders Service rejects new orders for that region with a retryable error for a few seconds; in-flight transactions finish.
- Final sync and flip. Wait for replication to apply the last changes, verify row counts and checksums, then update the routing table to point the region at the new group. Clear the region's cache entries.
- Unfreeze and clean up. Orders resume against the new primary; client retries succeed. Later, drop the old partitions.
The write freeze is typically a few seconds and can be scheduled in a quiet hour (for quick commerce, early morning). Because every region is independent, the procedure touches only one metro's customers. This is a good illustration of why an indirection layer between logical partitions and physical databases is worth building early: it makes splits, merges and hardware upgrades routine.
Sizing check. With 10 to 30 region groups, each primary sees about 1/20 of peak orders: 25 to 50 orders per second, or a few hundred row updates per second. Each group holds a few hundred MB to a few GB of inventory. That is tiny for PostgreSQL. Partitioning here is about isolation and locality, more than raw capacity.
Citus or a distributed SQL database? Instead of hand-managed groups, a distributed PostgreSQL (Citus) or a distributed SQL database (CockroachDB, YugabyteDB, Spanner) can partition by region_id and keep single-region transactions local while offering cross-region transactions when needed. That is a reasonable choice for teams who prefer the database to manage placement. The design principle is the same: co-locate data that is transacted together.
6. Peak-hour scaling#
Delivery demand is notoriously peaky:
- Daily peaks: lunch and dinner for restaurants; evenings and late nights for convenience delivery.
- Weekly peaks: Friday and Saturday evenings.
- Weather: rain, snow or a heatwave can raise demand sharply in one city within minutes, because people stop going out.
- Events: the Super Bowl, a big match, New Year's Eve; an app-wide promotion or push notification.
A push notification to millions of users can produce a thundering herd of app opens within a minute. The system must survive peaks of perhaps 5 to 10 times average in specific regions, while the physical operation (pickers, couriers) has a fixed capacity per hour.
Scaling the read path
- Stateless services autoscale on CPU and request rate. But autoscaling takes minutes, and a notification spike takes seconds. Pre-scale before known peaks (dinner, scheduled promotions) using last week's traffic curve.
- The cache absorbs the burst. With per-DC snapshots, a spike in browsing hits Redis, not the database. Make sure Redis has headroom, because it is the new bottleneck. Use read replicas of Redis or client-side caching of snapshots for a second or two.
- Request coalescing: when a snapshot expires during a spike, only one request reloads it; others wait briefly or get the stale value (stale-while-revalidate).
- Degrade gracefully: under overload, drop personalised extras (recommendations, "buy it again"), return cached availability with a longer TTL, and serve the homepage from a precomputed per-zone payload.
Scaling the write path
Orders are 100 per second on average and perhaps 1,000 at peak. The database copes, but hot items concentrate contention: a promotion on one product means hundreds of orders per second updating the same (dc_id, item_id) rows.
- Short transactions: the conditional decrement holds a row lock for about a millisecond, so even 500 updates per second on one row is feasible on PostgreSQL. Beyond that, queueing on the lock raises latency.
- Split hot inventory rows: divide one DC's stock of a hot item into several "buckets" (rows) of, say, 10 units each, and have orders pick a random bucket with stock. Contention divides by the number of buckets (see Pattern: Dealing with Contention).
- Redis as a fast gate for flash promotions: pre-load the promotional quantity into Redis and decrement atomically with a Lua script; only orders that win the Redis decrement proceed to the database transaction, which remains the source of truth. This is the flash-sale pattern, and it is only worth the complexity for extreme cases.
Physical capacity: the real bottleneck
The servers are rarely the true limit; pickers and couriers are. If a DC can pick 120 orders per hour and receives 300, accepting them all means 2-hour deliveries and broken promises. So the system needs admission control based on operational capacity:
- Track each DC's current load: orders in the picking queue, available pickers, couriers nearby.
- Feed that into the ETA: as queues grow, the pick-and-pack time grows, and the Nearby Service's "deliverable within 1 hour" filter drops the overloaded DC for some customers, automatically shifting demand to less busy DCs.
- When all DCs in a zone are saturated: show longer ETAs, offer scheduled delivery slots, apply surge delivery fees, or temporarily close the zone with a clear message. Restaurant platforms similarly throttle busy restaurants by extending prep times or pausing them.
This feedback loop is what keeps promises honest during peaks. It connects the technical design (Nearby Service, ETA) with the operational reality.
Capacity planning
Forecast demand per zone per 15 minutes from history plus weather and event calendars, and plan both the server fleet (pre-scaling) and the workforce (picker shifts, courier incentives) from the same forecast. Load-test the read path at 3 times the forecast peak and the order path at the hot-item contention level, not just the average (see Capacity Planning and Load Testing).
7. Keeping inventory in sync with the physical world#
The database says 4 tubs of ice cream; the shelf has 3. One was dropped, one was put on the wrong shelf, one expired, or the delivery from the supplier was short. Inventory accuracy is the quiet killer of quick-commerce: every phantom unit becomes a failed pick, a missing item, a refund and an unhappy customer. The system design must treat inventory as an event stream from the physical world, not just a number decremented by orders.
Sources of inventory change
| Event | Effect | Source |
|---|---|---|
| Receiving (supplier delivery) | quantity += n | DC staff scan inbound pallets |
| Order reserved | reserved += n | Orders Service |
| Picked | quantity -= n, reserved -= n | Picker scans item into the bag |
| Order cancelled before pick | reserved -= n | Orders Service |
| Damage, expiry, theft (shrinkage) | quantity -= n | Staff adjustment |
| Cycle count correction | quantity = counted | Periodic shelf counts |
| Transfer between DCs | -n here, +n there | Operations |
Each change is written as a row in an append-only inventory_adjustments log in the same transaction as the counter update. The log gives auditability ("why did this count change?"), the ability to rebuild counters, and data for loss analysis. In effect the counter is a materialised view of the adjustment log, a light form of event sourcing.
The warehouse management system
DCs run a warehouse management system (WMS) that tracks bins, shelf locations and pick paths. Two common integration styles:
- Our database is the source of truth for available quantity, and the WMS sends adjustment events (received, damaged, counted) through an API or a queue. The Orders Service owns reservations.
- The WMS is the source of truth, and our inventory table is a replica fed by change events. Reservations must then be coordinated with the WMS, which is slower and couples availability latency to an external system.
The first style suits this design: ordering consistency stays in our transactional database, and the WMS reports physical facts.
Idempotent adjustments. WMS events can be delivered twice. Each carries a unique id; the adjustment log has a unique constraint on it, so a duplicate insert fails and the counter is not double-adjusted (see Idempotency and Safe Retries).
Absolute versus relative updates. A cycle count says "there are 3", an absolute value, while a pick says "minus 1", a relative change. Applying an absolute count while picks are in flight can lose or double-count those picks. Resolve it by timestamping the count and applying picks that occurred after the count snapshot on top: quantity = counted - picks_since(count_time).
Safety stock and confidence
Because counts drift, mature systems keep a per-item safety buffer: if available <= buffer, show out of stock. The buffer can be learned per item and DC from historical pick failure rates (how often a picker found the shelf empty when the system said there was stock). Fast-moving, frequently misplaced items get larger buffers. This trades a few lost sales for far fewer failed orders, usually a good trade, because failed orders cost more in refunds, courier time and customer trust than a missed sale.
Pick failures
When a picker cannot find an item:
- They mark it as not found. The system immediately sets
quantityfor that item at that DC to 0 (or to the count of other bins), so no further orders are promised it. - It offers the customer's substitution preference, or removes the line and adjusts the charge.
- It triggers a targeted cycle count for that bin.
- It feeds the pick-failure-rate model.
8. The order lifecycle and fulfilment workflow#
Placing the order is only the start. An order moves through picking, courier assignment, delivery and settlement, with failures possible at each step. Model it explicitly as a state machine stored on the order row, with every transition written atomically along with an outbox event.
Transitions and their side effects:
- PendingPayment to Failed: release the reservations (
reserved -= n) in the same transaction. - Confirmed to Picking: the DC's picking queue assigns the order to a picker; the pick list is ordered by shelf location for a short walk.
- Picking to Packed: each scan converts a reservation into a physical decrement.
- Packed to OutForDelivery: a courier scans the bag. Capture the payment for the final amount (after substitutions).
- Cancelled: before picking, release reservations; after picking, return items to stock with an adjustment.
Durable orchestration. The order workflow spans services (payments, picking, dispatch, notifications) and takes 15 to 60 minutes. A durable workflow engine such as Temporal, or an event-driven saga with an outbox and idempotent consumers, keeps it moving through crashes and retries. Each step is retried with backoff, timeouts trigger compensations (no courier found in 10 minutes: escalate or offer a refund), and the state is always queryable. (See Temporal and Workflow Engines.)
Stuck-order sweeper. Independent of the engine, a periodic job finds orders in a non-terminal state for longer than expected (PendingPayment over 2 minutes, Picking over 20 minutes) and alerts or remediates. This is the safety net that catches bugs in the happy path.
Customer notifications. Each transition emits an event; a notification service pushes "Your order is being packed" and "Your courier is 5 minutes away". Live courier location on a map comes from the courier app's location stream, relayed over server-sent events or WebSockets (see Pattern: Pushing Realtime Updates).
9. Courier dispatch and delivery ETA#
Driver routing is out of scope for the core, but interviewers often ask how the order actually reaches the customer. The design is a cousin of ride-hailing matching, with a twist: the item is ready at a known place and time, and one courier can carry several orders.
Courier location. Couriers' apps send location every few seconds while on shift. Store the latest location in an in-memory geo index (Redis GEO, or H3 buckets keyed by cell) with a short TTL, exactly as ride-hailing does. A few hundred thousand couriers at one update per 4 seconds is tens of thousands of writes per second: a moving-point index, unlike the static DC index.
When to dispatch. Assigning a courier the moment the order is placed wastes courier time if picking takes 8 minutes. Assigning too late makes the bag wait on the shelf. A good policy targets courier arrival ≈ packing completion: estimate the pick-and-pack completion time, estimate each candidate courier's travel time to the DC, and dispatch so that the courier arrives just as the bag is ready. Restaurant delivery has the same problem with food preparation time, and errors are costlier there because food goes cold.
Batching. One courier can carry two or three orders heading in similar directions from the same DC. The dispatcher periodically (every 10 to 30 seconds) solves a small assignment problem over pending orders and available couriers: minimise total lateness and courier time, subject to every order meeting its promise. Batched assignment beats greedy "nearest courier for each order" in total efficiency. DoorDash has written publicly about its dispatch optimisation (internally called DeepRed, per its engineering blog), which combines machine-learned predictions such as prep times and travel times with an optimisation layer. Treat the internal details as theirs; the general shape (predict, then optimise in batches) is standard.
ETA shown to the customer = remaining pick time + courier wait + drive time from DC to customer, updated as the order progresses. Learned models trained on historical deliveries beat summing raw estimates, because they capture systematic effects (apartment buildings take longer to deliver to; certain DCs are slower at dinner).
Proof of delivery and exceptions. Photo on delivery, age verification for restricted items (alcohol, tobacco), and "customer unreachable" flows. Each is a state transition with timeouts in the workflow.
10. The restaurant variant (DoorDash, Uber Eats)#
If the "DCs" are restaurants rather than company-run warehouses, the same skeleton applies, but several assumptions change.
| Aspect | Warehouse delivery (Gopuff) | Restaurant marketplace (DoorDash) |
|---|---|---|
| Inventory | Counted units; strongly consistent decrements | Menus; availability is mostly binary ("86'd" items marked unavailable by staff) |
| Who controls supply | The platform | Independent merchants via a tablet or POS integration |
| Discovery | Union of nearby DC stock | Search and rank nearby restaurants, then their menus |
| Preparation time | Pick and pack, a few minutes | Cooking, 10 to 30 minutes, variable and merchant-dependent |
| Consistency risk | Overselling the last unit | Restaurant closed, too busy, or item unavailable after ordering |
| Order handoff | Internal WMS | Merchant tablet or POS API; merchant must confirm |
Discovery becomes a proximity search. "Restaurants that deliver to me" uses each restaurant's delivery zone (a polygon or set of H3 cells, often derived from drive-time isochrones, as in deep dive 1), indexed so that a customer's point returns the restaurants whose zones contain it. Then search and ranking apply: cuisine, rating, ETA, delivery fee, promotions, personalisation. This is the proximity-service problem with a reversed containment query.
Menu availability. Restaurants mark items unavailable when they run out. That is a write from the merchant tablet that must propagate to search and menus within seconds, typically through CDC into caches and indexes. There is usually no unit counter, so the platform cannot strongly guarantee availability. Instead, the merchant confirms each order (automatically via POS integration, or by a tap on the tablet), and a rejected order is cancelled and refunded quickly. Consistency comes from the confirmation step, not from a counter.
Merchant capacity. A busy kitchen slows down. Platforms adjust prep-time estimates from recent order throughput and can throttle a restaurant (longer quoted times, temporarily hidden from search) to protect delivery promises. This is the same feedback loop as DC load in deep dive 6.
Three-sided marketplace. Customers, merchants and couriers all need apps, and the system balances them: courier supply versus demand per zone (surge pay, delivery fees), merchant visibility, and customer prices. Those are the economics; the system pieces (location streams, dispatch, workflows, notifications) are shared with the warehouse design.
11. Allocation: which DC fulfils an order?#
When several DCs can serve a customer, the choice of DC affects delivery time, cost and future availability. A simple rule: pick the DC with the fastest ETA that can fulfil the whole basket. More sophisticated allocation considers:
- Basket completeness: prefer the DC that has every item; a split order costs a second pick and possibly a second courier.
- Load: a DC with a long pick queue may be nearer but slower in practice (deep dive 6).
- Stock balance: taking the last unit of a fast seller from a DC that serves many customers may be worse than taking it from a DC with plenty; some operators keep per-DC targets to avoid draining one location.
- Cost: courier distance, batching opportunities with other orders from the same DC.
The Orders Service computes a ranked list of candidate DCs (or DC combinations), then tries the conditional decrement transaction on the best candidate. If any line fails (stock went to zero since the read), it tries the next candidate, up to a small limit, before returning 409. The ranking is cheap and in-memory; only the final reservation hits the database.
12. Reliability, failover and disaster recovery#
Disaster recovery is below the line, but a staff-level answer shows how the design degrades.
Regional database primary fails. Each region group has a synchronous standby (or a quorum-replicated cluster) and automatic failover, typically 10 to 60 seconds. During failover, orders in that region fail with retryable errors, and the client retries with the same idempotency key. Availability keeps working from the cache and replicas. Other region groups are unaffected. (See Designing for High Availability and Disaster Recovery and Backups.)
Redis cache cluster fails. Availability falls back to replicas, which must be sized to absorb at least a temporary loss of the cache, or the service sheds load, serving the homepage from precomputed payloads. This is the most dangerous failure for the read path: a 99 percent hit-rate cache hides a 100-fold load increase. Use a replicated Redis setup, spread nodes across zones, and load-test the cache-loss scenario.
Travel-time service degraded. Use cached cell ETAs, then precomputed isochrones, then conservative radii (deep dive 1). Never block the availability page on a routing call.
Payment provider outage. Orders cannot be confirmed. Options: queue orders as PendingPayment for a short window with reservations held, or fail fast with a clear message. A second payment provider for failover is common at scale.
Whole cloud region down. The read path can run in another region from replicated data; the write path needs the region group's primary promoted elsewhere, with replication lag determining the recovery point objective (RPO). Because DCs are physical and local, a regional outage affects customers within that geography, which simplifies blast-radius reasoning: losing US-East affects East Coast deliveries, not West Coast.
Inventory corruption from a bug. The adjustment log allows rebuilding counters: replay adjustments from the last good cycle count. A nightly reconciliation compares counters with the log and flags drift.
Bottlenecks and Failure Modes#
| Failure / hotspot | Impact | Mitigation |
|---|---|---|
| Availability read volume (20k to 100k QPS) | Database overload, slow pages | Per-DC snapshots in Redis, read replicas, region partitioning, in-process catalogue cache |
| Travel-time service latency or outage | Slow or failed availability | Cell-level ETA cache, precomputed isochrones, conservative radius fallback, tight timeouts |
| Two orders for the last unit | Oversell | Conditional decrement in one transaction on the primary; CHECK constraint; never trust cached counts at checkout |
| Deadlocks between multi-item orders | Aborted transactions, latency | Lock rows in sorted item_id order; keep transactions short |
| Hot item during a promotion | Row-lock queueing at one DC | Split stock into bucket rows; Redis gate for flash quantities; short transactions |
| Client retries after timeout | Duplicate orders | Idempotency key with a unique constraint on (customer_id, idempotency_key) |
| Crash between reservation and payment | Inventory held by a dead order | Order state machine, stuck-order sweeper, durable workflow with compensations |
| Phantom inventory (count drift) | Failed picks, refunds | Adjustment log, cycle counts, safety buffers learned from pick-failure rates |
| Regional primary failure | Orders fail in one region | Synchronous standby with fast failover; retries with idempotency; other regions isolated |
| Cache cluster loss | Replicas flooded | Replicated Redis across zones; replicas sized for degraded mode; load shedding |
| Demand spike beyond picker and courier capacity | Broken delivery promises | Load-aware ETA, demand shifting, zone throttling, scheduled slots, surge fees |
| Boundary customers spanning region groups | Cross-database orders | Prefer single-DC fulfilment; saga for rare cross-group splits |
What Interviewers Expect#
Mid-level.
- Separates Item from Inventory and defines DC and Order entities.
- Defines the two APIs (availability by location, place order) and a clean data model.
- Builds both paths: nearby DCs plus inventory lookup for availability, and an order flow that does not double-sell.
- Identifies that ordering needs a transaction or lock, even if the first proposal is not optimal. Discusses the trade-offs when prompted.
Senior.
- Moves quickly through the high-level design to spend time on the critical paths.
- Ordering: a single ACID transaction with conditional decrements or row locks, lock ordering to avoid deadlocks, idempotency, and payment outside the transaction with compensation.
- Availability scaling: estimates around 20k QPS from orders and conversion, then applies per-DC caching with invalidation, read replicas and region partitioning.
- Travel time: radius pruning plus a travel-time matrix, with caching by cell.
- Spots the "trivial" partitioning: all queries are local, so partition by region.
Staff+.
- Goes deep on two or three areas with real-world insight: inventory accuracy and safety stock, load-aware ETAs and admission control at peaks, isochrone precomputation, allocation across DCs.
- Explains how the design fails and degrades: cache loss, routing outage, regional failover, payment outages.
- Connects technical design to operations: pickers and couriers as the real bottleneck, and the feedback loop between load and promised ETAs.
- Discusses the restaurant marketplace variant and how consistency shifts from counters to merchant confirmation.
- Leaves the interviewer with a new perspective, for example on why the availability page should show less than the database says.
Deep Dive: The order transaction in code, with retriesShow
The Orders Service code for the recommended conditional-decrement approach, including DC fallback and error classification. Pseudo-TypeScript against a PostgreSQL client:
async function placeOrder(req: OrderReq): Promise<OrderResult> {
const prior = await findByIdempotencyKey(req.customerId, req.idemKey);
if (prior) return prior; // exact replay
const dcs = await nearby.serviceableDcs(req.lat, req.lng); // ranked by ETA
const lines = [...req.items].sort((a, b) => a.itemId - b.itemId); // lock order
for (const dc of rankForBasket(dcs, lines).slice(0, 3)) {
try {
return await db.tx(async (t) => {
for (const l of lines) {
const r = await t.query(
`UPDATE inventory SET reserved = reserved + $1, version = version + 1
WHERE dc_id = $2 AND item_id = $3 AND quantity - reserved >= $1`,
[l.qty, dc.id, l.itemId]);
if (r.rowCount === 0) throw new Short(l.itemId); // rolls back
}
const orderId = newId();
await t.query(`INSERT INTO orders (...) VALUES (...)`, [orderId /* ... */]);
await t.query(`INSERT INTO order_items (...) VALUES ...`, [/* ... */]);
await t.query(`INSERT INTO outbox (...) VALUES (...)`, [/* order_created */]);
return { orderId, dcId: dc.id, status: "pending_payment" };
});
} catch (e) {
if (e instanceof Short) continue; // try next DC
if (isUniqueViolation(e, "orders_idem")) return findByIdempotencyKey(req.customerId, req.idemKey);
if (isRetryable(e)) { await sleepJitter(); continue; } // 40001, 40P01, failover
throw e;
}
}
return { error: "insufficient_inventory", unavailable: await shortItems(dcs, lines) };
}Points worth explaining in an interview:
- Lock order is fixed by sorting lines by
item_idbefore the loop, so two transactions never wait on each other in a cycle. - Each attempt is a whole transaction. A
Shorton any line rolls back everything, so partial reservations never leak. - Bounded fallback: at most three DCs are tried, so a worst-case checkout touches the database three times, not ten.
- Error classes: serialisation failures (
40001) and deadlocks (40P01) are retryable; a unique-violation on the idempotency constraint means a concurrent retry already succeeded; anything else is a bug and surfaces as a 500. - Payment happens after this returns, outside the transaction, driving the order from
pending_paymenttoconfirmedorfailed(with reservation release).
Transaction duration. With a regional primary in the same data centre (round trip about 0.5 ms) and 5 lines, the transaction is about 8 statements: roughly 4 to 6 ms end to end, holding each inventory row lock for a few milliseconds. Even a hot item at 200 orders per second on one row keeps the lock busy only around 40 to 100 percent of the time in the very worst case. That is the point at which bucket splitting (deep dive 6) becomes worthwhile. Batching the line updates into a single statement (UPDATE ... FROM (VALUES ...) with a returned row count compared with the number of lines) cuts round trips further.
Deep Dive: Travel-time caching and isochrones in numbersShow
The naive cost. 20,000 availability requests per second × 10,000 DCs = 200 million origin-destination pairs per second. Even a fast routing engine computing a one-to-many query in milliseconds cannot sustain this, and commercial matrix APIs bill per element: at fractions of a cent per element, this would cost millions of dollars per day.
After radius pruning. In a dense metro, perhaps 10 DCs fall within 60 miles; in a smaller city, 2 or 3. Call it 10. That is 200,000 elements per second: still large.
After cell caching. Suppose the service covers 300 metros, each with about 3,000 active H3 resolution-9 cells at peak. That is 900,000 active cells. With a 5-minute TTL, each needs one 1×10 matrix call per 5 minutes: 900,000 / 300 s = 3,000 matrix calls per second, or 30,000 elements per second. That is a 6,000-fold reduction from naive and feasible for a self-hosted routing cluster.
With isochrones. For each of 10,000 DCs, compute a 45-minute drive-time isochrone for, say, 6 time-of-day buckets: 60,000 isochrone computations, refreshed hourly: about 17 per second. Each isochrone polygon is rasterised into H3 resolution-9 cells: a 45-minute urban isochrone might cover 300 to 800 km², or 3,000 to 8,000 cells. Store cell → [dc_id, eta] for the current time bucket. The table has around 10,000 DCs × 5,000 cells = 50 million entries, a few GB in Redis or a key-value store. The read path is then one key lookup per request, with no routing calls at all.
Accuracy trade-off. Isochrones per time bucket capture rush-hour patterns but not a sudden accident. Two remedies: refresh the buckets around rush hour more often, and at order time call the live routing engine for the chosen DC only (one call per order, 100 to 1,000 per second), so the promise the customer pays for uses live traffic.
The safety margin. If isochrones say 44 minutes and pick time is 8, the total is 52 minutes, under the hour. But a 10 percent error makes it 57, and a slow courier assignment pushes it over. Production systems include a margin, for example by requiring the 90th percentile ETA, not the mean, to fit the promise. That shrinks each DC's effective zone in exchange for reliable promises.
Haversine and the radius cut. To prune in memory, convert the 60-mile radius to degrees: 60 miles ≈ 96.6 km, about 0.87° of latitude, and 0.87° / cos(latitude) of longitude (about 1.16° at Chicago's 41.9°). Scan DCs in that bounding box, then compute haversine for survivors. With DCs in an in-memory grid keyed by 1° cells, the scan touches a handful of cells and a few dozen DCs: microseconds.
Deep Dive: The 100 ms availability budgetShow
| Step | Time (cache hits) | Time (cache misses) |
|---|---|---|
| Gateway auth and routing | 1 to 3 ms | 1 to 3 ms |
| Nearby Service: cell lookup | 0.5 to 1 ms (Redis) | 20 to 60 ms (travel-time matrix) |
| Per-DC snapshots: one MGET for 1 to 5 DCs | 1 to 2 ms | 10 to 30 ms (replica query per DC, parallel) |
| Merge, filter, paginate in memory | 1 to 3 ms | 1 to 3 ms |
| Catalogue hydration from in-process cache | under 1 ms | under 1 ms |
| Serialise and respond | 1 to 2 ms | 1 to 2 ms |
| Server total | about 5 to 12 ms | about 35 to 100 ms |
The hit path is an order of magnitude inside the budget, and the double-miss path barely fits. That is fine if double misses are rare (well under 1 percent), and it explains why both caches matter: the cell-to-DC cache protects the routing engine, and the per-DC snapshot cache protects the database. Network time to the client is on top and depends on the customer's connection. That is why the budget is usually set for server time, with client time measured separately.
Snapshot size and the merge. A DC snapshot with 5,000 items is about 40 KB raw. Five snapshots is 200 KB over the network from Redis: at 10 Gbit/s that is about 0.16 ms of transfer, plus Redis serialisation time, which dominates. Store snapshots as a compact binary blob (item id and quantity as varints) rather than a Redis hash with 5,000 fields, so one GET returns one value and the client does the parse. The merge is a hash-map sum over 25,000 entries, well under a millisecond.
Pagination over a merged set. Sorting 5,000 to 10,000 merged items by name or popularity per request is cheap (about a millisecond), but you can avoid it: the catalogue order (by category, then popularity) is fixed, so keep snapshots sorted by catalogue rank and do a k-way merge that stops after the page is full.
Deep Dive: Operational maths: pick capacity, queues and safety stockShow
Little's law for a DC. For a stable queue, L = λ × W: the average number of orders in the DC (L) equals the arrival rate (λ) times the average time each spends there (W). If a DC receives 2 orders per minute at dinner and each takes 6 minutes from confirmation to packed, there are on average 12 orders in progress. With 4 pickers each handling one order at a time, that is 3 per picker, so orders wait. Throughput per picker is 1 order per 6 minutes (if 6 minutes is pure pick time), or 0.17 per minute, so 4 pickers can do about 0.67 per minute. Demand of 2 per minute exceeds capacity threefold: the queue grows without bound and ETAs explode.
Queueing intuition. Even below full capacity, waiting time grows sharply as utilisation approaches 100 percent. In the simplest queue model (M/M/1, Poisson arrivals and exponential service times), the average time in system is 1 / (μ − λ), where μ is the service rate. At 50 percent utilisation the wait is 2 × the service time; at 90 percent it is 10 ×; at 95 percent it is 20 ×. Real DCs are multi-server and less random, but the lesson holds: target 70 to 80 percent utilisation of pickers at peak, and feed the current queue length into the ETA so the promise reflects reality.
Admission control from the maths. Given a promise of 60 minutes and an expected drive time of 20 minutes, the pick-and-pack plus courier wait must be under 40 minutes. If the current pick queue implies a 35-minute wait, the DC is near its limit; the Nearby Service should start excluding it for customers at the edge of its zone (where drive time is longest), shrinking the effective zone dynamically. That is the load-aware ETA loop from deep dive 6, made quantitative.
Safety stock for availability display. Let p be the probability that the system's count for an item at a DC is overstated by at least one unit (a phantom unit). If an item shows 1 available and p = 0.15, then 15 percent of orders for it fail at pick time. Showing "out of stock" at 1 unit, when the buffer is 1, loses the sales of genuinely present last units, but avoids those failures. If a failed order costs roughly 5 to 10 times the margin of a sale in refund, courier time and churn, the buffer is worth it whenever p is above about 10 to 15 percent. Estimate p per item and DC from pick-failure history, and set the buffer per item accordingly.
Replenishment. Quick-commerce DCs reorder based on forecast demand over the replenishment lead time, plus safety stock that scales with demand variability (a classic textbook form is z × σ × √L, where z is the service-level factor, σ the daily demand standard deviation and L the lead time in days). It is not on the request path, but it shapes availability: a well-stocked DC shows more items and needs fewer multi-DC splits.
Deep Dive: How real delivery platforms approach thisShow
Public detail is limited; treat these as directional and check the companies' own publications.
- Gopuff runs its own network of micro-fulfilment centres (hundreds, in the US and elsewhere) and owns the inventory, which is exactly the model of this design: availability is the stock of DCs that can reach the customer quickly, and ordering decrements company-owned inventory.
- DoorDash began as a restaurant marketplace and added convenience and grocery, including its own DashMart stores, so it runs both variants in this page. Its engineering blog describes dispatch as an optimisation problem informed by machine-learned predictions of preparation and travel times, and discusses moving from a monolith to microservices as the business grew.
- Instacart fulfils orders from partner retailers' stores, so it does not see exact shelf inventory. It has written about predicting item availability with machine learning: estimating the probability that an item is on the shelf, rather than counting it. That is the extreme version of the safety-stock idea.
- Uber Eats shares geo infrastructure with Uber's ride business, including the H3 hexagonal grid, which Uber open sourced in 2018 and uses for marketplace analytics and zone definitions.
- Routing engines: open-source OSRM, Valhalla and GraphHopper are widely used for self-hosted travel-time and isochrone computation; commercial APIs (Google, Mapbox, HERE, TomTom) provide live traffic.
The common pattern: precomputed delivery zones, cached ETAs, transactional reservations at the store, and dispatch as batch optimisation.
Deep Dive: Failure walkthroughsShow
1. Friday 7 pm, rain in Chicago, demand triples in 15 minutes. Read traffic triples. Per-DC snapshot caches hold, with hit rates unchanged because snapshots are per DC, not per request, and the Availability Service autoscales from pre-warmed headroom. Orders per DC triple; pick queues grow. The load-aware ETA pushes quoted times from 25 to 45 minutes, and edge-of-zone customers stop seeing overloaded DCs. The zone triggers a delivery fee surcharge and courier incentives. Nothing breaks technically; what matters is that promises stay honest.
2. The Midwest primary fails at 7:30 pm.
The standby is promoted in about 30 seconds. In-flight order transactions fail; the app retries with the same idempotency keys, and some succeed on the new primary, others return the existing order. Availability is unaffected (cache and replicas, which reattach to the new primary). The outbox relay resumes from the new primary; events are at-least-once, so consumers deduplicate by event id. Customers see a short spinner. The stuck-order sweeper later finds a few orders left in pending_payment by crashed requests and completes or releases them.
3. The routing engine cluster is overloaded after a map-data deploy. Matrix calls time out. The Nearby Service serves cell ETAs from cache (TTL extended automatically in degraded mode), then isochrone tables. New cells (customers in new areas) fall back to a conservative 5 km radius. An alert fires on fallback rate. Some customers see fewer DCs, and nobody gets a false promise. Rolling back the deploy restores normal operation.
4. A promotion on a popular energy drink at 50 percent off. Hundreds of orders per second target one item at a few dozen DCs. Row locks on those inventory rows queue up and checkout latency climbs to seconds. Mitigation applied: the promoted item's stock is split into 10 bucket rows per DC, so lock contention drops tenfold. The per-customer purchase limit (enforced in the same transaction) prevents one customer clearing a DC. The availability cache for those DCs is invalidated many times per second; request coalescing keeps the reload rate to one per DC per invalidation.
5. Inventory drift after a WMS integration bug double-applies receiving events. Counts rise above reality; pick failures spike for affected items. The pick-failure-rate dashboard flags the DCs. Root cause: missing idempotency on a new event type. Fix: add the unique event-id constraint, then rebuild counters from the adjustment log minus the duplicates, and trigger cycle counts for affected items. Lesson: every integration that writes inventory must be idempotent, and drift metrics must be watched.
Deep Dive: A 45-minute interview planShow
| Minutes | What to do |
|---|---|
| 0 to 5 | Requirements: availability by location within 1 hour (union of nearby DCs); multi-item orders. Non-functional: under 100 ms reads, strongly consistent orders, 10k DCs, 100k items, 10M orders/day. |
| 5 to 8 | Entities: Item versus Inventory (class versus instance), DC, Order, OrderItem. APIs: GET availability with location and pagination; POST order with location and idempotency key. |
| 8 to 18 | HLD: Availability Service, Nearby Service, PostgreSQL with inventory and items; Orders Service with single-transaction ordering; compare the two-store distributed-lock option and its failure modes. |
| 18 to 26 | Deep dive: travel time. Crow-flies, then all-DC routing, then radius pruning plus matrix; cell caching and isochrones. |
| 26 to 36 | Deep dive: scaling availability. Estimate 20k QPS (10 pages / 5 percent conversion), then per-DC cache with invalidation, read replicas, partitioning by region (ZIP3). |
| 36 to 42 | Deep dive: ordering correctness. Conditional decrement, lock ordering, idempotency, payment outside the transaction. |
| 42 to 45 | Peaks and failures: load-aware ETA, hot items, failover. |
Common pitfalls:
- Treating Item and Inventory as the same thing.
- Using straight-line distance as "deliverable within 1 hour".
- Checking stock with a
SELECTand decrementing with a separateUPDATEwithout a lock or condition. - Putting the payment call inside the database transaction.
- Over-engineering storage (sharding by item, NoSQL counters) when the inventory fits in a few GB and every query is regional.
Deep Dive: ObservabilityShow
See Observability: Logs, Metrics and Traces. Key signals:
- Availability: p50, p95 and p99 server latency split by cache hit and miss; cell-to-DC cache hit rate; snapshot hit rate; routing fallback rate; zero-DC rate (customers outside every zone).
- Ordering: order success rate; 409 rate by item (a spike means the availability display is overstating stock); transaction latency; lock waits (
pg_locks,pg_stat_activitywait events); serialisation and deadlock retries; idempotency replays. - Inventory health: pick-failure rate by DC and item; cycle-count discrepancy rate; drift from the adjustment log.
- Operations: pick queue length and age by DC; courier wait time; ETA accuracy (promised versus actual, by percentile); on-time rate.
- Business guardrails: conversion from availability view to order, by zone.
The single most telling metric is 409s at checkout per 1,000 orders: it measures the gap between what the read path promises and what the write path can deliver.
Deep Dive: Variants interviewers ask aboutShow
Scheduled delivery slots. "Deliver tomorrow between 6 and 7 pm." Each slot at each DC has a capacity (orders per slot), and booking a slot is another conditional decrement on a slot_capacity row in the same order transaction. Inventory is reserved at booking time or nearer the slot, with a risk that stock runs out in between. Grocery services typically reserve the slot first and allocate stock closer to fulfilment.
Age-restricted items. Alcohol and tobacco require ID checks at delivery and are not deliverable in some zones or hours. That becomes another availability filter (zone rules, local time) and a delivery-state step (scan ID), not a new architecture.
Multi-merchant baskets. A customer orders from a restaurant and a pharmacy at once. That is two fulfilment legs with separate merchant confirmations and possibly one courier doing two pickups. Model it as a parent order with child orders, each with its own state machine, and a saga that cancels or refunds a leg if the other fails, depending on customer preference.
Price consistency. Prices change (promotions start and end). The order stores unit_price_cents at purchase time, and the transaction checks that the price shown to the customer still holds, or applies the lower one, so customers are not surprised at checkout.
International expansion. Region keys move from ZIP3 to postal prefixes or H3 cells; region groups align with data-residency requirements (EU data in EU regions); routing data and isochrones come from local providers.
Deep Dive: Exactly how a naive checkout oversellsShow
It helps to see the race concretely. Suppose one unit of item A remains at DC 7, and two customers check out at the same moment with this naive code:
SELECT quantity - reserved AS avail FROM inventory WHERE dc_id = 7 AND item_id = 'A';
-- application: if avail >= 1 then
UPDATE inventory SET reserved = reserved + 1 WHERE dc_id = 7 AND item_id = 'A';
INSERT INTO orders ...;
COMMIT;Both transactions read avail = 1 before either wrote. Under READ COMMITTED, the second UPDATE waits for the first to commit and then applies its increment to the new row version. But nothing re-checks the application's earlier decision, so reserved becomes 2 against a quantity of 1. This is a lost-update / write-skew style anomaly: the check and the write were separate operations.
Even REPEATABLE READ does not save the naive code in every database. PostgreSQL at REPEATABLE READ would abort the second transaction with a serialisation error when it tries to update a row changed since its snapshot (good), but MySQL InnoDB at REPEATABLE READ would let the update proceed on the latest version (bad). Relying on isolation-level subtleties across engines is fragile. The robust fixes are the ones from deep dive 3:
- Put the condition in the write (
WHERE quantity - reserved >= 1) and check the affected row count. - Or lock the row before reading (
SELECT ... FOR UPDATE). - Or use SERIALIZABLE and retry on
40001. - And add
CHECK (reserved <= quantity), so even a buggy code path cannot commit an oversell: the database rejects it.
The CHECK constraint is a cheap, last line of defence that turns a silent oversell into a loud error, which is exactly what you want for an invariant this important.
Deep Dive: Cache invalidation races with read replicasShow
The per-DC snapshot cache (deep dive 4) is invalidated by the Orders Service after each commit. A subtle race appears because cache misses are filled from read replicas, which lag the primary:
- Order commits on the primary: item A at DC 7 goes from 3 available to 2.
- Orders Service deletes
inv:7from Redis. - A browsing request misses, reads DC 7 from a replica that is 200 ms behind, sees 3, and writes the stale snapshot back into Redis with a 60-second TTL.
- For the next minute, every customer near DC 7 sees 3 units of A.
This is the classic cache-aside race with replication lag. For inventory, the consequence is bounded (stale counts, an occasional 409 at checkout), but for a fast-selling item near zero, a stale positive count produces a stream of failed checkouts. Remedies, from simplest to most robust:
- Short TTL (for example 10 to 60 seconds): bounds the damage, but does not prevent it.
- Delayed double delete: delete on commit and again after a delay longer than typical replica lag (say 1 second). Simple and effective in practice, but not a guarantee if lag spikes.
- Versioned snapshots: every inventory row carries a
version, and the snapshot records the maximum version or the replica's replay position (the LSN). The Orders Service writesinv:7:min_version = von commit; a reloader refuses to cache a snapshot older than that and reads the primary instead. - CDC-driven invalidation: invalidate (or update) from the replication stream itself, after the change is visible, rather than from the Orders Service. The cache then follows the same ordered log as the replicas, and a stale reload cannot overwrite a newer invalidation.
- Reload from the primary for snapshots invalidated in the last few seconds. The primary handles about 1 reload per DC per second, which is fine at our scale.
The general rule: when caching data read from asynchronous replicas, either tolerate staleness bounded by the TTL, or tie cache freshness to the replication position. For inventory we tolerate a little staleness on the read path because the write path is authoritative, but we add versioning for items near zero, where staleness hurts most (see Cache Eviction and Invalidation and Consistency Models).
Deep Dive: Inventory counters in other storesShow
PostgreSQL is the recommended choice, but interviewers sometimes ask "what if you used DynamoDB or Redis for inventory?" Each can work, with different trade-offs.
DynamoDB. Model inventory with partition key dc_id and sort key item_id (see Amazon DynamoDB in Practice). A single-item decrement is a conditional UpdateItem with ConditionExpression: available >= :q and UpdateExpression: SET available = available - :q. That is an atomic compare-and-set, with no lock. For multi-item orders, TransactWriteItems groups up to 100 conditional writes (a limit that was raised from 25 in 2022) plus the order record into one all-or-nothing transaction. Transactions cost about twice the write capacity of normal writes and fail with TransactionCanceledException on conflicts, which the client retries. This is a solid design if the organisation prefers a managed key-value store and the orders table also lives in DynamoDB. You lose ad hoc SQL for availability queries and the easy joins with the catalogue.
Redis. A Lua script can check and decrement several keys atomically in one round trip, because Redis executes scripts serially. It is extremely fast (tens of thousands of orders per second on one node), which is why flash-sale designs use it as a gate. But Redis is not a durable system of record by default: with asynchronous replication and periodic persistence, a failover can lose recent decrements and resurrect sold units. Use it as a fast first gate in front of a durable store (as in deep dive 6), never as the only record of reservations.
Cassandra and other leaderless stores. Counters in Cassandra are not idempotent (a retried increment may double-apply) and there is no cheap multi-row atomic conditional update. Lightweight transactions (Paxos-based) support single-partition compare-and-set at much higher latency. They are a poor fit for inventory reservations (see Apache Cassandra in Practice).
Separate inventory service with its own store. At very large scale, inventory often becomes its own service owning its database, with orders in another. Then the reservation step is a call to the inventory service ("reserve these lines, idempotency key K, expiring in 10 minutes") and the order is a saga: reserve, create order, pay, confirm or release. The reservation-with-expiry model makes the cross-service flow safe: if the order service dies, reservations expire on their own. Choose this when organisational boundaries or scale demand it; for this problem's scale, one database is simpler and stronger.
Deep Dive: Combining catalogue search with availabilityShow
Search is out of scope, but the availability API has a keyword parameter, and in practice the homepage and search results must show only items the customer can actually get. Combining a text search index with per-DC availability is a common follow-up.
Option 1: search, then filter by availability. Query the catalogue search engine (Elasticsearch, see Elasticsearch and Search Systems) for "ice cream", fetch the top 200 item ids by relevance, intersect with the merged availability of the customer's DCs, and return the first 20 that are in stock. It is simple, and the catalogue index stays independent of inventory. The risk: if most of the top 200 are out of stock locally, you return too few results and need another round with the next 200. That is acceptable when local assortments overlap the catalogue heavily.
Option 2: index availability into the search engine. Add a field in_stock_dcs: [dc_id, ...] to each item document and filter with terms: { in_stock_dcs: [7, 12] }. Search then returns only locally available items in a single query, with relevance ranking intact. The cost: the field must be updated whenever an item goes in or out of stock at a DC. That is a much lower rate than every order (only transitions across zero, or across the safety buffer, matter), so it is feasible: a CDC consumer watches inventory changes and emits an update when available crosses the threshold. Updates are slightly delayed, so the final count still comes from the snapshot cache.
Option 3: per-DC indexes. One small index (or index alias with a routing filter) per DC or per region. That is useful when assortments differ widely per DC, at the cost of many indexes to manage.
Option 2 is the usual answer for quick commerce, because assortments are local and the most frequent searches ("milk", "ice cream", "batteries") must exclude out-of-stock items. The general principle: put the most selective, frequently filtered dimension into the index, and use the cache for the exact, fast-changing numbers.
Production reference. Swiggy's engineering posts on delivery-time prediction, assignment and batching, serviceability, Tile38 geo queries and ML payment routing are studied lesson by lesson in Swiggy's engineering lessons.
Key Takeaways#
- Item versus Inventory is the key modelling distinction: customers see catalogue items, while the system tracks physical stock per DC and sums it across serviceable DCs.
- "Nearby" means drive time, not distance. Prune DCs with a generous radius (about 60 miles for 1 hour), then use a travel-time matrix for the candidates. Cache by location cell, or precompute isochrone delivery zones, so the read path rarely calls the routing engine.
- Ordering is a single ACID transaction: conditional decrements (
quantity - reserved >= qty) on the regional primary, lines locked in sorted order, all-or-nothing, with idempotency keys and payment outside the transaction. - Availability is a read-scaling problem (about 20k QPS from 10M orders/day): per-DC snapshots in Redis with invalidation on orders, read replicas and an in-process catalogue. Cached counts are allowed to be stale because the write path re-checks.
- Partition by region (for example ZIP3): every query is local, transactions stay on one primary, failures and hotspots are isolated, and scaling is incremental.
- Peak-hour scaling is mostly operational. Pickers and couriers are the true bottleneck, so feed DC load into the ETA, shift demand, throttle zones, and split hot inventory rows.
- Inventory accuracy needs an adjustment log, idempotent WMS events, cycle counts and safety buffers, because a phantom unit costs more than a missed sale.
- The restaurant variant keeps the skeleton but swaps counters for merchant confirmation and adds preparation-time prediction and dispatch timing.