Scaling reads
Most apps read far more than they write. Learn the order of steps that serves many more reads without breaking what users see.
Updated since you finished it. We changed this lesson after you marked it done. Your progress is kept.
What broke
This is a real case, from a paper Facebook published in 2013. Facebook's users read an order of magnitude more content than they create. So the work was mostly reads, and Facebook put a large cache, memcache, in front of MySQL and other data stores. 1
Loading one popular page fetched an average of 521 different items from that cache. Facebook ran hundreds of cache servers in one cluster. Every web server talked to every cache server, and that caused two problems. Replies that arrived all at once could overload the network switches. And one busy cache server could slow down many web servers. 1
Simply buying more servers did not fix everything. The paper says popular items only become more popular as you add web servers. It also notes that a single key can be 20% of one cache server's requests. 1
Then Facebook added data centres in other regions. One master region kept the other regions up to date. Those regions read from local copies of the database, which can lag behind. When lag was large, a user's next page could be missing the change they had just made. 1
There was no single outage. The read path worked at one size and needed new fixes at the next.
The idea in simple words
A read path is the route a read takes, from the user's phone to the data. Scaling reads means answering each read as close to the user and as cheaply as you can. Keep the primary database for work only it can do.
Think of it as a ladder. Climb one step at a time, only when your numbers say so. Each step adds a new way for data to be stale.
The key idea. Every read you answer higher up is a read your database never sees. But every copy of data can be out of date. Choose, for each kind of read, how stale it may be.
How it works
Step 0: measure the read/write ratio
First, count reads and writes per second, and find the queries that use the most total time. In PostgreSQL, the pg_stat_statements module, once enabled, tracks planning and execution statistics for every SQL statement. These include how often each one ran and its total time. 4
Facebook's numbers made the choice clear. In a sample of 6.5 million requests to TAO, its graph store, 99.8% were reads and 0.2% were writes. 2 If your mix is closer to half and half, read-side tools will help much less. See Scaling writes instead.
Step 1: fix the query and the index
Many "we need replicas" problems are one slow query. EXPLAIN shows the query plan the database chose. EXPLAIN ANALYZE really runs the query and shows true row counts and times. So for an UPDATE or DELETE, wrap it in a transaction and roll it back. 3 Look for a full table scan where you expected an index.
This step is cheap, and it never shows stale data. Do it first.
Step 2: cache
Keep hot results in memory. The common pattern is cache-aside: read the cache, and on a miss read the database and fill the cache. On a write, Facebook deletes the cached key instead of updating it, because deletes are idempotent. 1 The caching lesson covers TTLs, invalidation and stampedes.
Step 3: read replicas
Send reads to copies of the database, and writes to the primary. This adds read capacity, but replicas lag. TAO measured the lag of its replica databases in other regions. It was under 1 second 85% of the time, under 3 seconds 99% of the time, and under 10 seconds 99.8% of the time. 2 So plan for seconds, not zero. The replication lesson explains lag in depth.
The bug users notice is read-your-writes: "I saved it, and it is gone." Facebook's fix was a "remote marker". When a web server in a non-master region writes, it first sets a marker for that key. On a cache miss, if the marker exists, the read skips the local replica and goes to the master region. 1 TAO has a similar idea: a read can be marked "critical" and sent to the master region. The paper's example is a login check, so old credentials are not used. 2
Our advice: most reads go to replicas. A user's own data, just after they write it, goes to the primary.
Step through one read falling through the layers. Use Next and Back, or the ← and → keys.
- A visitor opens a public product page. It is the same for everyone, so the CDN has a fresh copy and answers near the user. Your cache and databases never see this read.
- A logged-in user opens their feed. It is private, so the CDN passes it on. The app finds the feed in its cache and answers from memory.
- Another user asks for an old page of the feed. The cache misses. The app reads from a replica, puts the result in the cache, then answers.
- This user just changed their profile. The replica may still be behind. So for a short time, the app reads this user's own data from the primary.
- Each layer answers what it can and passes the rest down. The primary is left free for writes and for the few reads that must be fresh.
Step 4: denormalise and precompute
Denormalise. Store a copy of data where it is read. For example, keep comment_count on the post row, instead of counting comments on every page view. You now have two places to update.
Materialized views. PostgreSQL can store the result of a query in a table-like form. Reads are often much faster than querying the base tables. The cost: the data is not always current. 5 You update it with REFRESH MATERIALIZED VIEW. A plain refresh can block readers. With CONCURRENTLY, readers are not blocked. But the view needs a unique index on plain columns that covers all rows. 6
Step 5: read models fed by change data capture
When one database cannot serve every kind of read, build separate read models. This is the idea behind CQRS: one model for updates and a different model for reads, maybe in a different database. 7 In this lesson, a feed table, a search index and a cache can all count as read models. CQRS and read models goes deeper.
Feed them from the database's change log, with change data capture (CDC). The sagas, outbox and CDC lesson shows how. Facebook used a similar idea to keep its caches correct. Daemons read the SQL that each database committed and sent the cache deletes to every frontend cluster in the region. Lost deletes could be replayed from that reliable log. 1
Be careful. Fowler warns that for most systems CQRS adds risky complexity, and should be used only on parts of a system. Separate models also make eventual consistency likely. 7 For a few heavy queries, he suggests a simpler option: a separate reporting database. 7
Step 6: search indexes for complex reads
Send full-text search and complex filters to a search index: another read model, with its own lag. See Search systems.
Step 7: CDN and edge caches for public reads
Reads that are the same for everyone, like product pages or images, can be answered by a CDN near the user. See CDNs and HTTP caching.
Slack's Flannel caches data about users, channels and more at its edge locations, so clients load it only when needed. For a team of 32,000 users, the startup data clients needed became 44 times smaller. 8
Hot keys
A hot key is one key that gets a huge share of reads. Hashing spreads keys, not reads of one key, so more servers do not help.
Facebook copies a small, very busy set of keys to several servers in a pool. Its example: one server holds 100 keys and answers 500,000 requests a second. Each request needs all 100 keys, and 1 million requests arrive each second. Split the keys over two servers, and each server still gets 1 million requests. Copy all keys to both, and each gets 500,000. The cost: every delete must reach every copy. 1
Other ways to spread a hot key, from our experience:
- Cache it inside each app server for a few seconds.
- Split it into copies like
post:42#1…post:42#8, and read one at random. - Collapse many misses for one key into one database read.
Trade-offs
| Step | Read capacity gained | Staleness | Cost and new risks |
|---|---|---|---|
| Query and index tuning | Often large, for the queries you fix. | None. | Indexes slow writes a little and use disk. |
| Cache | Very large for hot data. | Until the TTL or delete arrives. | Invalidation bugs, stampedes, hot keys. |
| Read replicas | Roughly one database per replica. | Replication lag, sometimes several seconds. | Routing logic for read-your-writes. |
| Denormalise or materialized view | Large for joins and counts. | Until you update or refresh. | Two copies to keep in step. |
| Read model fed by CDC | Large, and each read shape gets its own store. | Pipeline lag. | A new pipeline to run, watch and replay. |
| Search index | Makes complex queries possible. | Indexing lag. | Another system and its own operations. |
| CDN | Huge for public reads. | Until the cache rules say it expires. | Only safe for data that is the same for many users. |
Our simple rule: climb the ladder in order, and stop at the first step that meets your target.
At work: how a senior uses this
- Start with numbers: reads per second, writes per second, and the top ten queries by total time.
- For each kind of read, ask: "How stale may this be?" Write the answer in the design doc. A bank balance and a like count get different answers.
- Decide who reads from the primary. Make it a rule in one place in the code, not a choice in each query.
- Watch replica lag and alert on it. Reads that "sometimes show old data" are often lag.
- Before a launch or a sale, ask which item everyone will open at once.
With AI
What to ask the agent
"Here is the output of pg_stat_statements for our top 20 queries, and our schema. For each query, say if an index would help, and write the CREATE INDEX statement. Do not suggest caching yet."
"Add read routing to this data layer. Reads go to a replica by default. For 10 seconds after a user writes, that user's reads go to the primary. Show where the 10 seconds is set."
"Design a materialized view for this dashboard query. Add the unique index it needs for REFRESH CONCURRENTLY, and a job that refreshes it every 5 minutes."
What to check yourself
- The new index matches the real WHERE and ORDER BY, and
EXPLAINshows the plan uses it. - The agent did not run
EXPLAIN ANALYZEon an UPDATE or DELETE outside a rolled-back transaction. - The read-your-writes window is longer than your real replica lag at p99, not your average.
- Every cache or read model has a way to be rebuilt, and someone owns it.
- Hot keys are spread, and the agent did not add a cache that all servers miss at once.
Check yourself
Your progress is saved only in this browser. Export it to keep it safe.
You have finished 5 lessons. Your progress lives only in this browser. Export a copy so you don’t lose it.
Go deeper
Show 8 sources and related lessons
- Rajesh Nishtala and others, “Scaling Memcache at Facebook”, NSDI 2013 (USENIX) (opens in a new tab)
How Facebook served a read-heavy workload with memcache, replicas in other regions, hot key replication and invalidations from the database log. - Nathan Bronson and others, “TAO: Facebook's Distributed Data Store for the Social Graph”, USENIX ATC 2013 (opens in a new tab)
A read-optimized graph store with leader and follower cache tiers. Shows the read/write mix and measured replication lag. - PostgreSQL documentation, “Using EXPLAIN” (opens in a new tab)
How to read a query plan, and what EXPLAIN ANALYZE really runs. - PostgreSQL documentation, “pg_stat_statements” (opens in a new tab)
A module that counts calls and time for every SQL statement, so you can find your top reads. - PostgreSQL documentation, “Materialized Views” (opens in a new tab)
What a materialized view is, why it can be much faster, and why its data is not always current. - PostgreSQL documentation, “REFRESH MATERIALIZED VIEW” (opens in a new tab)
Refreshing a view, and the CONCURRENTLY option that keeps readers unblocked. - Martin Fowler, “CQRS”, martinfowler.com, 2011 (opens in a new tab)
Separate models for reading and writing, and a clear warning that most systems do not need it. - Bing Wei, “Flannel: An Application-Level Edge Cache to Make Slack Scale”, Slack Engineering, 2017 (opens in a new tab)
A cache near users that cut what clients of large teams had to download at startup.
Case studies: Meta: TAO: a graph cache in front of sharded MySQL · Slack: Flannel: an edge cache so huge teams can start fast
Related: Caching and cache stampedes · Replication · Distributed caches · Sagas, outbox and CDC · Search systems and inverted indexes · CDNs and HTTP caching · Scaling writes and hot keys
Read the TAO case and the Slack Flannel case. Related lessons: Distributed caches, Replication and Scaling from zero to millions.