Scaling reads
The menu is read sixteen times for every order. Caching it means deciding, part by part, how stale each piece may be, and defending against races, stampedes and cold starts.
A menu page is read about sixteen times for every order placed. At 8:15 pm a biryani restaurant in Hyderabad might have hundreds of people looking at its menu, while its menu changes a few times a week and its “sold out” markers change a few times an evening. Serving every one of those views by asking the database the same questions again is wasteful, and at Dabba’s peak it is more than one database can do.
This chapter designs the menu’s read path. The core move is a cache in front of the database, and most of the work is deciding, piece by piece, how stale each part of the menu may be and what makes a cached copy go away. We will also meet the three ways a cache causes outages: a race that keeps old data alive, a stampede when a hot entry expires, and the cold start when a cache comes back empty.
What a menu view costs without a cache
Building one menu from Postgres means reading the restaurant row, its categories, about 80 items, their option groups (spice level, extra raita, half or full portion) and the current availability of each item. With sensible indexes that is a handful of queries and about 25 ms of database time, producing a JSON document of around 40 KB.
The brief’s design target is 2,000 menu views a second. At 25 ms each, that is 2,000 × 0.025 = 50 seconds of database work every second: about 50 database cores doing nothing but rebuilding menus that have not changed since the last request. The same database also takes orders. If a cache answers 98% of views, only 40 a second reach the database, which is one core’s worth of work.
Two more numbers shape the design. All 50,000 menus at 40 KB each come to about 2 GB, which fits in the memory of one modest cache server. So the cache will never need to evict menus for lack of space; misses will come from entries expiring or being invalidated, and from the cache starting empty. And popularity is skewed: assume the busiest 1% of restaurants receive about 30% of menu views, while thousands of small restaurants see a view every few minutes.
Split the menu by how fast each part changes
A menu is not one piece of data with one freshness requirement. Its parts change at very different rates, and a stale copy of each part causes a different problem. The useful question for each part is: if a customer sees an old value, what happens next?
| Part of the menu | Changes | Tolerable staleness | What a stale copy causes |
|---|---|---|---|
| Names, descriptions, categories, photo links | a few times a week | minutes | a slightly old description |
| Prices | a few times a month | minutes, because checkout re-prices | a PRICE_CHANGED response at checkout |
| Item sold out | many times an evening | about 30 seconds | a cart built around a dish that is gone |
| Restaurant open, busy or closed | several times an evening | about 30 seconds | orders sent to a kitchen that has stopped cooking |
| Offers for this customer | per customer | not in a shared cache at all | one customer’s discount shown to another |
Prices can tolerate minutes only because the API chapter made checkout recompute every price and compare it with the quoted total. That decision is what lets the menu cache be relaxed. Without the server-side check, a stale price would become a wrong charge, and the cache would need to be exact.
The table suggests two cache entries per restaurant. The menu document holds the slow parts (structure, descriptions, prices) and can live for a long time, refreshed when the restaurant edits its menu. A small availability entry holds the sold-out item IDs and the open or closed state, about a hundred bytes, with a 30-second lifetime and an explicit update whenever the kitchen taps “sold out” on its tablet. The menu service reads both and merges them. That costs a second cache lookup per view, which is a fraction of a millisecond, and in exchange a sold-out toggle never forces a 40 KB rebuild. Personal offers are fetched separately for each customer and never put in the shared menu entry.
Cache-aside, and the race it hides
The pattern Dabba uses is cache-aside: the application checks the cache, and on a miss reads the database and puts the result in the cache. When the restaurant edits its menu, the application writes the database and then deletes the cache entry, so the next read rebuilds it.
async function getMenu(restaurantId) {
const cached = await redis.get(`menu:${restaurantId}`)
if (cached) return JSON.parse(cached)
const menu = await buildMenuFromDb(restaurantId) // ~25 ms
await redis.set(`menu:${restaurantId}`, JSON.stringify(menu), { EX: 3600 })
return menu
}
async function updatePrice(itemId, paise) {
await db.updateItemPrice(itemId, paise)
await redis.del(`menu:${restaurantIdOf(itemId)}`)
}This looks correct and is correct most of the time. The problem is an ordering that happens rarely, but at 2,000 views a second, rarely still means regularly.
A reader misses the cache and reads the menu from the database: paneer tikka at ₹240. Before it writes that to the cache, perhaps because its server paused for garbage collection, the restaurant owner changes the price to ₹280. The editor’s code updates the database and deletes the cache entry, which is not there yet, so the delete does nothing. Then the reader resumes and writes its copy, with the old price, into the cache. With a one-hour lifetime, customers now see ₹240 for up to an hour, every checkout fails with PRICE_CHANGED, and the owner, who can see the old price in the customer app, calls support to say the edit did not work.
The lifetime bounds the damage, which is one reason to always set one, even on data that is invalidated explicitly. To remove the race, Dabba gives each menu a version number. Every edit increments menu_version on the restaurant row in the same transaction as the change. The cached document is stored under a key that includes the version it was built from, menu:48213:v17, and a small pointer entry, menuver:48213, records the current version. Readers look up the pointer, then the document. A reader that built a document from version 16 and stored it late stores it under the version-16 key, which no reader asks for once the pointer says 17. The race can still happen; it just no longer matters.
The pointer itself must not go stale forever, so it has a short lifetime, 60 seconds, and on a miss the reader takes the version from the database. If the editor’s process crashes after committing and before updating the pointer, readers see the old version for at most a minute. The cost of the scheme is two dependent cache lookups per view instead of one, about half a millisecond more, and old versions that sit in the cache until their own lifetimes expire. Both are cheap.
Dabba’s menu cache answers 98% of views. At 8:10 pm a botched maintenance restarts the Redis cluster and it comes back empty. What reaches Postgres in the first minute, and what else suffers?
Show the worked answer
All 2,000 views a second now miss. Each costs about 25 ms of database time, so the database is asked for 50 cores’ worth of work instead of one. The primary cannot do that. Queries queue, each one takes longer, and the menu rebuilds take longer still, so more of them overlap. Popular menus are rebuilt dozens of times in parallel, because every request that misses starts its own rebuild.
The worst effect is elsewhere. Orders are written to the same database, so placing an order slows down and starts timing out. A cache problem on the read path has become an outage of the write path, in the dinner peak. The next section covers the defences: menu rebuilds that cannot reach the order database’s primary, a limit on how many rebuilds run at once, one rebuild per key instead of hundreds, and serving slightly stale menus while the cache refills.
Hot restaurants and the stampede
During a cricket final, Dabba features one restaurant on the home banner. Its menu goes from 20 views a second to 1,500. Two separate problems follow.
The first is the hot key. A Redis cluster spreads keys across shards, but a single key lives on one shard. 1,500 reads a second of a 40 KB document is 60 MB a second, about 480 megabits a second, all of it leaving one cache node, on top of everything else that node serves. Adding shards does not help, because the key cannot be split. The fix is a small in-process cache on each menu server that keeps the hottest documents for one or two seconds. With 30 servers each refreshing the key at most once a second, Redis sees about 30 reads a second for it instead of 1,500. Customers may see a menu up to two seconds older, which the table above already allows.
The second is the stampede. At 8:32 pm the restaurant edits its menu, the version changes, and the new document is not in the cache. Every request in the next moments misses. A rebuild normally takes 25 ms, but under load it might take 200 ms, and during those 200 ms about 1,500 × 0.2 = 300 requests arrive, each starting the same rebuild with the same queries against the database. The more rebuilds run, the slower each one gets, and the longer the window during which new requests also miss.
Request coalescing fixes this. On each server, the first request to miss a key starts the rebuild, and every other request for the same key waits for that result instead of starting its own. Go’s singleflight package is a well-known implementation, and it is a few dozen lines in any language. With 30 servers, at most 30 rebuilds run for one key instead of 300. A short lock in Redis can reduce that to one across the fleet, at the cost of another round trip and a lock that must expire if its holder dies.
Better still is to avoid the moment where nothing is cached. Dabba stores each menu entry with a soft expiry inside the value, a little earlier than the real one. A reader that finds an entry past its soft expiry returns the stale copy immediately and starts one background rebuild. Customers get the old menu for a few hundred milliseconds longer, and nobody waits for the database. For entries that are refreshed in bulk, such as all menus warmed after a deploy, the lifetimes get random jitter of a few minutes, so they do not all expire in the same second an hour later.
The cold start from the prediction above needs two more defences. Menu rebuilds read from a replica of the database, never from the primary that takes orders, so a menu storm cannot slow order placement. And each server limits concurrent rebuilds, say to 8; a request that would exceed the limit gets a stale copy if one exists or a quick error if not, which the app retries a moment later. During a cold start that limit means some customers see an error on a menu for a few seconds. Without it, everyone sees a slow app for many minutes and nobody can place an order.
Small restaurants and the arithmetic of hit rate
If an entry lives for T seconds and a key is read r times a second, the cache misses about once per T seconds and serves about r × T reads in that time, so the hit rate for that key is roughly 1 − 1 / (r × T). For a popular restaurant read 10 times a second with a one-hour lifetime, that is 1 − 1 / 36,000, almost perfect. For a small restaurant read once every five minutes with a five-minute lifetime, r × T is 1, and the cache barely helps: nearly every view is a miss.
This is why Dabba invalidates menus on edit rather than relying on short lifetimes. Explicit invalidation lets every menu, popular or not, keep its cache entry for an hour or a day, because staleness is handled by the version change, not by expiry. The long tail of small restaurants then hits the cache too. The overall hit rate depends on the long tail more than intuition suggests, because there are so many small restaurants.
Requests for restaurants that do not exist need handling too. Old shared links, deleted restaurants and scrapers trying random IDs all miss the cache, because there is nothing to cache, and every one of them reaches the database. Caching the absence (“no restaurant 99999”) for a minute closes that path.
Read replicas, and the customer who could not find her order
Menu rebuilds now go to a read replica: a copy of the database that receives the primary’s changes a little later, usually milliseconds, sometimes seconds under heavy write load. For menus that lag does not matter, because the cache is already staler than the replica.
It matters a great deal for a different read. A customer places an order, the order service commits it on the primary and returns its ID, and the app immediately loads GET /orders/9001 to show the tracking screen. If that read goes to a replica that is 300 ms behind, the order does not exist there yet, and the customer sees “Order not found” a second after paying. Restaurant owners hit the same problem when they edit a price and reload their own menu page to see the old one.
The guarantee missing here is called read-your-writes: a client should always see its own changes. One way to provide it is to send reads that follow a recent write by the same user to the primary, for example for 10 seconds after any write. Another is to return the new version number from the write and have the read wait until the replica has caught up to it. Dabba uses the simplest option for orders: reads of a single order by ID go to the primary, and the tracking screen is served from a cache that the order service fills at the moment it creates or changes an order.
That last choice is worth working through, because it reverses an instinct. Order status looks like data that must be fresh, so it seems a poor candidate for caching. But with 42 orders a second at peak and about 35 minutes from order to doorbell, about 42 × 2,100 ≈ 88,000 orders are in progress at once. If each tracking screen asks for status every 10 seconds, that is 8,800 reads a second, more than four times the menu traffic. Each order changes status about six times and is read about 200 times. Writing the new status into the cache as part of every status change (write-through) keeps those reads off the database, and the realtime chapter later replaces the polling with pushed updates.
What should not be cached
Some reads drive decisions where a stale answer produces a wrong action rather than an old display. The idempotency check in the order API must read the database, because a stale “key not found” would create a duplicate order. The payment state during checkout must come from the source, because a stale “unpaid” could charge a customer again. Stock for limited items, covered in the writes chapter, is checked inside the transaction that takes it. For these reads, being correct is the requirement, and a cache adds risk without adding anything the design needs.
A cache is also not worth its cost when hit rates are low: data read once per user, such as a customer’s full order history beyond the first page, or keys so numerous and so rarely repeated that every read is a miss plus a cache write. And a cache is never the record of truth. If losing the cache would lose data, it is a database with weaker guarantees. We should revisit the menu design if the hit rate falls below about 90%, which would mean the invalidation or the key design is wrong, or if the database becomes able to serve menus directly at a cost the team prefers to the operational work of the cache.
The menu document is now cheap to serve from Mumbai. Each menu still comes with 25 dish photos, and the customer may be in Guwahati or Kochi, far from Mumbai. The next chapter, The edge: CDNs and static delivery, moves photos and public menus close to customers and sets the HTTP headers that decide what may be cached there.