Caching

Make the common path fast without lying to your users.

Caching in 30 seconds

  • What: keep a copy of expensive data somewhere fast and close, so the common request is cheap.
  • The trade: you buy speed with freshness — a cached answer can be out of date.
  • Strategies: cache-aside (app fills on miss, the common default), read-through, write-through, write-behind — pick by read/write ratio and staleness budget.
  • Invalidation is the hard part: TTL, invalidate-on-write, or versioned keys — most systems combine a short TTL with on-write invalidation.
  • The stampede: a hot key expires and thousands miss at once — fix with TTL jitter, a per-key rebuild lock, or serve-stale-while-refresh.
  • Pitfalls to name: unbounded growth (set eviction), caching errors, and dual-write skew between cache and DB.

A barista who remembers your order

Picture a busy coffee shop. The first time you order, the barista has to ask your name, your drink, how you like it — it takes a minute. But a regular walks in and the barista already has it: 'the usual flat white, right?' No questions, no wait. The barista remembered the expensive-to-gather answer and kept it somewhere instant to reach. That's a cache. The catch is just as human: if you quietly switched to oat milk last week and the barista doesn't know, they'll happily make your old usual. Fast, but wrong. Every caching decision you'll ever make lives in that tension — speed from remembering, risk from remembering something that changed.

The problem it solves

Reading the same data from a slow source over and over is wasteful. A cache keeps a copy of expensive-to-produce data somewhere fast and close, so the common request is cheap. The trade you accept in return is freshness: a cached answer can be out of date.

To feel why this matters, you have to feel how uneven speeds are inside a computer. Reading a value already sitting in memory is on the order of nanoseconds. Reaching across the network to a database and back is on the order of milliseconds — roughly a hundred thousand to a million times slower. If a page needs the same user record for every one of a million requests an hour, fetching it fresh from the database each time is like driving across town to re-ask a question you already know the answer to.

The whole reason caching pays: memory is orders of magnitude closer than disk or network.

The core idea, plainly

A cache is a bet. You bet that the same data will be asked for again soon (temporal locality) and that a slightly stale answer is acceptable for a while. When the bet pays off, you turn a database read into a memory lookup. When it doesn't, you've added a layer that costs memory and can serve wrong data. Good caching is mostly about making that bet honestly and having a plan for when it's wrong.

Two words will follow you through the rest of this page, so pin them down now. A hit is when the data you asked for is already in the cache — the fast, happy case. A miss is when it isn't, so you fall back to the slow source and (usually) stash the result for next time. The fraction of requests that are hits is your hit rate, and it's the single number that decides whether a cache is earning its keep. A cache with a 10% hit rate is mostly just an extra hop that occasionally helps; one with a 95% hit rate is quietly carrying your system.

Why not just cache everything forever?

The tempting first instinct is: memory is fast, so put all the data in the cache and never expire it. Two things break that dream, and seeing them break is how you understand every design choice that follows.

  • Memory is small and expensive. Your database might hold terabytes on cheap disk; your cache holds gigabytes in costly RAM. You physically cannot keep everything, so something must decide what to throw out — that's eviction.
  • Data changes underneath you. The moment the source of truth updates, every copy you kept is a potential lie. If you never expire anything, you're guaranteeing that lie gets served — possibly for ever. That's the invalidation problem.

So a real cache always answers two questions: when something new arrives and the cache is full, what gets kicked out? and when the source changes, how does the stale copy get corrected? The first is eviction; the second is invalidation. Hold those two questions in mind — the strategies below are just different answers to them.

Cache-aside: the app owns the read-and-fill logic.

The simplest working cache: cache-aside

Start with the pattern you'll reach for 80% of the time, because it's the easiest to reason about. In cache-aside (also called lazy loading), the application code is in charge: it checks the cache first, and only on a miss does it go to the database and then stash the result. The cache is a side companion to the app, not something the app routes through — hence the name.

Cache-aside read with TTL (python)
def get_user(user_id):
    key = f"user:{user_id}"
    cached = cache.get(key)
    if cached is not None:
        return cached            # hit
    user = db.query("SELECT * FROM users WHERE id = ?", user_id)
    cache.set(key, user, ttl=60) # fill with a short TTL
    return user

def update_user(user_id, changes):
    db.update(user_id, changes)
    cache.delete(f"user:{user_id}")  # invalidate on write

Notice two beginner-friendly properties. First, the cache only ever fills with data someone actually asked for, so you don't waste memory on cold records. Second, if the cache server disappears entirely, the code still works — every request just becomes a miss and goes to the database. The cache is an optimization, not a dependency. That resilience is a big part of why cache-aside is the default.

Strategies and when each fits

The patterns differ in who writes the cache and when. Pick based on your read/write ratio and how much staleness you can tolerate.

StrategyHow it worksProsConsUse whenAvoid when
Cache-asideApp reads cache; on miss, reads DB and fills cache.Simple, resilient to cache outage, only caches what's used.First read is slow; risk of stale after writes.Read-heavy, tolerant of brief staleness.You need strict freshness on every read.
Read-throughCache library loads from DB on miss transparently.Clean app code; consistent load path.Couples you to a cache that understands your store.Many services share one caching layer.You want the app to control fallback logic.
Write-throughWrites go to cache and DB synchronously.Cache always fresh for written keys.Every write pays cache + DB latency.Write-then-read-soon patterns.Write-heavy with rarely-read data.
Write-behindWrite to cache; flush to DB asynchronously.Fast writes; absorbs bursts.Data loss window if cache dies before flush.High write throughput, some durability slack.You can't lose any acknowledged write.

The split that trips people up is read-through vs cache-aside — they look almost identical. The difference is who owns the miss logic. In cache-aside, your app notices the miss and goes to the DB. In read-through, the cache library itself knows how to load from the DB, so your app just asks the cache and never sees the database directly. Read-through gives cleaner app code; cache-aside gives you full control over the fallback. Both end with the same data in the cache.

Write-through: cache and DB stay in lockstep (python)
def set_user(user_id, user):
    key = f"user:{user_id}"
    db.save(user_id, user)       # write the source of truth first
    cache.set(key, user)         # then update the cache synchronously
    # cache is now fresh for this key; every write pays both latencies.
    # (write-behind would skip the wait and flush to db later, in the
    #  background -- faster writes, but a crash loses unflushed data.)

Eviction: deciding what to throw out

Because memory is finite, every cache eventually fills up, and a new entry can only go in if an old one comes out. The rule that picks the victim is the eviction policy, and the right choice depends on how your data is accessed.

PolicyEvicts...Good whenWeakness
LRU (least recently used)The entry untouched for the longest time.Recent access predicts future access (most apps).A one-off scan can flush out your hot set.
LFU (least frequently used)The entry asked for the fewest times.A stable set of genuine favourites.Slow to let go of yesterday's hot item.
FIFO (first in, first out)The oldest-inserted entry, regardless of use.Simple; order roughly tracks relevance.Evicts a hot item just because it's old.
TTL-onlyNothing early — entries just expire by clock.Natural freshness windows (prices, sessions).Can run out of memory before anything expires.

LRU is the sensible default for most workloads because recency is a strong signal: the thing you looked at a second ago is probably the thing you'll look at next. Reach for LFU only when you have a genuinely stable popular set and lots of one-off noise around it.

Invalidation: the genuinely hard part

There are two famously hard things, and cache invalidation is one of them. You have three honest options: expire by TTL (accept staleness up to the TTL), invalidate on write (delete or update the key when the source changes), or version the key (write a new key and switch readers over). Most real systems combine a short TTL with on-write invalidation as a backstop.

Why combine them instead of trusting one? Because each has a blind spot. Pure TTL serves known-stale data for up to the TTL window, even when you could have known sooner. Pure invalidate-on-write is precise, but if a single invalidation message is dropped — a crash, a network blip, a bug in a code path that forgot to invalidate — that key stays wrong for ever. Pairing them gives you the best of both: on-write invalidation makes the common case fresh immediately, and a short TTL is the safety net that guarantees any missed invalidation self-heals within, say, 60 seconds.

The gap a cache can't fill: it is not your source of truth

A tempting shortcut, especially with a fast store like Redis, is to treat the cache as the database — write to it, read from it, skip the slow store entirely. Resist it. A cache is designed to be allowed to forget: it evicts under pressure, it may be wiped on restart, and most deployments don't give it the durability guarantees a database does. The instant you depend on data only living in the cache, a routine eviction or a cache restart becomes silent data loss.

The mental model to keep: the source of truth is the thing you'd be heartbroken to lose, and the cache is a disposable fast copy of some of it. You should always be able to throw the entire cache away, take a latency hit while it refills, and lose nothing. If that isn't true, you don't have a cache — you have an under-protected database pretending to be one.

The stampede trap

When a hot key expires, thousands of requests miss at once and all hit the database together — a cache stampede (or thundering herd). Mitigate it with a short randomized jitter on TTLs, a per-key lock so only one request rebuilds the value, or by serving a slightly stale value while one worker refreshes in the background.

Picture it concretely. A celebrity's profile is cached and getting 50,000 reads a second — all hits, the database is idle and happy. The TTL ticks to zero. Now the next 50,000 requests all miss in the same instant, and all 50,000 slam into the database to recompute the exact same value at once. The database, which was doing nothing, suddenly gets a year's worth of load in a second and falls over — taking the cache's ability to refill down with it. The data didn't change; the expiry was the trigger.

Single-flight rebuild with a per-key lock (python)
def get_with_lock(key):
    cached = cache.get(key)
    if cached is not None:
        return cached                 # hit, no stampede risk
    # only one request wins the lock and rebuilds; the rest wait.
    if cache.set_nx(f"lock:{key}", 1, ttl=5):   # atomic set-if-absent
        value = db.load(key)          # the single DB hit on a miss
        cache.set(key, value, ttl=60)
        cache.delete(f"lock:{key}")
        return value
    sleep(0.05)                       # loser backs off, then re-reads
    return get_with_lock(key)         # by now the winner has filled it

The single-flight lock turns 50,000 simultaneous database hits into exactly one. Adding a little random jitter to TTLs (say, 60 seconds plus or minus 10) is the cheap partner trick: it stops thousands of keys that were cached together from all expiring on the same tick, spreading the refill load over time instead of bunching it.

Where caches live: the layered view

Caching isn't one box — it's a habit that repeats at every layer between the user and the data. Each layer catches the requests the layer above it couldn't, so the database sees only the small trickle that truly needs it.

  • Browser cache — the user's own machine remembers images, scripts, and responses, so a revisit hits nothing at all.
  • CDN / edge cache — a copy near the user's region serves static assets and cacheable responses without ever reaching your origin (see CDN).
  • Application cache — an in-memory store like Redis or Memcached in front of the database holds hot records and computed results.
  • Database cache — the DB's own buffer pool and query cache keep recently-touched pages in memory.
  • Local/in-process cache — a plain in-memory map inside a single service instance, the fastest of all but not shared between instances.

A single request can breeze past several of these. The design question is always how close to the user can I safely answer this? The closer the cache, the faster and cheaper the hit — but the harder it is to invalidate, because you don't control the user's browser the way you control your own Redis.

Caching is the first lever almost every system reaches for when reads get hot — it's how you buy large amounts of speed cheaply, as long as you're honest about the freshness you're trading away.

Why it matters

  • It turns a database read into a memory lookup, shaving latency and shielding your data tier from load.
  • It's often the difference between a system that scales reads smoothly and one that falls over on a hot key.
  • It forces an explicit conversation about how stale is acceptable — a question every design should answer.

If ignored

  • A celebrity-profile hotspot or viral page hammers the database until it buckles.
  • A cache with no invalidation story serves confidently wrong data long after the source changed.
  • A hot key expires and a stampede of simultaneous misses knocks the origin over.

Where it fits

  • Sits on the read path, between the application and the slow source of truth.
  • Appears at every layer — browser, CDN edge, application cache, and database query cache.
  • Leans on eviction policies and TTLs; pairs with a CDN to push caching all the way to the user's region.

Related topics

  • CDN: caching pushed to the network edge, close to the user
  • Latency & throughput: the numbers that make a memory hit worth chasing
  • Consistency models: stale reads are the consistency cost a cache introduces
  • Pub/Sub & CDC: a clean way to invalidate caches when the source data changes

Interview lens

Questions it unlocks

  • Design the read path for a URL shortener or news feed.
  • How would you keep a product price consistent across a cache and the database?
  • A hot celebrity profile is overloading the DB — what do you do?

60-second answer

Lead with the read/write ratio and the staleness budget — those pick the strategy. For a read-heavy, staleness-tolerant path I'd use cache-aside with a short TTL plus invalidate-on-write as a backstop. I'd call out the stampede risk on hot keys and mitigate with TTL jitter and single-flight rebuilds. Then I'd name the consistency trade: the cache can be briefly wrong, and that's acceptable here because the business impact of a few seconds of stale data is low.

Common traps

  • Reaching for a cache before establishing there's a real read-heavy hotspot.
  • Ignoring invalidation entirely and claiming the cache is 'always fresh'.
  • Forgetting the stampede on expiry of a hot key.
  • Treating the cache as a source of truth and losing data when it evicts or restarts.

Search topics

↑↓ to move · Enter to open · Esc to close