Skip to content

Cache

Why cache?

Caching improves page-load times and reduces load on servers and databases. The dispatcher first checks if a request has been served before and returns the previous result, saving the actual execution.

Databases benefit from uniform read/write distribution. Popular ("hot") items skew the distribution and cause bottlenecks — a cache in front of a database absorbs uneven loads and traffic spikes.

Where caches live

  • Client caching — browser or OS.
  • CDN caching — CDNs are a type of cache.
  • Web server caching — reverse proxies and caches like Varnish serve static/dynamic content directly.

  • Database caching — DBs include some caching by default; tune it for your usage patterns.

  • Application caching — in-memory key-value stores (Memcached, Redis) between the app and data storage.

  • Data in RAM is far faster than disk-backed DBs.

  • RAM is limited, so use eviction algorithms like LRU (least recently used).
  • Redis adds persistence and built-in data structures (sorted sets, lists).

Levels you can cache

Two broad categories — database queries and objects:

  • Row level
  • Query level
  • Fully-formed serializable objects
  • Fully-rendered HTML

Avoid file-based caching — it makes cloning and auto-scaling harder.

Caching at the database query level

Hash the query as a key and store the result. Downside — expiration issues:

  • Hard to delete a cached result for complex queries.
  • If one cell changes, you must delete all cached queries that might include it.

Caching at the object level

Treat data as objects (like in app code); assemble the DB result into a class instance or data structure:

  • Remove the object from cache when its underlying data changes.
  • Enables async processing: workers assemble objects from the latest cached object.

Good things to cache: user sessions, fully-rendered pages, activity streams, user graph data.

When to update the cache

Cache-aside (lazy loading)

The application is responsible for reading/writing storage; the cache doesn't touch storage directly.

  1. Look for entry in cache → cache miss.
  2. Load entry from database.
  3. Add entry to cache.
  4. Return entry.
def get_user(self, user_id):
    user = cache.get("user.{0}".format(user_id))
    if user is None:
        user = db.query("SELECT * FROM users WHERE user_id = {0}".format(user_id))
        if user is not None:
            cache.set("user.{0}".format(user_id), json.dumps(user))
    return user

Used by Memcached. Only requested data is cached (no filling cache with junk).

Disadvantages: each miss = 3 trips (latency); data can go stale (mitigate with TTL or write-through); a failed node is replaced by an empty one.

Write-through

The app uses the cache as the main data store; the cache writes through to the DB.

  1. App adds/updates entry in cache.
  2. Cache synchronously writes to data store.
  3. Return.

Slow overall (write op), but subsequent reads are fast, and cache data is not stale.

Disadvantages: a new node won't cache entries until they're updated in the DB (combine with cache-aside); much written data is never read (use TTL).

Write-behind (write-back)

  1. App adds/updates entry in cache.
  2. Cache asynchronously writes to data store → faster writes.

Disadvantages: data loss risk if the cache dies before flushing to the store; more complex to implement.

Refresh-ahead

Cache automatically refreshes recently-accessed entries before they expire. Reduces latency vs read-through if the cache can predict future needs.

Disadvantage: poor prediction makes performance worse.

Strategy comparison

Strategy Write path Read freshness Risk
Cache-aside App writes DB directly Can be stale (TTL) Miss latency, stale data
Write-through Sync via cache Fresh Slow writes, cold cache
Write-behind Async via cache Fresh-ish Data loss on crash
Refresh-ahead — Proactive refresh Bad predictions

Disadvantages of caching overall

  • Must maintain consistency between cache and source of truth (invalidation).
  • Cache invalidation is hard — deciding when to update adds complexity.
  • Requires app changes (adding Redis/Memcached).

Key takeaways

  • Caching is the highest-leverage performance tool, but its cost is staleness and invalidation complexity.

  • "There are only two hard things in Computer Science: cache invalidation and naming things."

Common Interview Questions

Design a cache system like Memcached

Why it's asked here: the direct cache question.

Key points to discuss:

  • In-memory KV, eviction policy (LRU), and sharding across nodes.
  • Consistent hashing to minimize reshuffling when nodes change.
  • Cache-aside (lazy loading) flow and the cache-miss cost.
  • Invalidation and TTL to manage staleness.
flowchart LR
    A[App] -->|get| C[(Cache cluster)]
    C -->|miss| DB[(Database)]
    DB --> C
    C -->|consistent hashing| N1[Node 1]
    C -->|consistent hashing| N2[Node 2]
Design a key-value store for a search engine (query cache)

Why it's asked here: caching query results is a classic query-level cache.

Key points to discuss:

  • Cache query → results; hit ratio drives value.
  • Query-level vs object-level caching trade-offs.
  • Invalidation: hard to delete cached results for complex queries.
  • Eviction + TTL for the long tail of queries.
flowchart LR
    Q[Query] --> C[(Query cache)]
    C -->|hit| R[Result]
    C -->|miss| E[Search engine]
    E --> C
Design a news feed / Twitter timeline (cache fan-out)

Why it's asked here: timelines are served from cache via fan-out.

Key points to discuss:

  • Precompute and cache each user's timeline (fan-out on write).
  • Redis sorted sets / lists for timeline storage.
  • Cache update strategies: write-through vs write-behind vs cache-aside.
  • Staleness vs performance for celebrity (hot) users.
flowchart LR
    P[Post] --> F[Fan-out on write]
    F --> T[(Timeline cache)]
    U[User] --> T
    T -->|miss| D[(Sharded tweets)]

Further reading


Design a Cache System Like Memcached

The cache is an in-memory key-value store positioned between stateless application servers and the source-of-truth database. To establish requirements and scale, assume a service with 10 million daily active users, a peak load of about 1 million operations per second, a 90/10 read/write split, and an average cached value of 1 KB. The functional requirements are to support get, set, delete, expiration, atomic compare-and-swap updates, and simple increment/decrement operations for counters. The non-functional requirements include sub-millisecond p50 latency on cache hits, very high throughput, bounded memory on each node, horizontal scalability by adding nodes, and the ability to degrade safely when a node fails. The cache is not the system of record; the backing database remains authoritative, so cached data can be repopulated after failures or evictions.

The high-level architecture uses a cluster of independent Memcached nodes with no master node and no node-to-node communication. Application servers embed a Memcached client library that shards keys across the cache nodes using consistent hashing. When an application needs a value, it hashes the key to select a node and sends a get command. On a hit, the node returns the stored byte string. On a miss, the application loads the value from the database, writes it back to the chosen cache node with a TTL, and returns it to the caller. Writes follow a cache-aside or write-through style: the application updates the database and then updates or invalidates the corresponding cache entry. Because nodes are independent, the cache tier can grow by adding nodes and updating the client-side hash ring.

Data is stored in RAM as a flat key-to-item mapping. Each item contains the value, flags, an expiration timestamp, and a CAS version number. Memcached uses a slab allocator that divides memory into size classes and assigns items to slabs based on item size, which reduces fragmentation and avoids per-object allocation overhead. The store is intentionally not persistent: if a node restarts, all data on that node is lost and must be repopulated from the database. Values are opaque byte strings from the perspective of the cache, so schema concerns remain with the application. This model is appropriate because the workload requires many simple hot lookups and tolerates losing cache contents rather than durable storage or rich queries.

The core mechanism is client-side consistent hashing combined with per-node LRU eviction and lazy expiration. Consistent hashing maps each key to a point on a ring and each cache node to one or more virtual points, so only a small fraction of keys move when nodes are added or removed. This avoids the large miss storm that simple modulo sharding would cause. Inside each node, a hash table provides O(1) lookup, while a per-slab LRU list tracks recently used items. When a slab needs space for a new item, the least-recently-used item in that slab is evicted. Expired items are treated as misses when accessed and are reclaimed lazily rather than by a dedicated background timer. Compare-and-swap lets clients perform optimistic updates only when an item has not changed since it was read, preventing a request from overwriting a newer value.

For scaling and availability, the cache tier scales horizontally by adding nodes and memory. Consistent hashing keeps key movement low and allows the cluster to grow during traffic peaks. Memcached nodes do not replicate each other, so losing a node means its cached keys miss and the database temporarily absorbs more load; clients can detect a failed node, remove it from the ring, and continue serving. The database must be sized to tolerate a cold-cache or node-failure scenario. To reduce the impact of hot keys and cache stampedes, applications commonly use TTL jitter, lease-based reads for expensive misses, and multiple cache clusters when availability matters more than perfect consistency. Client libraries perform load distribution, so there is no separate cache load balancer.

The main trade-offs are memory cost versus database load, consistency versus latency, and simplicity versus availability. Keeping data in RAM gives very low latency but limits capacity and costs more per gigabyte than disk-backed stores. Memcached provides weak consistency by design: after a database update, a cache entry may remain stale until its TTL expires or the application invalidates it. The lack of persistence and replication keeps the system simple and fast, but a failed node causes temporary misses and more database traffic. Consistent hashing reduces reshuffling but can create uneven load unless virtual nodes or weight adjustments are used. Finally, choosing a simple key-value model makes operations fast and easy to reason about, but versioning and invalidation must be handled explicitly by the application.

flowchart LR
    A[Application Servers] --> C1[Memcached Node 1]
    A --> C2[Memcached Node 2]
    A --> C3[Memcached Node 3]
    A --> DB[(Backing Database)]
    C1 --> DB
    C2 --> DB
    C3 --> DB
    A -->|consistent hashing get/set| C1
    A -->|cache miss read-through| DB
    C1 -->|miss/load| DB
    C2 -->|miss/load| DB
    C3 -->|miss/load| DB

Design a Key-Value Store for a Search Engine Query Cache

To size this store, assume the search service handles 10 billion queries per day, about 120,000 QPS at peak and roughly 30,000 QPS on average. The query cache stores only the hottest queries because search result sets are large and the long tail is not reused enough to justify memory. The functional requirements are GET for a cached query plus normalized parameters, SET on a miss, invalidation or purge when indexes or features change, and expiration through TTLs. The non-functional requirements include sub-millisecond cache access, a high hit rate, bounded memory, high availability, and graceful degradation to the search backend when the cache fails.

The high-level architecture places a Redis-compatible key-value cluster between stateless search API servers and the search backend. The API server normalizes the incoming query into a cache key, hashes it to a Redis shard, and performs a cache-aside read. On a hit, it deserializes and returns the stored ranked result list. On a miss, it queries the search engine, builds the result object, writes that object to the cache with a TTL, and returns the response to the user. A separate invalidation bus or control path broadcasts purge keys when the index or result model changes.

The data model is a key-value mapping from a canonical query descriptor to a serialized search-response object. The key encodes the normalized query text, market and language, search vertical, and any filters that materially affect results. Variants that produce identical result sets should be collapsed into one key to improve hit rate. The value contains document IDs, titles, snippets, ranking scores, sort parameters, and a short TTL. Redis is the right backing store because the workload needs point lookups, very high throughput, low latency, and bounded memory, and this cache is allowed to be ephemeral rather than the system of record.

The core mechanism is query-level cache-aside with normalization, TTLs, and LRU eviction. Because complex queries are hard to invalidate exactly, the design does not maintain a relational mapping from every index update to every affected query. Instead, it uses short TTLs for volatile query spaces, explicit purges for high-impact events, and LRU eviction to keep memory bounded. Queries for breaking news or celebrity names can become extreme hot spots, so the system may replicate a small number of hot entries or use request coalescing to avoid stampeding the backend on a miss. When many concurrent requests miss the same key, a single-flight or lock can perform one backend query and share the result.

For scaling and availability, the Redis cluster is partitioned by hash slots across multiple primary nodes, and each primary replicates asynchronously to at least one replica. Sentinel or cluster-managed failover promotes a replica when a primary fails. A failed cache is treated as a miss rather than an error, so the system remains available but temporarily loses the latency benefit. Sharding spreads both memory and request load, and consistent hashing helps reduce reshuffling when nodes change. The search API tier is stateless behind a load balancer, so cache clients can scale independently. Health checks remove failed cache nodes, while rate limits, timeouts, and circuit breakers protect the search backend when cache hit rate drops.

The central trade-off is freshness versus hit rate and backend load. Longer TTLs improve cache hits and reduce search backend cost but can serve stale results after index changes or breaking events. Query-level caching helps popular head queries a great deal, but personalized and long-tail queries often cannot be cached efficiently without exploding memory and lowering hit rate. Storing only serialized results keeps the store simple but means ranking or availability changes require new entries or invalidation. Finally, Redis gives high performance and replication at the cost of memory, and the cache is accepted as a transient, incomplete replica of the backend search result rather than a durable database.

flowchart LR
    U[User] --> LB[Load Balancer]
    LB --> A1[Search API 1]
    LB --> A2[Search API 2]
    A1 --> R1[(Redis Primary Shard 1)]
    A1 --> R2[(Redis Primary Shard 2)]
    R1 --> RP1[(Replica 1)]
    R2 --> RP2[(Replica 2)]
    A1 -->|miss| B[Search Backend / Index]
    A2 -->|miss| B
    A1 -->|purge| N[Invalidation Bus]
    N --> R1
    N --> R2