Building at scale · L1Scaling reads

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.

L1 Must-knowBuilding at scale18 min read
Fact-checked by AI against cited sources · Human review pendingLast reviewed 22 Oct 2026 · How we check content
Section 1 of 8

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.

Section 2 of 8

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.

Section 3 of 8

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.

One read falling through the layers: CDN, app cache, replica, primary User CDN Cache Replica Primary publichitnot asked feedpasshit200 old pagemissreadrowsfill200 my profilejust wroteskip the replica ✓ the primary sees few reads SeniorPath
  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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 1 of 5

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.
Section 4 of 8

Trade-offs

StepRead capacity gainedStalenessCost and new risks
Query and index tuningOften large, for the queries you fix.None.Indexes slow writes a little and use disk.
CacheVery large for hot data.Until the TTL or delete arrives.Invalidation bugs, stampedes, hot keys.
Read replicasRoughly one database per replica.Replication lag, sometimes several seconds.Routing logic for read-your-writes.
Denormalise or materialized viewLarge for joins and counts.Until you update or refresh.Two copies to keep in step.
Read model fed by CDCLarge, and each read shape gets its own store.Pipeline lag.A new pipeline to run, watch and replay.
Search indexMakes complex queries possible.Indexing lag.Another system and its own operations.
CDNHuge 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.

Section 5 of 8

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.
Section 6 of 8

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 EXPLAIN shows the plan uses it.
  • The agent did not run EXPLAIN ANALYZE on 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.
Section 7 of 8

Check yourself

1. Your database CPU is at 90%. What should you do first?

Show answer

Find the top queries by total time, and check their query plans. A missing index or a bad query is the cheapest fix. Replicas and caches can come later, if the numbers still need them.

2. A user saves their new display name, refreshes, and sees the old one. Reads go to a replica. What is a common fix?

Show answer

Read this user's own data from the primary for a short time after they write. This is a read-your-writes problem. Only the writer needs the fresh copy, so only their reads go to the primary.

3. One cache server is overloaded because of one very popular key. Why does adding more cache servers with the same hashing not help?

Show answer

The key still maps to one server, so that server still gets all its reads. Hashing spreads keys, not reads of one key. Copy the hot key to several servers, or cache it inside each app server.

4. What is the main cost of a materialized view?

Show answer

Its data is only as fresh as its last refresh. PostgreSQL stores the result and updates it only when you refresh it, so reads are fast but can be out of date.

5. Facebook's TAO paper reports reads as 99.8% of requests. What does a number like that tell you?

Show answer

Caching and read copies will pay off, because almost all the work is reads. Measure the read/write ratio first. When reads are almost all the work, read-side tools give the most benefit.

Your progress is saved only in this browser. Export it to keep it safe.

Was this clear?
Report a mistake (opens GitHub in a new tab)
Section 8 of 8

Go deeper

Show 8 sources and related lessons
  1. 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.
  2. 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.
  3. PostgreSQL documentation, “Using EXPLAIN” (opens in a new tab)
    How to read a query plan, and what EXPLAIN ANALYZE really runs.
  4. 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.
  5. 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.
  6. PostgreSQL documentation, “REFRESH MATERIALIZED VIEW” (opens in a new tab)
    Refreshing a view, and the CONCURRENTLY option that keeps readers unblocked.
  7. 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.
  8. 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

Term

See full entry

Jump to a section

  1. 1What broke
  2. 2The idea in simple words
  3. 3How it works
  4. 4Trade-offs
  5. 5At work
  6. 6With AI
  7. 7Check yourself
  8. 8Go deeper