← Study paths

Scaling reads

The first thing every read-heavy system needs, from one cache to a global edge.

7 blocks · about 36 min of reading · ends with URL Shortener

When you finish, you should be able to say

Explain why reads stop hitting the database, what goes stale when they do, and how you keep it correct.

The route

7 blocks (4 fundamental, 3 senior), then the practice problem.

  1. Cache the hot readsFundamental
  2. Invalidate the cache when data changesFundamental
  3. Protect against a cache stampedeSenior
  4. Spread reads across replicasFundamental
  5. Let users see their own writesSenior
  6. Serve static bytes from the edgeFundamental
  7. Spread a hot keySenior
  8. URL Shortener (TinyURL / bit.ly)
Latency & performanceConsistency & coordinationFundamentalSenior
Read each block, then tick “I can explain this”: the path remembers where you are.Start with step 1
Your URL Shortener so far0 of 7 blocks in
Link creatorcreates, then opensthe linkURL creation serviceAmazon EC2 Auto Scalinginsert row, then DELaliasPrimary databaseAmazon Auroraall writes; recentwriters read hereVisitor's browserGET /aB3xZ9CDN edgeAmazon CloudFrontTLS and static assets;302 passes throughRedirect serviceAmazon EC2 Auto Scalingstateless; local LRUfor hot aliasesRead replicasAmazon Auroraasync, a few hundredms behindRefresh lockone reload per expiredkeyRedis cacheAmazon ElastiCachealias to long URL, TTLplus jitterHot alias copiesalias#1 to #4 on fournodesStep 2: Invalidate the cache when data changes2Step 4: Spread reads across replicas4Step 5: Let users see their own writes5Step 6: Serve static bytes from the edge6Step 7: Spread a hot key7Step 4: Spread reads across replicas4Step 3: Protect against a cache stampede3Step 1: Cache the hot reads1Step 7: Spread a hot key7GET /aliasforward1. lookup2. on missrecent writerreplicatePOST /urlsinserthot key expiredcelebrity alias

Next, step 1 adds Redis cache (outlined). A box fills in when you tick “I can explain this” on the block that introduces it; plain boxes come from the problem itself.

Each block has a diagram. Open one beside its step, or all of them at once.
  1. Cache the hot reads

    Latency & performancefundamental~6 min

    Start here: the one component that removes most database reads, and the pattern every other caching idea assumes.

    The same data is read far more often than it changes and every read hits the database.

    Say it like this: Reads are 100× writes, so I put Redis in front of the database as a cache-aside layer with a TTL, and the database only sees misses.

    Adds to the design: Redis cache

    Check yourself: Why delete the cache entry on write instead of updating it?

    Updating writes a value that may never be read again and races with concurrent writers, so two updates can leave the cache holding the older value. A delete is idempotent, cheap, and guarantees the next read loads the current database row.

    Read this block →

  2. Invalidate the cache when data changes

    Latency & performancefundamental~5 min

    Now that reads come from a cache, decide how writes reach it, because this is the first thing an interviewer probes.

    A record is updated or deleted but the cache keeps serving the old value until its TTL runs out.

    Say it like this: I invalidate by deleting the cached key on every write and keep a short TTL as the safety net, so the next read always loads the current row.

    Adds to the design: URL creation service

    Check yourself: Which should happen first, the database write or the cache delete?

    Database first, then delete. If you delete first, a concurrent read can miss, reload the old row and set it before your write commits, leaving stale data until TTL. With database first the stale window is only the few milliseconds between commit and delete.

    Read this block →

  3. Protect against a cache stampede

    Latency & performancesenior~5 min

    A cache that works most of the time still fails all at once when a hot key expires; this is how you stop that.

    A popular key expires and every request misses at once, flattening the database (dog-piling).

    Say it like this: I stop a hot key from dog-piling the database by letting one request refresh it while everyone else is served the stale value, and I jitter TTLs so keys never expire together.

    Adds to the design: Refresh lock

    Check yourself: What is the difference between a cache stampede and a thundering herd?

    A stampede is the specific case of one popular key expiring and all its readers missing at once. A thundering herd is the general pattern of many clients acting at the same instant, such as reconnects after an outage or retries aligned to the same backoff. The fixes overlap: jitter, coalescing, and serving stale.

    Read this block →

  4. Spread reads across replicas

    Latency & performancefundamental~5 min

    Misses still reach the database, so spread them over copies, and learn what replication lag does to a user.

    A single primary database cannot keep up with read traffic.

    Say it like this: Reads dominate, so I send them to read replicas and keep the primary for writes and for any read that must see the latest commit.

    Adds to the design: Primary database, Read replicas

    Check yourself: How do you make sure a user sees their own write?

    Route that user to the primary briefly after any write, using a short-lived session marker, or record the primary log position returned by the write and only use a replica whose replay position has passed it. Other users can read from replicas as normal.

    Read this block →

  5. Let users see their own writes

    Consistency & coordinationsenior~5 min

    The user-visible bug replicas introduce, and the routing rule that fixes it.

    A user posts, refreshes, and the post is missing because the read hit a lagging replica.

    Say it like this: Only the writer needs to see the write immediately, so after a write I route that session to the primary for a short window, keyed by the commit position, and leave everyone else on replicas.

    Adds to the design: Primary database

    Check yourself: Why not route all reads to the primary and avoid the problem?

    Because reads outnumber writes by orders of magnitude and the primary would become the bottleneck that replicas exist to relieve. Read-your-writes keeps that benefit by making only the writer, for a short window, pay for freshness.

    Read this block →

  6. Serve static bytes from the edge

    Latency & performancefundamental~5 min

    Static bytes and video should never reach your servers at all; the edge is the cache in front of everything.

    Users far from your servers wait on round trips for images, scripts, video segments.

    Say it like this: Latency to users is dominated by distance, so I serve every static and cacheable byte from a CDN edge near them and let the origin handle only misses and dynamic requests.

    Adds to the design: CDN edge

    Check yourself: What can you cache on a CDN besides images and video?

    Anything identical for every requester with the same key: API responses for public data, anonymous HTML, redirect responses, even 404s. The test is whether a response can be shared. If it depends on the user, keep it private or cache only the shared fragments.

    Read this block →

  7. Spread a hot key

    Latency & performancesenior~5 min

    One celebrity key can still overload one cache node; finish with the fix for that.

    One celebrity record or one counter overwhelms the single cache node that owns it.

    Say it like this: One key is taking more traffic than a single cache node can serve, so I replicate it under suffixed names across nodes and add a tiny per-server cache, trading brief staleness on that key for linear read capacity.

    Adds to the design: Redirect service, Hot alias copies

    Check yourself: Why does sharding not solve a hot key?

    Sharding places each key on exactly one node by hashing it, so all traffic for that key lands on that node no matter how many nodes there are. Only replication, having the same key on several nodes, divides the read load.

    Read this block →

  8. Putting it together

    How the blocks above combine into one design for URL Shortener. The numbers on the boxes are the steps that introduce each part.

    The URL shortener read path, assembled from the path
    Link creatorcreates, then opensthe linkURL creation serviceAmazon EC2 Auto Scalinginsert row, then DELaliasPrimary databaseAmazon Auroraall writes; recentwriters read hereVisitor's browserGET /aB3xZ9CDN edgeAmazon CloudFrontTLS and static assets;302 passes throughRedirect serviceAmazon EC2 Auto Scalingstateless; local LRUfor hot aliasesRead replicasAmazon Auroraasync, a few hundredms behindRefresh lockone reload per expiredkeyRedis cacheAmazon ElastiCachealias to long URL, TTLplus jitterHot alias copiesalias#1 to #4 on fournodesStep 2: Invalidate the cache when data changes2Step 4: Spread reads across replicas4Step 5: Let users see their own writes5Step 6: Serve static bytes from the edge6Step 7: Spread a hot key7Step 4: Spread reads across replicas4Step 3: Protect against a cache stampede3Step 1: Cache the hot reads1Step 7: Spread a hot key7GET /aliasforward1. lookup2. on missrecent writerreplicatePOST /urlsinserthot key expiredcelebrity alias

    Each number is a step of this path; a box with two numbers is shaped by both blocks. The ring colour is the block's category, as on the route map. Boxes without a number come from the problem itself. Point at a step below, or at a bubble, to see where it appears.

    1. Cache the hot reads
    2. Invalidate the cache when data changes
    3. Protect against a cache stampede
    4. Spread reads across replicas
    5. Let users see their own writes
    6. Serve static bytes from the edge
    7. Spread a hot key

    A visitor reaches the redirect service through the CDN, which serves static assets and lets the 302 through. The service answers from Redis, falls back to a replica on a miss, and sends a link creator to the primary for a short window so their new link works at once.

    How each block shows up in the design

    • 1. Cache the hot reads: the redirect service reads Redis first and only falls back to the database on a miss, writing the long URL back with a TTL, so the 100-to-1 read load never reaches the database.
    • 2. Invalidate the cache when data changes: an edit or delete commits to the primary and then deletes the cached alias, so a deleted link stops redirecting on the next request rather than when its TTL runs out.
    • 3. Protect against a cache stampede: when a popular alias expires, one request takes a short refresh lock and reloads it while the rest are served the old value, and TTLs carry jitter so a batch of links never expires together.
    • 4. Spread reads across replicas: misses go to read replicas instead of the primary, which keeps the primary free for writes; replicas lag by a few hundred milliseconds at most.
    • 5. Let users see their own writes: for a short window after creating a link, that creator's reads go to the primary, so the link they just made never misses because a replica has not caught up.
    • 6. Serve static bytes from the edge: the CDN terminates TLS and serves the site's static assets near the user, but the 302 itself passes through so every click is counted.
    • 7. Spread a hot key: a viral alias is copied under suffixed keys across several Redis nodes, and each redirect server keeps a tiny local cache of the hottest aliases, so one link cannot overload one cache node.
  9. ★

    URL Shortener (TinyURL / bit.ly)

    Now run the timed practice. The blocks above should appear in your answer without prompting; if one does not, that is the one to reread.

The same parts on other clouds

The diagrams above name AWS services as one concrete example. Every part has a close equivalent elsewhere. In an interview, name the role first, such as “a managed Redis cache”, then the product you would pick.

AWSUsed here asGoogle CloudMicrosoft AzureOpen source and others
Amazon EC2 Auto ScalingURL creation service, Redirect service, Service, Read router, App serverCompute Engine managed instance groupsVirtual Machine Scale SetsKubernetes Deployment with a HorizontalPodAutoscaler, Nomad
Amazon AuroraPrimary database, Read replicas, Database, Primary, Replica 1, Replica 2, Replica 3, Replica A, Replica B, Posts storeAlloyDB for PostgreSQL, Cloud SQLAzure Database for PostgreSQL or MySQLPostgreSQL, MySQL, CockroachDB
Amazon CloudFrontCDN edge, Edge PoP, Origin shieldCloud CDN, Media CDNAzure Front DoorCloudflare, Fastly, Akamai
Amazon ElastiCacheRedis cache, RedisMemorystoreAzure Managed RedisRedis, Valkey, Memcached
Amazon S3Origin / object storeCloud StorageBlob StorageCloudflare R2, MinIO, Ceph