interviewpath
  • 0day streak
  • 10total XP
  • Level 1
0/6

Unit 5 · Distributed & cloud · Lesson 5 of 14

Partitioning, hot keys and caching

Partitioning spreads data and load across machines; caching keeps hot data close to where it is used. Choosing partition keys, rebalancing with consistent hashing, handling hot keys and picking cache policies that stay correct under concurrency are recurring design-interview topics and everyday backend work.
About 4 hFocus mode

Step 1: Learn the ideas

  • Partitioning by key range versus by hash
  • Choosing partition keys from access patterns
  • Consistent hashing and virtual nodes
  • Rebalancing and request routing
  • Secondary indexes: local versus global
  • Skew, hot keys and hot partitions
  • Cache-aside, read-through, write-through and write-back
  • TTLs, invalidation and negative caching
  • Cache consistency races and leases
  • Stampede control: coalescing, jittered TTLs, early refresh
  • Cold caches and dependence on hit rate

Why it matters

Once data or traffic outgrows one machine you split it, and the split decides which queries are cheap, which are expensive and which machine melts when one customer goes viral. Caches then hide most reads from the store, until they fail, go cold or serve stale data. In a design interview, "how would you shard this?" and "what would you cache, and how do you keep it correct?" arise naturally, and the follow-ups concern skew and failure, not the happy path.

Core ideas

Range versus hash partitioning. Range partitioning keeps keys sorted, so range scans touch few partitions, but sequential keys (timestamps, auto-increment IDs) pile writes onto one partition. Hash partitioning spreads keys evenly and keeps point lookups cheap, at the price of range locality. A compound key (hash of a user ID, then a sorted timestamp within it) often gets both: even spread across users and efficient scans within one user.

Consistent hashing. Hash-mod-N remaps almost every key when N changes. Placing nodes and keys on a hash ring, with each key owned by the next node clockwise, means a join or leave moves only about 1/N of the keys. Virtual nodes (many ring positions per machine) smooth out uneven arcs, let a machine's share follow its capacity, and spread a failed node's load over many survivors instead of one neighbor. Another common approach is a fixed number of partitions, much larger than the node count, moved whole between nodes; both avoid mass reshuffling.

Hot keys. No hash function splits a single key. Options: append a small random suffix to spread writes for a hot key across sub-keys (and merge on read), replicate hot read-mostly keys to several cache nodes, cache them briefly inside application servers, and coalesce identical concurrent requests. Detect hotness with per-key sampling; averages hide it.

Cache policies.

  • Cache-aside: the application reads the cache; on a miss it reads the store and fills the cache; on a write it updates the store and deletes the entry. Simple; the consistency races are yours.
  • Read-through / write-through: the cache layer loads from and writes to the store itself. Write-through keeps the cache fresh at the cost of write latency.
  • Write-back: writes land in the cache and are flushed later. Fast, but acknowledged data is lost if the cache dies before flushing.

Invalidation races. With cache-aside, a reader can miss, read the old value from the store, stall, and fill the cache after a writer has updated the store and deleted the entry, leaving stale data until the TTL expires. Fixes: leases or tokens handed out on a miss and invalidated by deletes, versioned sets that refuse to overwrite newer data, and short TTLs as a backstop. TTLs bound staleness; they do not provide correctness.

Stampedes. When a popular entry expires, many requests miss together and hit the store at once. Controls:

  • Request coalescing (single flight): one caller recomputes, the others wait for its result.
  • Jittered TTLs: randomize expiry so entries written together do not expire together.
  • Probabilistic early refresh: each reader recomputes slightly before expiry with a probability that rises as expiry nears, so one reader refreshes while the rest still hit.
  • Serve stale while revalidating where the product tolerates it.

Capacity depends on the cache. If the store can only handle a fraction of total reads, a flush, cold restart or lost cache node becomes a store outage. Plan warm-up, cap concurrent misses and know what the store can absorb.

Common misconceptions

  • "Hashing removes hot spots." It removes skew across keys, not load on one key.
  • "Delete-on-write cache-aside is always consistent." Concurrent readers can repopulate stale values; use leases, versions or accept bounded staleness explicitly.
  • "A longer TTL always reduces load." It increases staleness and can synchronize expirations; tune per data type and add jitter.
  • "The cache is an optimization, so losing it is harmless." If the store cannot serve the uncached load, losing the cache is an outage.
  • "Consistent hashing balances load perfectly." Without virtual nodes arcs are uneven, and request skew remains either way.

How to approach it

Read DDIA Ch. 6, the Dynamo paper's partitioning section and the Builders' Library caching article. If your cloud coursework involved memcached, revisit it with these questions: what was the key-popularity distribution, what would a stampede look like, how would you shard the keys? Graduates should choose a sensible partition key and cache-aside with TTLs. Mid-level candidates should handle hot keys, invalidation and stampedes. Senior candidates should quantify cache dependence, plan rebalancing and warm-up, and treat consistency races explicitly.

Suggested order

  1. 1Read DDIA Ch. 6 (Partitioning): key-range and hash partitioning, "Skewed Workloads and Relieving Hot Spots", secondary indexes and rebalancing.
  2. 2Read sections 4.2 (Partitioning Algorithm) and 4.3 (Replication) of the Dynamo paper for consistent hashing with virtual nodes.
  3. 3Simulate consistent hashing in a short script: 10 nodes and 100,000 keys with 1 and with 100 virtual nodes per node; measure the load spread and the keys moved when a node joins.
  4. 4Read the Builders' Library article "Caching challenges and strategies" and list each failure mode it describes.
  5. 5Read the parts of "Scaling Memcache at Facebook" on leases and invalidation (or the 6.5840 LEC 16 notes), then the XFetch paper's algorithm description.
  6. 6Implement LRU Cache, then write single-flight request coalescing around a slow function and test it with concurrent callers.

Step 2: Check off what you can do

Tap each one you can genuinely do or explain. Each earns 10 XP.

Step 3: Go deeper

  • Designing Data-Intensive ApplicationsStart here

    O'Reilly Media (author's book site)

    Section: Ch. 6: Partitioning

    Range versus hash partitioning, skew, secondary indexes, rebalancing and request routing.

    Open(opens in a new tab)Link responded, 5 Oct 2026
  • Caching challenges and strategiesStart here

    Amazon Builders' Library

    Practical cache design: TTLs, negative caching, cold caches and dependence on hit rate.

    Open(opens in a new tab)Link responded, 5 Oct 2026
  • Dynamo: Amazon's Highly Available Key-value Store

    All Things Distributed (Werner Vogels)

    Section: Sections 4.2 (Partitioning Algorithm) and 4.3 (Replication)

    Consistent hashing with virtual nodes in a production key-value store.

    Open(opens in a new tab)Link responded, 5 Oct 2026
  • Scaling Memcache at Facebook

    USENIX

    Leases against stale sets and thundering herds, invalidation and cold-cluster warm-up in a large look-aside cache.

    Open(opens in a new tab)Link responded, 5 Oct 2026
  • Optimal Probabilistic Cache Stampede Prevention

    VLDB Endowment

    Probabilistic early refresh as a stampede-prevention technique.

    Open(opens in a new tab)Link responded, 5 Oct 2026

Step 4: Practice

Implement LRU Cache to make eviction concrete, then run two short simulations: consistent hashing with and without virtual nodes (measure the max-to-mean load ratio and the fraction of keys moved on a join), and a stampede (many concurrent readers of an expiring key, with and without coalescing and jittered TTLs, counting store hits). Finally, design the cache layer for a read-heavy profile service and write down its invalidation race and how you close it.

Record attempts on each problem’s page (+15 XP, +10 more when solved on your own).

Step 5: Test yourself

Answer each one out loud or on paper before you finish the lesson.

  1. Question 1Why do auto-increment or timestamp keys create hot partitions under range partitioning?
  2. Question 2What happens to the backing store if the cache tier restarts empty at peak traffic?
  3. Question 3When would you choose write-through over cache-aside, and what does write-back risk?
  4. Question 4How would you detect a hot key in production?
  5. Question 5Why do TTLs need jitter?
  6. Question 6How does a global secondary index change the cost of a write?

You’re done when you can

  • Choose and justify a partition key for two unseen workloads, including how each handles its hottest key.
  • Explain consistent hashing and virtual nodes and estimate the fraction of keys moved when one node joins a cluster of N.
  • Describe a cache-aside stale-set race and one mechanism that prevents it.
  • Name three stampede controls and when each is appropriate.

Finish the lesson

How confident do you feel?

Lesson complete!

+50 XP

Reviews will come up on the Practice tab so it sticks.

Unlocks next: System design method, OLTP vs OLAP, distributed joins and distributed transactions

Your notes and study time

Log study time