Design a Distributed Cache for High-Traffic Static Assets
System DesignModel answerLast updated
Design a globally distributed caching layer that serves small static assets at hundreds of thousands of requests per second with sub-50ms latency and resilience to origin failures.
Design a Distributed Cache for High-Traffic Static Assets
Your platform serves large volumes of small static files — think icons, thumbnails, and UI asset images — to users around the world. The files are small (typically under 25 KB each), read far more often than they are written, and must be retrievable with minimal latency regardless of where the user is located.
Functional Requirements
GET /asset/{id}— retrieve an asset by ID.PUT /asset/{id}— upload or replace an asset; the previous cached version must no longer be served after an update.- The system should support versioning so that clients pinning a specific version can continue doing so, while other clients always receive the latest.
Non-Functional Requirements
- Latency: p99 response time under 50 ms for globally distributed users.
- Availability: the system must keep serving assets even if the origin data store experiences intermittent outages.
- Burst handling: popular assets must not cause cascading failures when their cache entries expire or are invalidated simultaneously.
What to Cover
- Cache topology: how many tiers, where they sit, and why.
- Invalidation strategy: how an update propagates globally while keeping the system eventually consistent.
- Degraded-mode behavior: what happens when the origin is unreachable, and what staleness guarantees you offer.
- Hot-key problem: how the design prevents a single wildly popular asset from overwhelming any layer.
Expected Output
Describe the end-to-end architecture and data flow for both reads and writes. Discuss the trade-offs in your consistency model. Explain how the system behaves during a regional failure and during an origin-side outage. Numbers and sizing estimates are expected.
Hints
Hint 1
Start by estimating the working set size. If the hot 1% of assets drives 90% of reads, does that hot set fit in memory? Your answer determines whether a memory-only regional tier is feasible and what capacity to provision there.
Hint 2
Think about what makes cache invalidation hard at global scale: you have many edge nodes, invalidation events can arrive out of order, and a TTL safety net is the last line of defense. Versioned, immutable URLs sidestep most of this — sketch out how that changes the write path.
Hint 3
The thundering herd is not one problem but several: simultaneous expiry of related keys, a flood of misses during a purge, and a single Redis shard melting under hot-key traffic. Walk through each scenario and name a concrete mitigation for each one.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
1. Size the System First
Interviewers watch whether your architecture choices are driven by numbers or intuition. Anchor on a few key figures before drawing any boxes.
| Parameter | Estimate |
|---|---|
| Peak read QPS | 300k globally (reads:writes ≈ 10,000:1) |
| Average asset size | 20 KB |
| Peak read bandwidth | 300k × 20 KB ≈ 6 GB/s |
| Total catalog | 500M assets × 20 KB ≈ 10 TB at origin |
| Hot working set | ~1% of assets → ~90% of traffic → ~100 GB |
| Latency budget | p99 < 50 ms — this rules out cross-ocean round trips (~150 ms) on the critical path |
The hot working set fitting in roughly 100 GB is the central insight. It means a regional in-memory cache can absorb nearly all reads before they touch origin. A single cross-ocean trip blows the latency budget, so the edge tier must serve the majority of requests locally.
Clarify with the interviewer before proceeding: Are assets public or access-controlled? How quickly must an update be visible — seconds or minutes is fine, i.e. eventual consistency? Is serving a briefly stale asset acceptable during an origin outage? Assume yes to both.
2. API Design
A clean versioning scheme eliminates most invalidation complexity upfront.
GET /asset/{id} → 302 to /asset/{id}/v{n} (short TTL: 30–60 s)
GET /asset/{id}/v{n} → bytes, Cache-Control: public, max-age=31536000, immutable
PUT /asset/{id} → If-Match: v{n}; returns new version identifier v{n+1}
The unversioned URL is a mutable pointer to the current version. It is cached briefly and purged on every write — a cheap operation because the object is tiny.
The versioned URL is immutable by definition. It can be cached forever at every tier, including the client browser, with no purge ever needed. Clients that embed v{n} in their own data (manifests, feeds) skip the redirect entirely.
This design converts a hard global-invalidation problem into a cheap pointer update.
3. Cache Topology
Client (browser/app cache)
│
Anycast / GeoDNS
│
Edge PoPs (~100+ locations, CDN) L1 — SSD/RAM, hot objects only, ~90% hit rate
│ miss
Regional shields (4–6 per continent) L2 — Redis or CDN mid-tier, holds full hot set
│ miss (~100 GB RAM per region), ~99% cumulative hit rate
Origin service (stateless, autoscaled) reads metadata store + blob store
│
Metadata DB + Blob store (multi-region replicated)
Read flow: the edge checks L1. On a miss it routes to the regional shield — never directly to origin. The shield collapses all concurrent misses for the same key into a single upstream fetch (request coalescing). A shield hit typically adds 20–30 ms, staying within the p99 budget.
Write flow:
- New bytes land in the blob store under key
assets/{id}/v{n+1}. - A conditional update (compare-and-swap on version) bumps the pointer in the metadata DB.
- An event
{id, new_version}is published to a global pub/sub topic (Kafka with MirrorMaker, SNS, or GCP Pub/Sub). - Regional invalidation workers consume the event, delete the pointer key from L2, and call the CDN purge API for
/asset/{id}. The versioned object at/asset/{id}/v{n}needs no purge — it is permanently correct for that URL.
Staleness window: event propagation typically takes 1–5 s. The 60 s TTL on the pointer is a safety net if an event is lost.
4. Handling the Thundering Herd
This is the part that separates good answers from great ones. There are several distinct failure modes:
Simultaneous expiry. Apply TTL jitter (±10–20%) so keys created together do not all expire at the same moment.
Stampede on expiry. Use stale-while-revalidate: serve the cached value immediately and trigger one background refresh. The cache entry stays warm throughout.
Probabilistic early refresh (XFetch). Begin refreshing a key with increasing probability as its TTL winds down, so the revalidation usually completes before expiry ever hits.
Hot-key shard saturation. A single asset receiving 50k+ QPS can melt one Redis shard. Detect keys above a threshold using a count-min sketch counter, then replicate those keys across all shards in L2, or pin them in a small in-process cache at the edge or shield layer. Because hot versioned assets never expire, most of this problem goes away once clients adopt versioned URLs.
5. Degraded-Mode Behavior
Origin outage:
- Configure
stale-if-errorat every tier: on a 5xx or timeout from origin, serve the most recently cached object up to a defined max staleness (e.g. 24 h) and emit an alert metric. - Place a circuit breaker in front of origin. When open, shields serve stale only and probe origin with a low trickle of requests.
- Apply brief negative caching (5–10 s) for 404 responses so a missing-key request does not hammer origin repeatedly.
- Writes fail cleanly with a 503 during the outage; reads keep working because the hot set lives entirely in L2.
Regional outage:
- GeoDNS health checks reroute traffic to the nearest healthy region within 30–60 s.
- Provision ~1.5× headroom per region so any single region can absorb a neighbor's traffic.
- Expect a brief spike in miss rate in the receiving region as its L2 warms up; request coalescing at the shield absorbs the origin pressure during that period.
6. Trade-off Summary
| Decision | Benefit | Cost |
|---|---|---|
| Versioned immutable URLs | Near-100% edge hit rate; trivial invalidation | Extra redirect hop; clients must track versions |
| Push invalidation via pub/sub | Freshness in seconds | Operational complexity; needs TTL backstop |
| TTL-only invalidation | Simple to operate | Staleness equals TTL; shortening TTL hurts hit rate |
| Serve stale on origin error | High read availability | Clients may briefly see outdated assets |
| Two-tier edge + shield | Shields origin; aggregates misses | One extra hop on L1 miss |
Common Mistakes
- Designing a single global cache tier with no regional shielding — origin sees every edge miss directly.
- Relying solely on TTLs for consistency with no push invalidation, leaving staleness windows too wide.
- Treating "thundering herd" as a single problem solved by one mechanism, rather than layering defenses.
- Forgetting that invalidation events can arrive out of order; a cache should only accept a version update if it is monotonically higher than what it already holds.
- Neglecting the write path entirely — uploads and version bumps need to be atomic or protected with compare-and-swap to avoid version conflicts under concurrent writes.