Caching in system design
42 questions in 10 subtopics.
Caching is one of the most effective tools in system design and one of the most common sources of incidents. A cache cuts latency and protects databases, but it also creates a second copy of data that can be stale, a load-bearing layer whose loss can overwhelm the backend, and synchronized expiries that turn into traffic spikes. Caches appear at many levels: in-process caches such as Caffeine, shared caches such as Redis, CDNs at the edge and HTTP caches in browsers and proxies. The questions cover the main read and write patterns, expiry and invalidation design, stampedes, penetration and avalanches, multi-level and local caches, CDN and HTTP caching headers, and keeping caches consistent with databases, from how each mechanism works to the strategy and cost decisions that senior engineers and leaders own.
Cache-aside, read-through and write-through
Cache-aside lets the application load and fill the cache on a miss, read-through hands loading to the cache itself, and write-through updates cache and store together on writes. Understand how the hit ratio translates into backend load and latency, why the order of database and cache writes matters, and when a dedicated read-through layer can protect a slow system of record.
A profile service receives 20,000 reads per second. Redis answers in about 1 ms, the PostgreSQL database in about 15 ms, and the database is comfortable up to about 1,500 queries per second.
How does the cache hit ratio determine database load and average latency here, and what hit ratio does the service need to stay safe?A Spring Boot service looks up currency exchange rates from a slow internal service. One developer writes cache-aside code by hand; another proposes a read-through cache, where the cache itself knows how to load a missing value.
Implement the lookup as a read-through cache with Caffeine'sLoadingCache, and explain what changes compared with hand-written cache-aside code.A profile service writes changes to Redis first and then to PostgreSQL in the same method, so readers see changes immediately. During a 3-minute database failover about 0.3 percent of updates returned HTTP 500, yet users saw those changes in the app and then saw them disappear about an hour later.
Explain what happened, and how should the write path be ordered and built so the cache never shows data the database does not have?A legacy policy administration system answers lookups in 300 ms and its owners allow at most 500 requests per second. New customer-facing apps need 20,000 lookups per second at under 50 ms, and policies change a few thousand times a day, only through the legacy system.
Design a caching layer that meets the new load without breaking the legacy limit, including how it is filled, refreshed and protected.A vendor proposes an in-memory data grid with read-through and write-through to your databases, claiming it would remove most database load and replace the data access code of 60 services. The licence is expensive and the change would take two years.
As the senior technical leader, how do you evaluate the proposal and decide?Write-behind and write-around
Write-behind acknowledges writes in the cache and stores them in the database later, trading durability and freshness for low latency and fewer writes. Write-around sends writes only to the database and fills the cache on reads. Know where each fits, how write-behind queues must be bounded, coalesced and versioned, and which data must never take this path.
Besides cache-aside and write-through, two other write policies appear in designs: write-behind, where the cache accepts writes and stores them in the database later, and write-around, where writes skip the cache entirely.
Explain write-behind and write-around, what each one risks, and give a fitting use case for each.A service keeps user preferences in a write-behind map that a background writer saves to MySQL. During a 20-minute database outage the pending queue grew to 2 million entries and heap use hit 85 percent; after recovery, some users found older preferences overwriting newer ones.
Explain both problems and how to redesign the write-behind so it survives long outages and keeps the newest value.A video platform shows view counts and receives 50,000 view events per second at peak, across about 200,000 distinct videos per minute. Writing each view to PostgreSQL is not possible, and displayed counts may lag by a few seconds.
Design a write-behind counter with Redis and a database flusher: the data structures, how flushing works, and what happens when a flusher or a Redis node fails.Product teams want write latency under 10 ms in several domains, and an architect proposes making write-behind caching the default write path for new services, with the database updated asynchronously.
As the senior technical leader, how do you decide where write-behind may be used, and what conditions do you set?TTL and expiry design
A TTL bounds how long a cached value can be served and how long memory is held. Learn to choose TTLs from staleness tolerance and change rate, the difference between absolute and sliding expiry, why jitter matters, how per-entry expiry works in Caffeine and Redis, and why scheduled business changes should not depend on TTLs at all.
Every cached value needs a lifetime. A TTL that is too short wastes the cache, one that is too long serves stale data, and identical TTLs can make many entries expire at the same moment.
How do you choose a TTL for a cached value, and what are absolute expiry, sliding expiry, TTL jitter and a TTL used as a safety net?A service calls a partner API with OAuth access tokens whose lifetime varies from 5 to 60 minutes and is given in each token response. Tokens are cached per partner in Caffeine, and calls fail when a token expires mid-flight.
Implement per-entry expiry in Caffeine so each token is dropped 30 seconds before it really expires, and show the equivalent in Redis.A Redis cache that should hold about 2 million keys with one-hour TTLs keeps growing until eviction starts. INFO keyspace shows db0:keys=48000000,expires=1900000, although every cache write is supposed to set a TTL.
What does the INFO line tell you, which common code paths create keys without a TTL, and how do you clean up and prevent it?A retail site caches product prices for one hour in Redis and in each service's local cache. Marketing plans a sale in which 40,000 prices must change at exactly 00:00; last year customers saw old prices for up to an hour and some orders were placed at the wrong price.
How do you design expiry and switching so the new prices are visible everywhere at midnight, without a load spike on the database?Cache invalidation
Invalidation removes or replaces cached entries when the source changes, through direct deletes, events, change data capture or version bumps. Understand how to invalidate groups of keys cheaply, how dependency tracking works for composed pages, why change streams can lag behind bulk updates, and how replication lag across regions can undo an invalidation that arrived on time.
Sometimes one change affects many cached entries, for example a category rename that changes thousands of cached product pages. Deleting each key is slow, and listing them may not be possible.
How can you invalidate a large group of cache keys at once, and what are the trade-offs of version-based keys compared with tracking keys in a set?Cache invalidation runs on change data capture: a connector streams row changes from PostgreSQL into Kafka and an invalidator service deletes the matching Redis keys. A nightly batch updated 3 million rows, consumer lag reached 1.8 million messages, and for 25 minutes users saw stale data.
Why does a bulk update hurt this design so much, and what do you change in the invalidator and in how bulk changes are handled?A marketplace caches rendered category listing pages in Redis. Each page shows up to 50 products, a product can appear on hundreds of pages, and when a product's price or stock changes, every page that shows it should be refreshed within a few seconds.
Design the dependency tracking and invalidation for these pages, including the data structures and how they are kept bounded.A service runs in three regions, each with its own Redis cache. The database primary is in one region and replicates to read replicas in the others with 1 to 2 seconds of lag, while invalidation messages reach all regions within about 200 ms.
Why can remote regions end up caching stale values even though invalidations arrive quickly, and how would you design invalidation across regions?Your teams spend a growing share of time on cache invalidation bugs and infrastructure: change streams, invalidation services and versioned keys. An architect argues the organisation should design data to be immutable and content-addressed wherever possible, so it never needs invalidation.
As the senior technical leader, how far would you push immutability as a caching strategy, and how would you lead the change?Cache stampede and thundering herd
A stampede happens when many requests miss the same entry at once and all rebuild it, overloading the backend. Learn how request coalescing works inside one process and across many, how locks with leases and stale-while-revalidate keep a dead rebuilder from blocking everyone, and how known traffic events and synchronized clients turn into herds.
A Spring Boot service running 40 pods caches a costly report summary per customer in Caffeine. When an entry is missing, dozens of concurrent requests for the same customer arrive within milliseconds.
Show how Caffeine coalesces concurrent loads of one key inside a JVM, and explain what still happens across the 40 pods and how you would deal with it.To prevent stampedes, a service rebuilds a hot cache key under a Redis lock (SET lock:<key> <token> NX PX 30000) while other requests poll until the value appears. During a deploy the pod holding a lock was killed, and for 30 seconds p99 latency rose to 30 s and request threads ran out.
Explain why the protection turned into an outage, and redesign it so a dead lock holder costs little.A ticketing platform opens sales for a popular concert at 10:00, and about 2 million users are expected to load the event page in the first minute. Last time, an editor's change at 09:59 invalidated the event page cache and the origin collapsed.
How do you plan caching and load protection for this known event so the page stays up even if something changes at the last minute?Post-incident reviews keep finding the same pattern in different forms: caches expiring together, cron jobs scheduled at the top of the hour, retry storms after outages, and millions of mobile apps reconnecting at once after a push notification.
As the senior technical leader, how do you treat synchronized load as an organisation-wide problem rather than fixing each case?Cache penetration and avalanche
Penetration is load from keys that do not exist and can never be cached; an avalanche is a large part of the cache vanishing at once through synchronized expiry, an outage or a deploy that changes keys. Know the defences, from negative caching and Bloom filters to jitter, warm-up and admission control, and why a cache that carries load must be treated as critical.
Three failure patterns are often grouped together as cache problems: requests for keys that do not exist, a large part of the cache disappearing at once, and a single very hot key expiring under heavy load.
Explain cache penetration, cache avalanche and hot-key breakdown, and give the standard defences against each.A product API caches products by id in Redis with a 95 percent hit ratio. Overnight the hit ratio fell to 62 percent, database queries per second rose eight times, and logs show many GET /products/{id} requests for ids that return 404, coming from a few hundred IP addresses.
What is happening, and how do you protect the database now and for the long term?A release changed the cache key format of a product service from product:<id> to product:<id>:<locale> and switched to a new JSON serializer. All 30 pods were deployed within five minutes, the database CPU went to 100 percent, and the service was slow for 40 minutes.
Why did a code change act like a cache outage, and how do you roll out key or format changes safely in future?Your platform's databases are sized for the load left after caching, with typical hit ratios of 90 to 99 percent. A total cache loss, from an outage or a bad deploy, would send ten to fifty times the normal load to them.
As the senior technical leader, should databases be sized to survive a complete cache loss, and how do you decide and fund the answer?Multi-level and local caches
Local in-process caches such as Caffeine are the fastest layer but are duplicated in every instance and return shared object references. Understand how adding instances dilutes their hit ratio, how a two-level cache with a shared layer behind it should read, write and invalidate, and how to size each level against memory cost and warm-up time.
A pricing service caches List<PriceLine> per product in a local Caffeine cache. After a new discount feature shipped, some customers see discounted prices they are not eligible for, and the problem disappears after a restart.
PriceLine objects returned by the cache and then renders them. What is the bug, and how do you prevent this class of bug?A developer wants a two-level cache in Spring: Caffeine in each pod in front of Redis. They configure a CompositeCacheManager with a CaffeineCacheManager and a RedisCacheManager and expect level-one then level-two behaviour.
CompositeCacheManager actually do, and how would you implement a real two-level Spring cache?A recommendation service kept a 20,000-entry local Caffeine cache in each pod and reached a 92 percent local hit ratio with 6 pods. After autoscaling to 40 pods for a traffic increase, the local hit ratio fell to 61 percent and calls to the backing store rose sharply.
Why did adding pods make the cache worse, and what are your options to restore the hit ratio?A catalogue service runs 200 pods, each with a 2 GB local cache, which adds up to 400 GB of RAM holding mostly the same data. The cloud bill is under review, and the team also reports that pods take 4 minutes to warm up after deploys.
How do you decide what belongs in the local layer, what belongs in a shared layer, and how big each should be?CDN and edge caching
A CDN stores responses at edge locations and serves them without contacting the origin. Learn what forms the cache key, how freshness, revalidation, purges, surrogate keys and origin shields work, how personalised content can leak when caching rules are too broad, and how to keep an origin within capacity during traffic peaks while updates still appear quickly.
A content delivery network (CDN) caches responses at edge locations close to users, so most requests never reach the origin servers. Teams use it for static assets and increasingly for HTML and API responses.
What decides whether a CDN serves a request from its cache, how long it keeps an object, and how do you remove an object early?After a CDN configuration change meant to speed up the website, a few users report that the account page shows another person's name and order history. Origin responses for /account carry no Cache-Control header, and the new CDN rule caches all HTML for 60 seconds.
What went wrong, what do you do in the first hour, and how do you make sure personalised responses can never be cached at the edge again?A news site serves 200,000 page requests per second at peak during breaking news. Articles are updated every few minutes while a story develops, home pages contain a few personalised modules, and the origin can render about 3,000 pages per second.
Design the edge caching so the origin stays within its capacity while updates appear within about 30 seconds.Your CDN bill is now the third-largest infrastructure cost, much of your edge logic runs as vendor-specific edge functions, and a CDN vendor outage last year took the whole site down for 50 minutes.
As the senior technical leader, how do you set the strategy for edge delivery, weighing multi-CDN, cost and lock-in?HTTP caching headers
HTTP caching is driven by Cache-Control and validators such as ETag and Last-Modified, read by browsers, proxies, gateways and CDNs. Know exactly what no-store, no-cache, private, public, max-age and s-maxage mean, how Vary affects correctness and hit ratio, how content-hashed asset URLs make long caching safe, and when shared caches may store authenticated responses.
HTTP caching is controlled mainly by the Cache-Control response header. Browsers, proxies and CDNs read it to decide whether they may store a response, for how long, and when they must check with the server.
Explain no-store, no-cache, max-age=0, must-revalidate, private and public, and say which you would send for a login page, a versioned product image and a user's order list.A Spring Boot application serves its JavaScript and CSS bundles from src/main/resources/static. After each release some users see a broken page, because their browsers combine the new HTML with old cached scripts.
Configure Spring Boot so static assets get content-hashed URLs and long-lived caching while HTML is always revalidated, and explain why this fixes the problem.A public catalogue API returns JSON or XML by the Accept header and localised text by Accept-Language, with Cache-Control: public, max-age=300. Behind a new shared cache, some clients get XML when they asked for JSON, and French users sometimes see German text.
What is missing from the responses, how do you fix it, and what does the fix cost in cache efficiency?A platform team is enabling a shared response cache in the API gateway for 80 internal and partner APIs. Most requests carry an Authorization header with a bearer token, some responses differ per tenant, and teams have set Cache-Control inconsistently or not at all.
Which responses may the gateway store and serve to other callers, what rules do you give API teams, and how do you roll the cache out safely?Keeping cache and database consistent
Every cache is a copy that can disagree with its source. Understand the race that leaves stale values even with delete-on-write, how read replicas and version checks affect it, how to make cache writes reject older data, and how to move between cache systems without serving stale data or overloading the database during the switch.
Cache-aside with delete-on-write is the most common way to keep a cache and a database in step, and it is often described as safe. It still has a race that can leave a stale value in the cache.
Walk through the interleaving of one reader and one writer that leaves a stale value in the cache, and explain why it is rare, what bounds it, and how it can be reduced.A service caches account settings in Redis, and the database keeps a version column that increases on every update. Concurrent loaders and writers sometimes overwrite a newer cached value with an older one.
Write a Redis Lua script that stores a value only if its version is newer than the cached one, and show how the Java side calls it.A profile service updates PostgreSQL on the primary, deletes the Redis key after commit, and loads from a read replica on a cache miss. Replica lag is usually 50 ms but reaches 800 ms at peak, and users report that an edited display name reverts for an hour, only at peak times.
Explain the sequence that causes this, and give the fixes in order of preference.A company is moving 30 services from a self-managed cache cluster to a managed Redis-compatible service in another network. The old cluster holds 600 GB of cached data, about 15 writer services send invalidations, and the move must happen without downtime or a database overload.
How do you plan the move so neither stale data nor a cold-cache overload happens during and after the switch?