Skip to content

Pattern: Scaling Reads

Intermediate 62 min read Part 11 of 18

Serve read-heavy traffic step by step: tune queries and indexes, scale up, add replicas, layer caches and CDNs, precompute views, handle lag and hot keys.

Summary#

Most systems read far more than they write: often 10 reads per write, and 100 or 1,000 for feeds, catalogues, links and media. Scaling reads is the pattern for serving that traffic without overloading the primary database. It is a ladder, and you climb only as far as the numbers force you. First, make each read cheap inside the database with the right indexes, query shapes and some denormalization. Next, scale up to a machine whose memory holds the working set. Then add read replicas and route reads to them, handling replication lag so users still see their own writes. Then put caches in front: in-process, Redis or Memcached, and a CDN at the edge. Finally, precompute expensive answers as materialized views or read models. Along the way you deal with three classic problems. Invalidation keeps cached data fresh. Hot keys are single items that millions of users want at once. Stampedes happen when many requests try to rebuild one expired entry together.

Why It Exists#

Open a photo-sharing app and the first screen needs dozens of posts. Each post needs its image metadata, the author's name and avatar, a like count, the first few comments and whether you have liked it. A naive implementation issues a handful of queries per post, which is more than a hundred database reads to draw one screen. Meanwhile, the person scrolling posts a photo perhaps once a day. One write, thousands of reads by followers, millions of reads across a day for a popular account.

The same imbalance shows up almost everywhere:

  • A short link is created once and clicked thousands of times.
  • A product is listed once and viewed by hundreds of shoppers for every purchase.
  • A video is uploaded once and watched millions of times. Video sites serve billions of views a day against millions of uploads.
  • A concert page is edited a few times and viewed by every fan refreshing it before tickets go on sale.

Read traffic also grows faster than write traffic. Each new user adds a little writing but a lot of reading, because they read other people's content as well as their own, and every new feature adds another query to every page view.

Eventually the database runs into physical limits, not bugs. A core executes a finite number of instructions per second. Memory holds a finite amount of data, and anything that falls out of memory costs a disk read. An SSD performs hundreds of thousands of random reads per second at best, and a network link carries a finite number of bytes. When a single server is at 100% CPU serving well-indexed queries, better code will not save you; you need fewer reads to reach it, cheaper reads, or more machines.

The good news is that reads are the easier half of scaling. A read does not change state, so it can be answered from any up-to-date copy of the data. You can make as many copies as you like: replicas, caches, CDN edges, precomputed views. The hard part is that every copy can be stale, so the real engineering in this pattern is deciding how stale each read may be, and keeping copies fresh enough.

How It Works#

Read scaling is a progression. Each rung adds capacity, and also adds cost and complexity, usually by introducing another copy of the data that can go stale. The skill, both in production and in interviews, is to climb in order and stop at the lowest rung that meets the requirements. Before any of it, you need to know that reads really are the problem.

The rungs are not strictly sequential. A CDN for images is rung 5, yet almost every system starts with one on day one, because it is cheap and solves a different problem. Precomputed feeds, rung 6, are part of the core design of a social network rather than a late optimisation. The ladder is a reasoning order: try the cheap, consistent options first, and justify each layer that adds staleness.

Read-heavy signals#

You know you have a read-scaling problem when the evidence says so, not when the product sounds popular. The signals are:

  • The read-to-write ratio is high. Count queries by type. A ratio of 10:1 is normal for most applications. Beyond 100:1, caching and replication will pay off handsomely, because each copy is updated rarely and read often.
  • Database CPU is high while serving SELECTs. The top queries by total time are reads, and they run thousands of times per second.
  • Latency rises with load, not with data size. p50 is fine at night and poor at peak, which means the server is saturated, not that queries are badly written.
  • The same rows are read again and again. A small number of keys, such as the home page, popular products or celebrity profiles, account for a large share of reads. That is a skewed, cacheable workload.
  • Each page view fans out into many reads. One request triggers tens or hundreds of queries, often through an object-relational mapper (ORM) loading related records one at a time.
  • The working set no longer fits in memory. The buffer cache hit ratio, the share of page reads served from memory, falls below about 99%, and disk read IOPS climb.

Read-heavy signals, in depth#

Estimate before you measure. In an interview, or before a launch, a quick calculation tells you which rung you will need. Suppose 10 million daily active users each load 30 screens a day, and each screen needs 20 reads. That is 6 billion reads a day. A day has about 86,400 seconds, so the average is roughly 70,000 reads per second. Peak traffic is commonly two to five times the average, so plan for 150,000 to 350,000 reads per second. A single well-tuned relational database on a large machine serves perhaps 20,000 to 100,000 simple indexed point reads per second, depending on row size and hardware. So this workload needs either several replicas or a cache in front, and almost certainly both, before you consider anything exotic. If the same users write 5 times a day, that is 50 million writes, about 600 per second on average. The ratio is about 120:1, which is the classic read-heavy shape.

Measure what the database spends its time on. In PostgreSQL, the pg_stat_statements extension records, for each normalised query, how often it runs and how much time it takes in total. Sort by total time, not by mean time: a 2 ms query run 50,000 times per second costs more than a 5 second report run once an hour. MySQL's performance schema and slow query log provide the same view. Look at:

  • Calls per second and total time for the top 20 queries. These are your targets.
  • Rows examined versus rows returned. A query that examines 100,000 rows to return 10 is missing an index.
  • Buffer hits versus reads. Many disk reads for a hot query mean the working set has outgrown memory.
  • Lock waits. Readers waiting on writers point to contention, a different problem with different fixes, covered by Dealing with Contention.

Separate saturation from inefficiency. If CPU is at 90% and every top query is a well-indexed primary-key lookup, the database is efficient but overloaded, and you need more capacity or fewer queries reaching it. If CPU is at 90% because three queries do full table scans, you have a rung 1 problem, and adding replicas would only copy the inefficiency onto more machines.

Know the shape of your key popularity. Read popularity is rarely uniform. Web objects, products and social content usually follow a Zipf-like distribution, where the item ranked k is requested roughly in proportion to 1 / k^s for some s near 1. Under such a distribution, the top 1% of keys can receive half or more of all requests. That is why a cache much smaller than the dataset can absorb most reads. It is also why a few individual keys become dangerously hot.

Rung 1: Optimise inside the database#

The cheapest read is one the database answers by touching a handful of pages. Before adding machines, make every frequent query cheap.

  • Indexes. An index is a sorted structure, usually a B-tree, that maps column values to rows, so the database finds matching rows in a few page reads instead of scanning the table. A lookup by an indexed column in a table of a billion rows takes about four page reads. Without the index it reads the whole table. Add indexes for the columns your hot queries filter, join and sort on. See Database Indexing for how B-trees, hash indexes and specialised indexes work.
  • Better query shapes. Fetch only the columns you need, replace N+1 loops with one query using IN or a join, paginate with a key instead of a large OFFSET, and avoid functions on indexed columns that stop the index from being used.
  • Denormalization. Store data in the shape it is read, even at the cost of duplication. Keep a like_count column on the post instead of counting the likes table on every view. Copy the author's display name onto each post row. Store a JSON document of everything a product page needs. Each duplicated value must be updated on every write, which is the trade-off.
  • Connection pooling. A pooler such as PgBouncer lets thousands of application threads share a few hundred database connections, so the database spends its time on queries rather than on managing connections.

Rung 1, in depth#

Why indexes are so effective. A B-tree page of 8 to 16 KB holds a few hundred keys, so each level of the tree multiplies the number of reachable rows by a few hundred. With a fan-out of 300, three levels address 27 million rows and four levels address 8 billion. The top levels are small and stay in memory, so a point lookup in a billion-row table usually costs one or two actual disk reads, and none if the leaf pages are cached too. A full scan of the same table reads hundreds of gigabytes. Few changes give a thousand-fold improvement; adding the right index regularly does.

Composite and covering indexes. For a query that filters on user_id and sorts by created_at, an index on (user_id, created_at) lets the database jump to that user's rows and read them already in order, so there is no sort step and the query can stop after the first page. The rule of thumb is to put equality columns first, then the range or sort column. A covering index also includes the columns the query returns, using INCLUDE in PostgreSQL or by adding them to the key in MySQL, so the database answers from the index alone without visiting the table. That is an index-only scan. A partial index indexes only rows matching a condition, such as WHERE status = 'active', which keeps it small when queries only ever look at a fraction of the rows.

-- Feed query: latest posts by one author, newest first
CREATE INDEX posts_author_created
  ON posts (author_id, created_at DESC)
  INCLUDE (title, like_count);          -- covering: no table visit needed
 
-- Keyset pagination: cost stays constant however deep the user scrolls
SELECT id, title, like_count, created_at
FROM posts
WHERE author_id = $1
  AND created_at < $2                    -- the last created_at already shown
ORDER BY created_at DESC
LIMIT 20;

Indexes are not free. Every index is updated on every insert and on updates to its columns, so a table with ten indexes turns one logical write into eleven physical ones. Indexes also take memory that the hot data needs. Add indexes for measured hot queries, drop unused ones (PostgreSQL's pg_stat_user_indexes shows scan counts), and remember that a write-heavy table may need the opposite advice, covered in Scaling Writes.

When queries slow down as the dataset grows. A common interview follow-up is: "Your queries were fast at launch, and now they get slower every month. Why, and what do you do?" The usual causes, and their fixes, are:

  • Missing or unusable indexes, which did not matter when the table fitted in memory. Use the plan output (EXPLAIN ANALYZE) to find sequential scans and add the right index.
  • Deep OFFSET pagination. OFFSET 100000 LIMIT 20 reads and discards 100,000 rows. Keyset pagination, as in the snippet above, costs the same at page 5,000 as at page 1.
  • The working set outgrew memory. Queries that used to hit the buffer cache now hit disk, and latency jumps from microseconds to hundreds of microseconds per page. Archive cold data, add memory, or partition.
  • Stale statistics, which lead the planner to choose a bad plan. Analyse tables regularly; autovacuum usually does it, but bulk loads can outpace it.
  • Table and index bloat from updates and deletes in MVCC databases, which leaves dead row versions that scans must step over. Tune vacuum and rebuild bloated indexes.
  • Unbounded growth of a time-ordered table. Partition by time, for example monthly, so queries for recent data touch one small partition, and old partitions can be dropped or moved to cheaper storage.

Denormalization, done deliberately. Normalised schemas avoid duplication so that each fact is updated in one place. Reads then pay for joins. Denormalization moves that cost to writes: when a user likes a post, increment the post's like_count in the same transaction as inserting the like row. When an author changes their display name, update the copies, either in the same transaction or asynchronously if a few seconds of old names are acceptable. Three rules keep denormalization safe. Know which copy is the source of truth. Keep a way to rebuild the copies from it. Prefer copying rarely changing values: author names change rarely, like counts change constantly. For very hot counters, the update itself becomes a write bottleneck, which is the Scaling Writes problem of sharded counters.

The N+1 problem. An ORM that loads 50 posts and then, in a loop, loads each post's author issues 51 queries. At 1 ms each, that is 51 ms of round trips for data one query could return in 2 ms. Fix it with eager loading, which uses a join or a second query with WHERE id IN (...). In a service architecture, use a batching loader, such as the DataLoader pattern in GraphQL servers, which collects all the IDs requested in one tick and fetches them in one call. Fixing N+1 often cuts database query volume by an order of magnitude, which no amount of caching achieves as cleanly.

Rung 2: Scale up#

Vertical scaling means moving the database to a bigger machine: more cores, more memory, faster storage. It is unfashionable and underrated. It changes nothing in the application, keeps strong consistency, and buys a lot of headroom quickly.

  • Memory matters most for reads. If the hot data and indexes fit in RAM, nearly every read is served from the buffer cache, in microseconds. Going from 64 GB to 512 GB can turn a disk-bound database into a memory-bound one.
  • Cores raise concurrency. More cores serve more simultaneous queries, up to the limits of locking and the database's internal latches.
  • Fast storage cuts miss latency. Local NVMe SSDs serve random reads in roughly 100 microseconds, against several milliseconds for network block storage under load or spinning disks.

The limits are real but further away than many people think. Cloud providers rent machines with well over a hundred cores and terabytes of memory, and managed databases run on them. The cost grows faster than linearly at the top end. One machine is still one failure domain, and a single server's network card and storage bandwidth still cap throughput. Scaling up also does not help users far from the data centre, whose latency is dominated by distance.

Rung 2, in depth#

Size memory to the working set, not to the dataset. The working set is the data actually touched in a typical window, say an hour. A 4 TB database where only the last 30 days of orders and the active product catalogue are read may have a working set of 200 GB. Measure it with the buffer cache hit ratio. PostgreSQL's pg_statio_user_tables gives hits and reads per table. If the hit ratio climbs from 95% to 99.9% after an upgrade, disk reads fall fifty-fold.

Why the hit ratio is the number to watch. Suppose a page read from memory costs 0.1 microseconds of copying and a miss costs 200 microseconds on SSD. At a 95% hit ratio, the average page access costs about 10 microseconds, nearly all of it from misses. At 99.9%, it costs about 0.3 microseconds. Small changes in hit ratio near 100% produce large changes in latency and disk load, and the same arithmetic applies to every cache layer later in this pattern.

The economics. An instance with twice the memory and cores typically costs about twice as much, until the largest sizes, where prices climb more steeply. Compare that with engineering time. Adding replicas means routing logic and lag handling. Adding a cache means invalidation logic and a new failure mode. If a bigger instance buys two years of growth for a few thousand dollars a month, it is often the right first answer, especially for a small team. Stack Overflow has described serving a very large site from a small number of powerful SQL Server machines with heavy caching. That is evidence that scaling up goes a long way when queries are efficient.

When to stop scaling up. Move on when the largest sensible machine has less than about a year of headroom at current growth. Move on as well when failover time on one huge machine becomes unacceptable: a cold buffer cache of 1 TB takes many minutes to warm. Or move on when you need read capacity in several regions.

Rung 3: Read replicas#

A read replica is a copy of the database that receives every change from the primary and serves read-only queries. The primary handles all writes and the reads that must be perfectly fresh. Replicas handle everything else. Adding replicas multiplies read capacity: one primary and five replicas give roughly six times the read throughput of the primary alone.

  • How replicas stay current. The primary records every change in its write-ahead log (WAL in PostgreSQL) or binary log (MySQL). Replicas stream that log and apply it. Most read replicas use asynchronous replication: the primary commits without waiting for replicas, so writes stay fast, and replicas trail by a short delay called replication lag. See Replication for synchronous, asynchronous and semi-synchronous modes.
  • Routing reads. The application, a proxy or a driver sends writes to the primary and spreads reads across replicas. Options include separate connection pools in the application, a proxy such as ProxySQL for MySQL or Pgpool-II for PostgreSQL, and managed endpoints such as the Amazon Aurora reader endpoint, which balances across up to 15 Aurora replicas.
  • Bonus benefits. Replicas are also standby copies for failover, places to run backups and reports without loading the primary, and a way to put data in other regions near users.

Rung 3, in depth#

Replicas do not divide the write load. Every replica applies every write. If the primary spends 30% of its capacity on writes, each identical replica also spends about 30% on applying them, leaving 70% for reads. With capacity C per machine and a write share w, total read capacity with r replicas is about (r + 1) × C × (1 − w), counting the primary. When writes are a small share, replicas scale reads almost linearly. When writes approach half the load, each replica adds little, and the right move is to reduce writes or shard, as in Scaling Writes.

Worked numbers. A primary can serve 40,000 reads per second at 70% CPU, which is the safe ceiling for absorbing spikes, and writes take about 10% of its capacity. You need 200,000 reads per second at peak. Each replica, at the same 70% ceiling, serves about 40,000 reads per second after applying writes. Five replicas give 200,000, and you add a sixth so that losing one at peak does not overload the rest. That is N + 1 sizing. Keep the primary for writes and freshness-critical reads only.

What makes replicas fall behind. Replication lag is usually milliseconds within a region, but it spikes for identifiable reasons:

  • Large transactions. A single update of 10 million rows produces a huge log segment that the replica applies after the primary commits, so lag jumps by the time it takes to apply it. Batch big changes into small transactions.
  • Single-threaded apply. Historically, MySQL replicas applied the binary log with one thread, so a primary writing with 32 threads could outrun them. Modern MySQL applies changes in parallel based on write-set dependency tracking. PostgreSQL physical replicas replay the WAL in a single startup process, so replay speed can still be a limit for very write-heavy primaries.
  • Conflicts with long replica queries. On a PostgreSQL hot standby, replaying a vacuum cleanup can conflict with a long-running query on the replica that still needs old row versions. PostgreSQL either cancels the query or pauses replay, controlled by max_standby_streaming_delay, trading query failures against lag. hot_standby_feedback avoids the cancellations at the cost of bloat on the primary.
  • Resource starvation on the replica. A replica overloaded by reads, or with slower disks than the primary, cannot keep up with replay.
  • Cross-region distance. A replica on another continent is at least one round trip behind, roughly 70 to 150 ms, plus apply time.

Lag-aware routing. Monitor lag on every replica, using pg_last_xact_replay_timestamp() or the replay LSN in PostgreSQL, and Seconds_Behind_Source or a heartbeat table in MySQL. A heartbeat table holds a row the primary updates every second; a replica's lag is the current time minus the timestamp it sees. Take replicas out of rotation when lag passes a threshold, such as 5 seconds, and put them back when they catch up. ProxySQL and several drivers can do this automatically. Otherwise a lagging replica quietly serves increasingly stale data.

Replica count limits. Every replica streams the full log from the primary, or from an intermediate replica in a cascading setup, which shields the primary from serving dozens of streams. Aurora avoids per-replica log application on separate storage by having replicas read from the same shared storage volume. Replicas there only update their in-memory caches from the log stream, which is why Aurora replica lag is often reported in tens of milliseconds.

Handling replication lag#

Asynchronous replicas are always slightly behind, so some reads will see old data. Most of the time nobody notices: a product description that is 200 ms old is fine. The cases that matter are the ones where a user notices their own action missing, or sees time go backwards.

  • Read-your-writes. A user updates their profile, the page reloads from a replica that has not received the change yet, and the old profile appears. The user assumes the save failed and tries again.
  • Monotonic reads. A user refreshes twice. The first request goes to an up-to-date replica and shows a new comment, the second to a lagging one where the comment has vanished.
  • Consistent prefix. A reader sees an answer before the question it replies to, because the two rows arrived on different replicas or partitions at different times.

The standard fixes, in increasing precision, are:

  1. Read from the primary for data the user just changed. After a write, route that user's reads of the affected data to the primary for a short window, such as 10 seconds, longer than typical lag. A cookie or session flag records the time of the last write.
  2. Read the user's own data from the primary always. Your own profile, settings and drafts come from the primary, while other people's content comes from replicas. It is simple, and it works when "own data" reads are a small share of traffic.
  3. Pin each user to one replica. Hash the user ID to choose a replica, which gives monotonic reads. If that replica fails, move the user to another and accept one possible step backwards.
  4. Use a replication position token. After a write, the primary returns its log position: an LSN in PostgreSQL, a GTID set in MySQL. The client sends the token with later reads. A replica serves the read only once it has replayed at least that position, otherwise the read waits briefly or goes to the primary. This gives exact read-your-writes with no fixed window.

Handling replication lag, in depth#

The position token in practice. In PostgreSQL, after a write, the application reads pg_current_wal_lsn() on the primary, or the commit's LSN, and stores it in the user's session. On each later read it picks a replica and compares pg_last_wal_replay_lsn() with the token. If the replica is caught up, the read proceeds. If not, the application waits up to a small budget, say 50 ms, or falls back to the primary. MySQL offers WAIT_FOR_EXECUTED_GTID_SET(gtid_set, timeout), which blocks on a replica until the given transactions are applied. Some managed databases expose session-level consistency settings that do this for you.

Cost of each approach. The fixed-window approach sends extra traffic to the primary after every write. For a workload with 1% of users writing in any 10-second window, that is a small fraction of reads. For collaborative or chat apps where almost everyone writes constantly, it can send most reads back to the primary, defeating the replicas. Tokens are precise but need plumbing through sessions, APIs and sometimes between services. If service A writes and service B reads, the token must travel in the request or event between them.

Lag and caches combine. If a cache is filled from a lagging replica right after an invalidation, it stores the old value until the next invalidation or TTL. This is one of the main sources of long-lived stale data. The fixes are to fill the cache from the primary for recently changed keys, to delay or repeat invalidation by more than the maximum lag, or to drive invalidation from the replication stream itself, covered in the invalidation section below.

Synchronous replicas as a different answer. You can make a replica synchronous, so the primary waits for it to confirm each commit. Reads from that replica are then current up to replay timing, but every write pays a round trip, and the replica's failure blocks writes unless you fall back to asynchronous. Synchronous replication is mainly a durability tool. Quorum systems, covered in Quorums and Leaderless Replication, offer a third option: read from enough replicas that at least one has the latest write.

Rung 3b: Sharding for reads#

Replication copies the whole dataset to every replica. When the dataset itself no longer fits on one machine, or the writes that every replica must apply become too heavy, you shard: split the data by a key so each shard holds a subset, with its own primary and replicas. See Partitioning and Sharding.

For reads, sharding helps in two ways. Each shard's working set is smaller, so more of it fits in memory, and read capacity grows with the number of shards. Geographic sharding also puts each user's data near them. But sharding only helps reads that include the shard key. A query for "posts by user 42" goes to one shard if posts are sharded by user. A query for "all posts tagged #travel" must be sent to every shard and the results merged, which is a scatter-gather read. Its latency is set by the slowest shard, and its cost grows with the number of shards.

Sharding for reads, in depth#

Tail latency of scatter-gather. If each shard answers within 10 ms 99% of the time, a query that waits for 100 shards finishes within 10 ms only 0.99^100, about 37%, of the time. Most such queries see at least one shard's slow tail. This is the "tail at scale" effect described by Jeffrey Dean and Luiz André Barroso (Communications of the ACM, 2013). Mitigations include hedged requests, which send a duplicate request to another replica if the first is slow; returning partial results when a few shards miss the deadline; and, best of all, building a secondary index or read model keyed by the other access pattern, such as a tag-to-posts table, so the query hits one place.

Choose the shard key for the dominant read. Read-heavy systems should shard by the key that most reads include: user ID for user-centric apps, tenant ID for business software, short code for a URL shortener. Then build separate, denormalized read models for the secondary access patterns, populated asynchronously by change data capture. This is the same idea as rung 6.

Rung 4: Cache layers#

A cache keeps recently or frequently read results in fast memory, so repeat reads skip the database entirely. Redis and Memcached answer a key lookup in well under a millisecond inside a data centre, and a single node handles 100,000 or more simple operations per second. A relational database spends milliseconds on the same lookup once you count parsing, planning and locking. For read-heavy data, a cache in front of the database is the single largest multiplier of read capacity. See Caching Strategies for the full catalogue of patterns.

  • Cache-aside, also called lazy loading, is the default. The application checks the cache. On a miss it reads the database, stores the result with a time to live (TTL) and returns it. On a write it updates the database and then deletes the cache entry. Only data that is actually requested gets cached, and a cache failure degrades to slower reads rather than errors.
  • Read-through caches hide the database behind the cache. The cache library or service loads missing entries itself, so application code only talks to the cache. DynamoDB Accelerator (DAX) works this way for DynamoDB.
  • Write-through updates the cache and the database together on every write, so the cache is never missing recently written keys, at the cost of caching data that may never be read.
  • In-process caches live inside each application server's memory, using libraries such as Caffeine for Java or simple LRU maps. They are the fastest, because there is no network hop, but each server has its own copy, so invalidating them is harder and they hold less.
  • Distributed caches such as Redis and Memcached are shared by all servers, hold much more, and give one place to invalidate. They cost a network round trip of a few hundred microseconds.

The usual production shape is two-tier: a small in-process cache with a very short TTL, such as 1 to 10 seconds, in front of a large shared Redis or Memcached cluster, in front of replicas, in front of the primary.

Cache layers, in depth#

Hit ratio is the lever. If a cache hit costs 0.5 ms and a miss costs 0.5 ms plus a 10 ms database query, the average latency is 0.5 + (1 − h) × 10 ms for hit ratio h. More important for capacity, the load on the database is (1 − h) × total reads. At 100,000 reads per second:

Hit ratioReads reaching the databaseAverage latency
80%20,000 per second2.5 ms
90%10,000 per second1.5 ms
99%1,000 per second0.6 ms
99.9%100 per second0.51 ms

Going from 90% to 99% cuts database load tenfold. That is why so much effort goes into the last few percent: more memory, better keys, longer TTLs where staleness is acceptable, and warming caches before traffic arrives.

What to cache, and at what granularity. Cache the result the caller needs, not raw rows, when the result is expensive to assemble: a rendered product summary, a list of IDs for a feed page, a permission set. Cache individual objects when many different results share them: a user object used by every post that user wrote. Object caching makes invalidation simple, one key per row, and the results that use the object are assembled from several cache reads. Many systems combine both: a cached list of 50 post IDs plus one cached object per post, fetched in a single multi-get.

Key design. Use structured keys such as user:42:profile:v3. The version suffix lets you change the cached format by bumping the version, rather than flushing the cache. Include everything that changes the result, such as locale, currency or experiment group, or you will serve one user's variant to another. Never include data that varies per request but not per result, such as a timestamp, or nothing will ever hit.

Choosing a TTL. The TTL is the maximum staleness you will tolerate if invalidation fails, and it also bounds how much memory cold data takes. Product descriptions might take an hour, prices a minute, stock levels a few seconds or no cache at all. Add jitter, a random spread of perhaps 10%, so that keys written together do not all expire together.

Negative caching. Cache "not found" results too, briefly, such as for 30 to 60 seconds. Otherwise requests for missing keys, whether from bugs, scrapers or attacks, all fall through to the database. A Bloom filter of existing keys is an alternative for very large key spaces; see Probabilistic Data Structures.

Memcached or Redis. Memcached is a simple, multi-threaded key-value cache that scales well per node and suits plain object caching. Redis adds data structures, such as sorted sets for leaderboards, hashes, lists and streams, plus replication, persistence options and Lua scripting, which makes it the more common default today. Both shard keys across nodes with client-side consistent hashing or, in Redis Cluster, 16,384 hash slots. See Distributed Caching.

Cache invalidation when updates must be visible#

Caches serve old data until an entry expires or is removed. For many reads, a TTL of a few minutes is fine. Some updates must be visible immediately: a user changes a privacy setting, a seller corrects a price, an admin bans an account. For these, you must invalidate the cached copy when the data changes, and do it in a way that cannot leave a stale value behind.

The main techniques are:

  • Delete on write. After committing the database change, delete the cache key. The next read misses and reloads the new value. Delete rather than update, because concurrent updates applied in the wrong order would leave the wrong value, while a delete is safe to repeat.
  • Write-through. Write the new value to the cache as part of the write path. Readers see it at once, but you must handle failures between the database write and the cache write.
  • Change-data-capture invalidation. A consumer reads the database's change stream, through Change Data Capture tools such as Debezium, and deletes or refreshes affected keys. Every committed change is seen, including changes made by scripts and other services, and deletes can be retried until they succeed.
  • Versioned keys. Store a version number per entity, such as in the row or a small key, and include it in cache keys. A write bumps the version, so readers immediately look up a new key, and old entries simply expire.
  • Short TTLs for the rest. Even with invalidation, keep a TTL as a safety net, so any missed invalidation heals itself.

Cache invalidation, in depth#

The stale-set race. Cache-aside with delete-on-write has a well-known race. A reader misses the cache and reads the old value from the database. Before it writes that value into the cache, a writer updates the database and deletes the key. Then the reader's delayed set lands, and the cache holds the old value until the TTL expires. With replicas, the window is wider, because the reader may read from a lagging replica after the delete.

Leases fix the race. Facebook's memcache paper, "Scaling Memcache at Facebook" by Rajesh Nishtala and colleagues (NSDI 2013), describes leases. On a miss, the cache gives the client a lease token. A later set is accepted only with a valid token, and a delete of that key invalidates outstanding tokens. In the race above, the writer's delete voids the reader's lease, so the stale set is rejected. The same mechanism limits thundering herds: the cache hands out a lease for a key only once every few seconds, and other clients that miss are told to wait briefly and retry, by which time the leaseholder has filled the key. Redis has no built-in leases, but you can build one with SET key token NX PX and a compare-and-set script.

Delayed double delete. A simpler, approximate fix is to delete the key after the write, then delete it again after a delay longer than the worst read-and-fill time plus replica lag, such as one second. Any stale value set in between is removed by the second delete. It narrows the window rather than closing it, but it is easy to add.

Invalidation from the commit log. Facebook's memcache system ran daemons that tailed the MySQL commit log and broadcast deletes for the keys each committed transaction affected. Driving invalidation from the log has three strong properties. A delete is generated only after the commit, so it cannot precede the data. Deletes can be replayed after a crash, because the log is durable. And they reach every region's caches, because the log is replicated. The modern equivalent is a CDC pipeline into Kafka with an invalidation consumer per cache cluster.

Visibility for the writer versus everyone. Often only the person who made a change needs to see it instantly. Everyone else can tolerate seconds. Then the simplest fix is to bypass the cache, or read from the primary, for the writer's own next reads, and let invalidation catch up for others. Facebook's paper describes a similar idea across regions: a remote marker set during a write in a non-primary region tells later reads from that user to go to the primary region until replication catches up.

Consistency budgets add up. A read that passes through a CDN with a 60-second TTL, a cache with 5-second invalidation delay and a replica with 1-second lag can be up to about 66 seconds stale in the worst case. Write down the staleness budget for each kind of data and check that the layers you add fit within it.

Hot keys: millions of reads for the same data#

A cache spreads keys across nodes, so most of the time load is even. But a single key always lives on one node, and some keys are wildly popular: a celebrity's profile, the home page, a breaking news story, the ticket page for a sold-out tour. If 1 million requests per second ask for one key, and one Redis node serves about 100,000 to 200,000 operations per second, that node melts while the rest of the cluster idles. Adding more cache nodes does not help, because they do not share the key.

The fixes all spread one key's reads over many places:

  • In-process caching of hot keys. Each application server keeps hot keys in local memory for a second or a few. With 500 application servers and a 1-second local TTL, the cache cluster sees at most about 500 reads per second for the key, however many users ask.
  • Key replication. Store copies of the hot key under several names, such as post:9:copy0 to post:9:copy15, on different nodes. Readers pick a copy at random, which divides the load by 16. Writers update or delete all copies.
  • Read replicas of cache nodes. Redis replicas of the shard holding the key can serve reads, if slightly stale reads are acceptable.
  • Request coalescing. At each layer, CDN, proxy and application, many concurrent requests for the same key are merged into one request downstream, and the single answer is shared by all of them.
  • Push the content to the edge. If the hot content is public, a CDN with a short TTL absorbs the load at hundreds of edge locations, and the origin sees a trickle.

Hot keys, in depth#

Detecting hot keys. You cannot fix keys you do not know about. Options include sampling requests at the application and counting keys with a heavy-hitters algorithm such as the Count-Min Sketch or Space-Saving, which find the top keys in small memory; see Probabilistic Data Structures. Redis's redis-cli --hotkeys scans for frequently used keys when an LFU eviction policy is configured. Cache proxies and client libraries can also export per-key counters for the busiest keys. Dynamic systems detect hot keys in real time and automatically promote them to local caching or replicated copies, then demote them when they cool.

Worked numbers. A sports app expects 2 million reads per second for the live score of a final at peak, from 800 application servers. Without protection, all 2 million requests hit one Redis shard, ten times its capacity. With a 1-second local cache per server, each server fetches the key once per second: 800 reads per second to Redis, well within one node, and every user sees a score at most about one second old. If the score must be fresher, a 200 ms local TTL gives 4,000 reads per second, still easy. If clients poll, a CDN in front with a 1-second TTL removes even the application load, and pushing updates over SSE or WebSockets removes polling altogether; see Pushing Realtime Updates.

Hot keys in the database too. The same skew hits databases. A single row read 50,000 times a second, such as a global configuration row, can bottleneck on the row's page latch even when it is in memory. Caching it in-process with a short TTL is the fix. For hot writes to a single row, such as a like counter on a viral post, the problem moves to Scaling Writes.

Cache stampedes: many requests rebuilding one entry#

When a popular entry expires, every request that arrives before it is refilled misses. If the key gets 10,000 requests per second and rebuilding it takes 200 ms, about 2,000 requests run the same expensive query at once, which can push the database over the edge. This is a cache stampede, or thundering herd. The same thing happens at scale when a cache node restarts empty, which is a cold cache. Cache Failure Modes covers these in full. The core defences are:

  • Request coalescing (single flight). Within a server, the first request for a missing key starts the load, and concurrent requests for the same key wait for that result instead of starting their own. Across servers, a short lock in the cache (SET lock:key token NX PX 5000) lets one server rebuild while others serve the stale value or wait briefly.
  • Serve stale while revalidating. Store a soft expiry inside the value, before the hard TTL. After the soft expiry, the first reader triggers a background refresh while everyone keeps getting the slightly old value. Users never see a miss.
  • Probabilistic early expiration. Each reader refreshes the value early with a probability that rises as expiry approaches, so on a busy key, one reader refreshes a little before expiry and the herd never forms.
  • Background refresh for known hot keys. A job recomputes the home page every 30 seconds and writes it to the cache. Readers never compute it at all.
  • TTL jitter and cache warming. Spread expiries so keys do not expire together, and preload hot keys into a new or restarted cache before sending it traffic.

Cache stampedes, in depth#

The XFetch rule. Andrea Vattani, Flavio Chierichetti and Keegan Lowenstein analysed probabilistic early recomputation in "Optimal Probabilistic Cache Stampede Prevention" (PVLDB, 2015). Store with each value the time delta that the last recomputation took. On each read, recompute early if now − delta × beta × ln(random()) ≥ expiry, where random() is uniform in (0, 1] and beta is a tuning constant, 1 by default. Because ln(random()) is negative, the left side is "now plus a random amount proportional to the recompute time". Readers refresh more often as expiry nears, and keys that are expensive to recompute start refreshing earlier. The paper shows this exponential rule is optimal in a precise sense, and it needs no locks or coordination.

Why coalescing needs a timeout. If the request doing the load hangs, every waiter hangs too. Give the loader a deadline. If it is exceeded, waiters either fail fast or serve the stale value, and the lock expires so another request can try. Coalescing also concentrates failure: one bad load result is shared by every waiter, so do not cache errors as values, or cache them only very briefly.

Coalescing at every layer. Varnish and most CDNs collapse concurrent misses for the same URL into one origin fetch. Nginx does it with proxy_cache_lock. Application-level coalescing protects the cache and database. Check that every layer collapses misses, or the herd simply moves down a level.

Rung 5: CDN and edge caching#

A content delivery network (CDN) is a network of caching servers in hundreds of locations worldwide, called points of presence (PoPs). Users connect to a nearby edge, and the edge serves cached responses or fetches them from your origin. A CDN cuts read load on your servers to the cache misses, and it cuts latency from a cross-continent round trip of 150 ms or more to the 10 to 30 ms of a nearby edge. See CDN for how CDNs route users and store content.

CDNs are not only for images and JavaScript. They can cache any response that many users share:

  • Static assets: images, video segments, scripts, stylesheets, fonts. Cache them for a long time with a content hash in the file name, so a new version is a new URL and nothing needs purging.
  • Public pages and API responses: a product page, an event listing, a news article, a public profile, search results for common queries. Even a TTL of a few seconds absorbs enormous load on a popular URL.
  • Personalised pages, split. A page mixes public content, such as the product, with private content, such as the cart count. Cache the public shell or API response at the edge and fetch the small private part separately, from the browser or by edge composition.

Caching is controlled by HTTP headers that your origin sets. Cache-Control: public, max-age=60 lets browsers and CDNs cache for 60 seconds. s-maxage sets a separate lifetime for shared caches such as CDNs. stale-while-revalidate lets the edge serve the old copy while it refreshes in the background, and stale-if-error lets it serve the old copy when the origin is down. The cache key usually includes the host, path and query string, and can be extended by Vary headers. Keep keys tight: a Vary: Cookie header makes every user's response unique and destroys the hit ratio.

CDN and edge caching, in depth#

Purging. When content changes before its TTL, you purge it. CDNs support purging single URLs, and many support purging by tag: the origin labels responses with tags such as product-42 in a header, and one API call purges every cached response carrying that tag. Fastly calls these surrogate keys and Cloudflare calls them cache tags. Purge latency is typically seconds across the network, which is fast enough for corrections but not for strong consistency. A common design uses long TTLs plus tag purges triggered by the same change events that invalidate the application cache.

Tiered caching and origin shields. With 300 edges each missing independently, a newly popular URL can cause 300 origin fetches. Tiered caching routes edge misses through a few regional mid-tier caches, sometimes a single designated origin shield, so the origin sees one fetch per object per tier. Combined with request collapsing, this keeps origin load low even during sudden spikes.

Edge hit ratio maths. Suppose a news site serves 500,000 requests per second globally and achieves a 95% edge hit ratio. The origin sees 25,000 requests per second. Raising the hit ratio to 99% through longer TTLs on articles, removing tracking parameters from cache keys and tiered caching cuts origin traffic to 5,000 per second: one fifth of the servers. As with application caches, the last few percent of hit ratio are worth the most.

Normalise what you can. Strip marketing and tracking query parameters from the cache key, sort parameters, lowercase where safe, and serve the same response to all users of a locale rather than varying on full headers. Each unnecessary variation in the key multiplies the number of distinct cached objects and lowers the hit ratio.

Edge compute. Platforms such as Cloudflare Workers, Fastly Compute and CloudFront Functions run small functions at the edge. They can assemble pages from cached fragments, verify tokens and choose variants, so more responses can be served at the edge without reaching the origin. They are discussed with Serverless.

The Ticketmaster-style case. Before a major on-sale, millions of fans refresh the event page. The event description, venue map and price ranges are identical for everyone and change rarely, so they are served from the CDN with a short TTL and purged when an admin edits them. Only seat availability and the purchase itself reach the origin, and those are protected by a waiting room and contention controls; see Dealing with Contention.

Rung 6: Materialized views and precomputed reads#

Some reads are expensive no matter how fast the storage: a dashboard that aggregates millions of rows, a feed that merges posts from hundreds of followed accounts, a leaderboard sorted by score, a search across several fields. Caching such a result helps only if many users ask for exactly the same thing. The alternative is to compute the answer ahead of time and store it in the shape it is read. Reads then become simple lookups.

  • Database materialized views. A materialized view stores the result of a query as a table. PostgreSQL's REFRESH MATERIALIZED VIEW CONCURRENTLY recomputes it without blocking readers, though it recomputes the whole view each time. Some databases, such as Oracle, SQL Server's indexed views and several cloud warehouses, maintain views incrementally on each change.
  • Summary tables maintained on write. The application or a trigger updates aggregate rows as events happen, such as daily sales per store or a like count per post.
  • Read models built from change streams. A consumer reads the change stream of the source database and maintains a denormalized copy elsewhere, such as a search index in Elasticsearch, a feed in Redis, or a document per product in a key-value store. This is the read side of Event Sourcing and CQRS.
  • Precomputed per-user results. Fan-out on write for feeds: when someone posts, insert the post ID into each follower's feed list, so reading a feed is one list lookup. Recommendation and "people you may know" lists are often computed in batch and stored per user.

The trade-off is freshness and write cost for read speed. A view refreshed every 5 minutes is up to 5 minutes old. Fan-out on write turns one post by an account with 10 million followers into 10 million list inserts, which is why news feeds use a hybrid: precompute for normal accounts and merge celebrity posts at read time; see Design a News Feed.

Materialized views, in depth#

Full refresh versus incremental maintenance. A full refresh reruns the whole query. It is simple and always correct, but its cost grows with the data, not with the change, so it is suitable for views refreshed every few minutes over modest data. Incremental view maintenance applies only the effect of each change to the stored result: a new order adds its amount to one daily total. For sums and counts that is easy. For joins, distinct counts, minimums after deletes and nested aggregates it is much harder. Research on the problem goes back decades, and the Differential Dataflow work by Frank McSherry, Derek Murray, Rebecca Isaacs and Michael Isard (CIDR 2013) underlies Materialize, a streaming database that keeps SQL views incrementally up to date. RisingWave and stream processors such as Flink offer similar capabilities; see Batch and Stream Processing.

Rebuildability is the safety net. A read model is a cache with structure. Because it is derived, it can be wrong after a bug, and it must be possible to rebuild it from the source: by replaying the change stream from a retained Kafka topic, or by a backfill job that scans the source and writes the view, followed by switching readers to the new copy. Design the rebuild path when you build the view, not after the first incident.

Idempotent, ordered updates. CDC consumers see each change at least once, and sometimes after a restart they see changes again. Make view updates idempotent, for example by storing the source row's version or LSN with each derived row and ignoring older updates. Partition the change topic by entity key so that changes to one entity arrive in order; see Delivery Semantics.

Freshness monitoring. Track the lag between a source commit and its appearance in each read model, for example by writing a heartbeat row every few seconds and measuring when it appears downstream. Alert when lag exceeds the freshness promised for that view.

Worked example: a product page at 300,000 reads per second#

An online store has 50 million products, 20 million daily users and a big sale coming. Each product page needs the product details, the price, stock status, the average rating and the first page of reviews. Estimates for the sale peak: 300,000 product-page requests per second, about 2,000 writes per second for price and stock changes, and 500 new reviews per second. The ratio is about 120 reads per write. Requirements: p99 page API latency under 100 ms; price and stock changes visible within 5 seconds; a seller sees their own edits immediately.

Rung 1. The product API originally ran 7 queries per page, including a review count computed with COUNT(*) and the reviews loaded one at a time. Rewritten, it runs one query for the product by primary key, which now carries a denormalized avg_rating and review_count updated when reviews arrive, and one keyset query for the first 10 reviews using an index on (product_id, created_at DESC). That gives 2 queries per page instead of 7, each under 1 ms when cached in memory.

Rung 2 and 3. The catalogue is 50 million products at about 4 KB each, around 200 GB with indexes, and reviews add 1 TB, of which the recent, hot portion is about 100 GB. A primary with 512 GB of memory holds the working set. Uncached, 300,000 pages × 2 queries = 600,000 queries per second, far beyond one server. Five replicas at about 40,000 queries per second each give 200,000, still not enough, and the price and stock writes add apply load to each one. Replicas alone would need around 15 machines, so we cache.

Rung 4. Product details and the review summary are cached in Redis as one object per product, invalidated by a CDC consumer when the product row changes, with a 10-minute TTL as a safety net. Price and stock are cached separately, with a 5-second TTL plus invalidation, matching the freshness requirement. Popularity is very skewed in a sale. Suppose the top 100,000 products receive 90% of views. Then a cache of under 1 GB of hot objects, at about 4 KB each, already reaches a hit ratio near 90%, and 10 GB covering the top 2 million products reaches about 99%. At 99%, database load falls to about 6,000 queries per second, which the primary plus two replicas handle with large headroom. The top 1,000 deal products are hot keys at up to 20,000 reads per second each. Each application server caches them in-process for 1 second, so Redis sees at most one fetch per key per server per second.

Rung 5. The product details and reviews are identical for every user in a locale, so the API response for the public part is served through the CDN with s-maxage=30, stale-while-revalidate=30 and purged by a product-<id> tag on change. Price and stock are fetched by the browser from a separate endpoint with a 5-second TTL at the edge. With a 90% edge hit ratio for the public part, the origin sees 30,000 requests per second for it, and Redis absorbs most of those.

Rung 6. The "customers also bought" list is computed nightly in batch and stored per product. The rating histogram is maintained incrementally by the review consumer. Neither is computed at read time.

Lag and the seller. A seller editing their product is routed, for 10 seconds after a write, to the primary for that product, bypassing caches. Other users see the change after CDC invalidation and the CDN purge, typically within a few seconds, and in the worst case after the 5-second price TTL.

Result. Of the 300,000 public product requests per second, the CDN serves about 270,000, and the remaining 30,000 reach the product API. The 300,000 price and stock calls are also mostly absorbed at the edge by the 5-second TTL, leaving tens of thousands per second for the API. About 12 application servers and a 6-node Redis cluster serve nearly all of that, and only a few thousand queries per second reach a primary and two replicas. For most users, p99 latency is set by the edge, at around 20 to 50 ms. The design meets the freshness requirements explicitly: 5 seconds for price and stock through TTL and invalidation, immediate for the seller, and up to about 30 seconds plus purge time for descriptions.

When to Use It#

  • The read-to-write ratio is high, around 10:1 or more. Feeds, catalogues, profiles, short links, media metadata, search results, configuration and reference data are typical.
  • Measured load on the database is dominated by reads, and the queries are already reasonably efficient, or you have just made them so.
  • Many users read the same data: a skewed popularity distribution makes caches and CDNs very effective.
  • Users are spread geographically, and reads from distant regions are slow. Replicas and edges near users cut latency.
  • Some staleness is acceptable for most reads, even if only a second or two, and you can name the reads that must be fresh.
  • In interviews, whenever the non-functional requirements include high read QPS, low read latency or a celebrity or viral item. Typical prompts are news feeds, URL shorteners, ticketing event pages, product pages, top-K lists and nearby search.

When NOT to Use It#

  • Do not add caches or replicas before fixing slow queries. They copy the inefficiency and hide it until the cache misses.
  • Do not cache data that must be strictly current unless you can invalidate it reliably: account balances at the moment of withdrawal, seat availability at the moment of purchase, permission revocations. Read those from the primary, or design the write path to enforce the invariant whatever the reader saw.
  • Do not cache data that is rarely re-read. A long tail of unique queries gives a low hit ratio and wastes memory, and the cache adds a network hop to every miss.
  • Do not reach for replicas when writes dominate. Every replica applies every write, so replicas add little capacity on write-heavy workloads. The problem is in Scaling Writes.
  • Do not climb the ladder for a small system. A few hundred reads per second fit comfortably on one database with good indexes. Each layer you add is another thing that can serve stale data or fail.
  • Do not put personalised responses on a shared CDN cache without splitting them first, or one user's data will be served to another.

How to Implement It#

  1. Write down the read requirements. Peak read QPS, latency targets per endpoint, and the staleness budget for each kind of data: immediate, a few seconds, minutes or hours. List the reads that must see the user's own writes.
  2. Measure. Find the top queries by total time, the read-to-write ratio, the buffer cache hit ratio, and the key popularity distribution.
  3. Fix the queries. Add composite and covering indexes for the hot queries, remove N+1 patterns, use keyset pagination, and denormalize values that are read constantly but change rarely.
  4. Size the database. Scale up until the working set fits in memory with headroom. Put a connection pooler in front.
  5. Add replicas when one machine is not enough. Route reads by staleness tolerance, monitor lag, remove lagging replicas from rotation, and implement read-your-writes for the user's own data.
  6. Add caches for repeated reads: cache-aside with TTLs and jitter, invalidation driven by writes or CDC, negative caching, request coalescing, and a short-TTL in-process tier for hot keys.
  7. Put a CDN in front of static assets and any shared, public responses. Set Cache-Control deliberately, normalise cache keys, and purge by tag on change.
  8. Precompute expensive reads as materialized views or CDC-fed read models, with a rebuild path and freshness monitoring.
  9. Load-test the failure cases: a cache node restart, a cold CDN, a replica falling 60 seconds behind, a single key at 100 times normal traffic.

The read helper below combines several defences: a short in-process tier, stale-while-revalidate with a soft expiry, single flight per server, negative caching and TTL jitter.

type Entry = { v: string | null; softExp: number };
const local = new Map<string, Entry>();                 // use a bounded LRU in production
const inflight = new Map<string, Promise<string | null>>();
 
export async function cachedRead(
  key: string, load: () => Promise<string | null>, ttlS = 300,
): Promise<string | null> {
  const now = Date.now();
  const l1 = local.get(key);
  if (l1 && l1.softExp > now) return l1.v;              // in-process hit, at most 1 s old
 
  const raw = await redis.get(key);
  if (raw !== null) {
    const e: Entry = JSON.parse(raw);
    local.set(key, { v: e.v, softExp: now + 1000 });
    if (e.softExp < now) refresh(key, load, ttlS).catch(() => {}); // serve stale, refresh behind
    return e.v;
  }
  return refresh(key, load, ttlS);                      // full miss: share one load
}
 
function refresh(key: string, load: () => Promise<string | null>, ttlS: number) {
  let p = inflight.get(key);
  if (!p) {
    p = load()
      .then(async (v) => {
        const soft = v === null ? 30 : ttlS;            // cache "not found" briefly
        const hard = Math.ceil(soft * 2 * (1 + Math.random() * 0.1)); // jittered hard TTL
        const e: Entry = { v, softExp: Date.now() + soft * 1000 };
        await redis.set(key, JSON.stringify(e), "EX", hard);
        return v;
      })
      .finally(() => inflight.delete(key));
    inflight.set(key, p);
  }
  return p;
}

The hard TTL is about twice the soft expiry, so a value past its soft expiry is still served while one request refreshes it. Across servers, a short SET lock:key NX PX lock can additionally limit refreshes to one per key cluster-wide.

TechnologyFits when
PostgreSQL or MySQL read replicasRelational data, read-heavy, a few seconds of lag acceptable for most reads
Amazon Aurora, AlloyDBManaged replicas on shared storage with low lag and fast failover
PgBouncer, ProxySQL, Pgpool-IIConnection pooling and read and write splitting in front of the database
RedisShared cache with data structures: sorted sets, hashes, counters, feeds
MemcachedSimple, multi-threaded object caching at very high throughput
Caffeine, in-process LRU mapsHot-key protection and sub-microsecond reads of small, slightly stale data
DynamoDB Accelerator (DAX)Read-through cache in front of DynamoDB
CloudFront, Fastly, Cloudflare, AkamaiEdge caching of assets and public API responses, tag purges, request collapsing
Varnish, Nginx proxy cacheSelf-hosted HTTP caching in front of your origin
Elasticsearch, OpenSearchSearch and filtering read models fed by CDC
Materialize, RisingWave, FlinkIncrementally maintained views over change streams
Debezium with KafkaChange streams to drive invalidation and read models

Trade-offs#

OptionProsConsPick when
Indexes and query tuningCheap, consistent, often 10 to 1,000 times fasterSlower writes, more memory per indexAlways first
DenormalizationRemoves joins and counts from readsDuplicate data to keep in sync, write amplificationHot reads of rarely changing values
Vertical scalingNo code change, strong consistencyCost climbs at the top, single failure domain, a ceilingWorking set nearly fits, small team
Read replicasMultiplies read capacity, adds failover and regional copiesReplication lag, routing logic, every replica applies all writesRead-heavy, lag tolerable for most reads
Shared cache, Redis or MemcachedSub-millisecond reads, huge offload at high hit ratiosInvalidation, stampedes, hot keys, another system to runRepeated reads of the same keys
In-process cacheFastest, protects against hot keysPer-server copies, hard to invalidate, smallHot keys, short-lived staleness acceptable
CDN and edge cachingLowest latency worldwide, offloads origin almost entirelyOnly for shared responses, purge delay, cache-key mistakesPublic or shareable content
Materialized views and read modelsExpensive reads become lookupsFreshness lag, write cost, rebuild machineryAggregations, feeds, search, secondary access patterns
ShardingScales data size and capacity beyond one machineScatter-gather for non-key reads, operational complexityDataset or write load outgrows one primary

Common Pitfalls#

  • Caching before measuring. The slow query is still there on every miss, and the cache hides it until the cache restarts.
  • No staleness budget. Layers are added independently, and nobody notices that a CDN TTL, a cache TTL and replica lag add up to a minute of staleness on data that should be fresh.
  • Updating the cache instead of deleting it on write. Concurrent writers can leave the older value in the cache. Delete, and let the next read fill it.
  • Filling caches from lagging replicas right after an invalidation, which re-caches the old value.
  • Ignoring read-your-writes. Users edit, reload, see the old value and edit again, generating duplicate writes and support tickets.
  • Synchronised expiry. Thousands of keys loaded at startup with the same TTL all expire in the same second and stampede the database.
  • No plan for hot keys. One celebrity post or flash-sale item overloads a single cache shard while the cluster average looks fine.
  • Cache keys that vary too much, such as including session IDs, tracking parameters or full headers, which drops the hit ratio towards zero.
  • Treating the cache as the source of truth. If the only copy of data is in Redis without persistence, a restart loses it.
  • Unbounded in-process caches that grow until the application runs out of memory.
  • Scatter-gather everywhere. Sharding by one key and then serving most reads by another sends every query to every shard.

Real-World Examples#

  • Facebook described in "Scaling Memcache at Facebook" (Nishtala and colleagues, NSDI 2013) how a look-aside memcache tier served billions of requests per second in front of MySQL, with leases against stale sets and herds, commit-log-driven invalidation and regional cache pools. Its social graph is served by TAO (Nathan Bronson and colleagues, USENIX ATC 2013), a read-optimised, graph-aware caching layer with follower and leader tiers.
  • Netflix runs EVCache, a distributed caching system based on Memcached, which it has described publicly. It replicates cache data across availability zones and regions so that reads stay local and survive the loss of a zone.
  • Wikipedia serves the large majority of page views from its edge caching layer, historically Varnish and now including Apache Traffic Server. Only cache misses and logged-in traffic reach the application servers and databases.
  • Twitter has described precomputing home timelines and storing them in in-memory cache clusters built on Redis, so that reading a timeline is a list lookup rather than a merge across followed accounts. This is the precomputation rung applied to a feed.
  • Amazon DynamoDB Accelerator (DAX) is a managed read-through cache for DynamoDB, which AWS positions for microsecond read latency on read-heavy tables.
  • Stack Overflow has long been cited for serving a very large site from a small number of powerful database servers, with careful queries and caching rather than a large distributed fleet.

Case studies that use this pattern#

In the Interview#

Deep Dive: The mathematics of cache sizingShow

Zipf popularity and how big a cache must be. Suppose N items are requested with Zipf popularity, so the item of rank k has probability proportional to 1 / k^s. If you cache the C most popular items, the hit ratio is the share of requests going to those items. For s = 1 this is about H(C) / H(N), where H(n) is the n-th harmonic number, roughly ln n + 0.577. For N = 50 million and C = 1 million, that is about (13.8 + 0.6) / (17.7 + 0.6), roughly 79%. Caching 2% of the items captures nearly four fifths of requests. For s greater than 1 the head is heavier: at s = 1.2, the same cache captures well over 90%. Real workloads vary. Measured web and social workloads have often shown exponents between about 0.6 and 1.2, and flash sales or breaking news can be far more skewed. That is why you should measure the popularity curve rather than assume one. Record a sample of keys for a day, sort by frequency, and compute the hit ratio for each candidate cache size.

Miss ratio curves. Plotting the miss ratio against cache size gives a miss ratio curve. It typically falls steeply at first and then flattens, and the knee tells you where extra memory stops paying. Because the database load is proportional to the miss ratio, the curve converts directly to a capacity plan. If going from 50 GB to 100 GB of cache reduces misses from 3% to 2%, it cuts database load by a third, which may or may not be worth the memory.

LRU is not the same as caching the top C. A real cache does not know popularity in advance. It evicts by a policy such as least recently used (LRU). A well-known approximation by Hao Che, Ye Tung and Zhijun Wang (IEEE JSAC, 2002) models an LRU cache with a single characteristic time T. An item stays in the cache if it is requested at least once every T, so an item with request rate λ has hit probability about 1 − e^(−λT). T is the value for which the expected number of cached items equals the capacity. The model explains why LRU does well for strongly skewed workloads and poorly for scans, where many items are read once, and why scan-resistant policies such as segmented LRU, ARC, and the TinyLFU admission policy used by Caffeine improve hit ratios. See Cache Eviction and Invalidation.

Little's law for pools and replicas. The number of requests in flight equals arrival rate times latency. At 40,000 queries per second and 2 ms per query, a replica has on average 80 queries in progress, so a pool of a few hundred connections across all application servers is plenty. If latency degrades to 50 ms during an incident, the same rate needs 2,000 concurrent queries, connection pools exhaust, and requests queue. Caches help here as well. Cutting the queries that reach the database cuts the concurrency it must hold, which keeps latency stable under load.

Headroom and failure. Size every tier so that it survives losing one member at peak. With 6 cache nodes at 60% load, losing one moves its keys to the others, through consistent hashing or by falling through to the database. If it falls through, the database suddenly sees one sixth of the cached traffic as misses. At a 99% hit ratio and 300,000 reads per second, that is an extra 50,000 queries per second, far more than the 3,000 it normally sees. Plan for this with replicated cache nodes, gutter pools or request limits on the fall-through path.

Deep Dive: Facebook's read path, from memcache to TAOShow

The two Facebook papers are the most detailed public accounts of scaling reads to billions per second, and most of their techniques now appear in other systems.

Look-aside memcache at scale. Web servers read from memcache and fall back to MySQL on a miss, then set the value. Writes go to MySQL, then delete the key. Keys are spread over hundreds of memcache servers per cluster by consistent hashing. A single page can need hundreds of keys, so web servers build a dependency graph of the data they need and fetch as much as possible in parallel, batched requests. The paper reports routing gets over UDP to cut connection overhead, while sets and deletes go over TCP through a proxy called mcrouter. To avoid incast, where hundreds of responses arrive at once and overflow switch buffers, clients use a sliding window that limits outstanding requests.

Leases. As described above, leases prevent stale sets, and they rate-limit refills of hot keys to avoid thundering herds. The paper reports that leases reduced peak database query rates for herd-prone keys dramatically.

Pools and gutters. Keys with different access patterns go to different pools. A small pool holds keys that are cheap to miss, and a larger pool holds keys that are expensive to recompute, so cheap keys do not evict expensive ones. When a memcache server fails, its requests go to a small gutter pool of otherwise idle servers that hold values with short TTLs. Misses for that server's keys then do not all fall through to the database at once. This is the headroom problem from the previous deep dive, solved with spare capacity.

Regions, replication and invalidation. Each region has several front-end clusters, each with its own memcache servers. One region holds the MySQL primaries and others hold replicas. Daemons called mcsqueal tail the MySQL commit log in each region and broadcast deletes to every cluster's memcache, so invalidation follows replication and cannot overtake it. Rarely accessed or large items can live in a regional pool shared by all clusters, which saves memory. New clusters are warmed by reading misses from an already warm cluster instead of from the database. To give users read-your-writes when they write from a replica region, the system sets a remote marker before the write. Reads that find the marker go to the primary region until replication delivers the change.

TAO. Many Facebook reads are graph queries: a user's friends, a post's likes, the comments on a photo. TAO models data as objects, such as users and posts, and associations, typed edges with timestamps, such as "liked" or "authored". It exposes a small API: get an object, list associations of a type from an object in time order, count them. Behind the API sit caching tiers. Followers serve reads and forward misses and writes to a leader tier per region, which talks to MySQL, keeps caches consistent for that shard, and sends invalidations to followers. Writes go through the cache to the database, write-through, rather than the look-aside pattern of memcache, which avoids the stale-set race. Association lists are cached in a form that supports the common queries, such as the most recent 50 comments, without hitting MySQL. TAO is a read model, a cache and a query engine at once, specialised for one data model.

Lessons for ordinary systems. Several ideas carry over to systems of any size. Batch and parallelise the many reads behind one page. Use leases, or locks with tokens, against stale sets and herds. Drive invalidation from the commit log. Plan for cache failure with spare capacity. Give the writer read-your-writes by routing, not by making everything strongly consistent. Specialise the cache to the data model when one access pattern dominates.

Deep Dive: Consistency across a layered read pathShow

Each rung of the ladder adds a copy of the data, and each copy has its own freshness. Reasoning about the combined behaviour is the part of read scaling most often done badly.

Staleness adds up along the path. The worst-case staleness of a read is roughly the sum of the delays of every layer it passes through on the way from the source of truth. Consider replica lag, plus the delay before the cache is invalidated or the TTL if invalidation fails, plus the CDN TTL or purge time, plus any browser cache lifetime. A read path with 1 second of lag, 2 seconds of invalidation delay, a 30-second CDN TTL and a 10-second browser max-age can return data about 43 seconds old. Write the budget per data type and check each layer against it.

Versioning makes staleness visible. Give each entity a monotonically increasing version, such as an updated_at timestamp or a counter, and carry it through every layer. Caches then refuse to overwrite a newer version with an older one, with a compare-and-set or a Lua script in Redis. Clients can detect that a response is older than what they have already seen and refetch. A CDN URL can include the version, such as /products/42?v=17, so a client that knows of version 17 is never served version 16 from the edge.

Monotonic reads across tiers. A user can see new data from one replica or cache node and old data from another on the next request. Pinning users to a replica, carrying the highest version seen in the session and rejecting older responses, or simply routing a user's requests to the same edge and cache node all reduce time going backwards. None is perfect across failovers, so decide whether the product can tolerate a rare step back. A feed usually can; a bank balance cannot.

Invalidation ordering. Invalidations must not overtake the data they invalidate. If a cache delete reaches a region before the database change replicates there, a reader can refill the cache from the stale replica, and the stale value sticks. Driving invalidation from each region's own replication stream, as Facebook did, or delaying deletes by more than the maximum lag, keeps the order right.

Make the critical paths independent of caches. The safest designs never let a stale read cause an incorrect write. The checkout reads stock from the cache to display it, but the purchase itself performs a conditional update on the primary, such as UPDATE ... SET stock = stock − 1 WHERE stock > 0, which enforces the invariant whatever the reader saw. Stale reads are then a display problem, not a correctness problem. That separation lets you cache aggressively everywhere else.

Test staleness deliberately. Inject replication lag in staging, delay invalidation messages, restart cache nodes, purge the CDN, and check what users see. Add synthetic monitors that write a value and measure how long until each layer serves it. Freshness that is measured stays within budget, and freshness that is assumed drifts.

Key Takeaways#

  • Most systems read 10 to 1,000 times more than they write. Reads are the easier half to scale, because any up-to-date copy can answer them. The real work is controlling how stale each copy may be.
  • Climb the ladder in order and stop when the numbers are met. Tune queries, indexes and denormalization first, then scale up, then add replicas, caches, a CDN and finally precomputed views.
  • Replicas multiply read capacity only when writes are a small share of the load, because every replica applies every write. Handle lag with primary reads for the user's own data, replica pinning or replication position tokens.
  • Cache hit ratio is the key number. Going from 90% to 99% cuts database load tenfold. Use cache-aside with TTLs and jitter, delete on write, negative caching and an in-process tier.
  • For updates that must be visible at once, delete after commit, drive invalidation from the change stream, use versioned keys, and use leases or double deletes against the stale-set race.
  • Hot keys need their reads spread: short-TTL in-process caching, key replication, request coalescing and CDN edges.
  • Stampedes are prevented with single flight, locks or leases, stale-while-revalidate, probabilistic early refresh and warm-up.
  • CDNs and materialized views turn expensive or distant reads into nearby lookups. Each needs a purge or rebuild path and a freshness target.
  • Keep correctness on the write path, using conditional updates on the primary, so stale reads can only ever affect what users see, never what the system does.