We are designing a cache hierarchy with four layers: CDN, edge, service, and DB.
Each layer has its own characteristics and we need to define keys, TTLs, and stampede defense for each.
Assumptions:
CDN: Caches static assets (like images, JS, CSS) and possibly some dynamic content that can be cached at the edge of the internet. TTLs can be longer because static assets don't change often.
Edge: This could be a reverse proxy or a set of servers closer to the user than the service layer. It might cache dynamic responses for a short time to reduce load on the service.
Service: The application servers that generate dynamic content. They might have an in-memory cache (like Guava, Caffeine) for frequently accessed data.
DB: The database, which might have its own query cache (but note that many modern DBs don't have a query cache or it's deprecated). Alternatively, we can think of the DB as the ultimate source and we want to avoid hitting it as much as possible.
We'll define for each layer:
What to cache (keys)
TTL (time to live)
Stampede defense (how to prevent multiple processes/requests from trying to regenerate the same cache key at the same time when it expires)
Let's break it down:
CDN:
Keys: Typically, the URL (including query string if it's part of the cache key) for static assets. For dynamic content, we might use a combination of URL and headers (like Accept-Language) but let's assume we are cache static assets by URL.
TTL: Long, e.g., 1 day to 1 year. We can use versioning in the URL for static assets to allow for long TTLs.
Stampede defense: CDNs typically handle this by serving stale content while revalidating in the background. Also, they might have a mechanism to avoid thundering herd by having a single request go to the origin and others wait or serve stale.
Edge (e.g., Varnish, Nginx, or a dedicated edge cache service):
Keys: For dynamic content, we might use the URL plus some request headers (like Authorization, Cookie) if they affect the response. But we want to cache as much as possible, so we might normalize the request (strip cookies if not needed).
TTL: Short, e.g., 1 second to 5 minutes. This is for dynamic content that changes frequently.
Stampede defense: Use a lock mechanism (like a mutex) so that only one request goes to the backend to regenerate the cache, and others wait for the result or serve stale.
Service (in-memory cache, e.g., Caffeine):
Keys: Could be a combination of method name and parameters for a service method call, or a database query key (like "user:123" for user with id 123).
TTL: Medium, e.g., 1 minute to 1 hour, depending on the data volatility.
Stampede defense: Use a similar lock mechanism, or use a cache that supports automatic refresh (like Caffeine's refreshAfterWrite) which allows one thread to recompute while others get the old value.
DB:
We don't typically cache in the DB itself (at least not in the way we are describing) but we might have a query cache. However, modern DBs often disable query cache because of performance issues. Alternatively, we can think of the DB as the source and we want to avoid hitting it. So we'll skip DB cache and focus on the layers above.
Alternatively, we can consider the DB's own buffer pool (which caches data pages) but that's not application-level caching.
However, note: the problem says "cache hierarchy" and includes DB. So maybe we are thinking of the DB as the last resort and we want to cache at each layer to avoid going to the DB.
Let's adjust:
We have four layers, and the DB is the source. So we want to cache at the service, edge, and CDN.
But note: the DB might have its own caching (like buffer pool) but that's not under our control in the same way.
We'll define for each layer:
CDN: For static assets, keyed by URL. TTL: long (1 year). Stampede: CDN's own mechanism (like revalidation with If-Modified-Since).
Edge: For dynamic pages, keyed by a cache key that is derived from the request (URL, headers, etc.). TTL: short (1-5 minutes). Stampede: use a lock (or semaphore) per cache key so that only one request goes to the service to regenerate.
Service: For data that is expensive to compute or fetch from DB, keyed by a business logic key (e.g., "user_profile:123"). TTL: medium (5-15 minutes). Stampede: use a cache that supports refresh (like Caffeine's refreshAfterWrite) or a lock.
DB: We don't cache at the DB layer in the same way, but we can consider the DB's buffer pool as a cache. We don't control TTL for that. So we might skip defining for DB.
Alternatively, we can think of the DB as having a query cache (if enabled) but that's not recommended in many cases.
Since the problem says "cache hierarchy: CDN→edge→service→DB", it might be implying that we go from CDN (closest to user) to DB (farthest). So we want to define for each.
But note: the DB is the source, so we don't cache at the DB. We cache above.
However, the problem might be expecting a cache at the DB layer? Let me clarify: in some architectures, there is a cache between the service and the DB (like Redis) but that's not listed. The hierarchy is CDN -> edge -> service -> DB.
So the service layer is the one that talks to the DB. The service layer might have an in-memory cache to avoid going to the DB.
Let's define:
Layer 1: CDN (for static assets)
Layer 2: Edge (for dynamic content that can be cached at the edge, but note: edge might be the same as CDN for some providers? But let's assume edge is closer to the origin than CDN)
Layer 3: Service (in-memory cache)
Layer 4: DB
But wait, the service layer is the application. It might have an in-memory cache and then it goes to the DB.
So we have:
CDN: caches static assets (images, css, js) by URL. TTL: long (1 year). Stampede: CDN handles by revalidating with origin.
Edge: caches dynamic responses (like HTML pages) by a key that includes the URL and relevant headers. TTL: short (1-5 minutes). Stampede: use a lock (or a "single flight" pattern) so that only one request goes to the service for a given key when it's about to expire.
Service: caches data objects (like user profiles, product details) in memory. TTL: medium (5-15 minutes). Stampede: use a cache that supports refresh (so that when an entry expires, the next request triggers a refresh in the background and the old value is served until refresh is done) or use a lock.
DB: no application-level cache, but we assume the DB has its own buffer pool. We don't control TTL for that.
However, the problem asks for keys, TTLs, and stampede defense for each. So we must define for DB? Maybe we can say:
DB:
- Keys: not applicable (or primary keys for rows, but we don't control the DB's buffer pool)
- TTL: not controlled by us (DB's buffer pool replacement policy is LRU or similar)
- Stampede: DB's own connection pooling and query optimization.
But that might not be what the problem expects.
Alternatively, we might have a cache between the service and the DB? But the hierarchy is CDN->edge->service->DB, so the service talks to DB.
Let's think of the service as having two caches: one in-memory and one that is shared (like Redis) but that's not in the hierarchy.
Given the hierarchy, I think we are to define for each layer as if they are separate caches.
So:
CDN:
Keys: URL (with versioning for static assets)
TTL: 1 year (for static) or as set by Cache-Control headers.
Stampede: CDN's own mechanism (like revalidation with If-Modified-Since, or serving stale while revalidating).
Edge:
Keys: A cache key built from the request (URL, headers, etc.) but normalized (e.g., ignore cookies if not needed). We can use a hash of the normalized request.
TTL: 1-5 minutes (configurable per endpoint)
Stampede: Use a lock (mutex) per cache key. When a request comes for an expired key, it acquires the lock, checks again if the cache is still expired (double-checked locking), and if so, goes to the service to regenerate. Other requests for the same key wait for the lock and then serve the new value or the old one if the lock holder has already updated.
Service:
Keys: Business logic key, e.g., "UserProfile:{userId}" or "Product:{productId}:{locale}". We can also use method signatures and arguments.
TTL: 5-15 minutes (configurable per data type)
Stampede: Use a cache that supports refresh (like Caffeine's refreshAfterWrite) which automatically refreshes entries in the background when they are accessed after the refresh time. Alternatively, use a lock similar to edge but in-memory.
DB:
We don't have an application-level cache at the DB, but we can consider the DB's query cache if enabled. However, many DBs (like PostgreSQL) have deprecated the query cache because it's often a performance bottleneck. So we might say:
Keys: The SQL query string (and parameters) if query cache is enabled.
TTL: Not controlled by us (DB's query cache TTL is set at the DB level, and often it's not used).
Stampede: DB's own mechanism (like row-level locks, but that's not for cache).
But wait, the problem says "cache hierarchy" and includes DB. Maybe they mean that we have a cache at the DB level? Or maybe they mean that we are caching the DB results at the service layer and the DB is the last layer.
Alternatively, we might have a distributed cache (like Redis) between the service and the DB? But that's not in the given hierarchy.
Given the hierarchy: CDN->edge->service->DB, it seems the service layer is the one that talks to the DB and might cache the results.
So I think we are to define for the service layer as the one that caches DB results.
Let's redefine the service layer as the one that caches the results of DB queries or expensive computations.
Then:
CDN: static assets
Edge: dynamic HTTP responses (like HTML) that can be cached at the edge
Service: data that is used by the application (from DB or computed) that can be cached in memory
DB: the source of truth, no cache (or we don't control)
But the problem asks for keys, TTLs, and stampede defense for each. So for DB, we might say:
DB:
- We don't cache at the DB layer in our application, so no keys, TTL, or stampede defense defined by us.
However, that might not be acceptable.
Alternatively, we can think of the DB as having a cache (like the buffer pool) and we can try to optimize by using indexes and such, but that's not the same.
Given the ambiguity, I will define for the first three layers and then for the DB, I will say that we don't have an application-level cache, but we rely on the DB's own caching (buffer pool) and we design our queries to be efficient.
But let's see the problem: "Create a cache hierarchy: CDN→edge→service→DB, keys, TTLs, and stampede defense."
It might be that they want a cache at each layer, including the DB? But the DB is the data store.
Another interpretation: the DB might have a cache (like Redis) in front of it? But then the hierarchy would be CDN->edge->service->cache->DB. But the problem says service->DB.
So I think we are to design the caches at CDN, edge, and service, and then the DB is the last layer without cache.
However, to be thorough, I'll define for the DB as:
DB:
- We don't have an application-level cache at the DB, but the DB itself may have a buffer pool. We don't control the keys or TTL. Stampede defense: the DB's own locking and transaction mechanisms.
But that seems weak.
Alternatively, we might have a cache at the service layer that caches DB results, and then the service layer is the one that talks to the DB. So the DB is the source.
Given the above, I'll write:
CDN:
Keys: URL (with versioning for static assets)
TTL: Long (1 year for static assets, set via Cache-Control)
Stampede defense: CDN's revalidation mechanism (If-Modified-Since) and serving stale while revalidating.
Edge:
Keys: Normalized request (URL + selected headers, e.g., Accept-Language, but without cookies if not needed). We generate a cache key by hashing the normalized request.
TTL: Short (1-5 minutes, set per endpoint based on data volatility)
Stampede defense: Use a lock (mutex) per cache key. When a request finds an expired entry, it tries to acquire the lock. The one that gets the lock regenerates the cache. Others wait and then serve the new cache or the old one if the lock holder has already updated.
Service:
Keys: Business logic keys, e.g., "user:{id}:profile", "product:{id}:details". We can also use method signatures and arguments for service methods.
TTL: Medium (5-15 minutes, configurable per data type)
Stampede defense: Use a cache with refresh capability (like Caffeine's refreshAfterWrite) or a lock (similar to edge) but in-memory.
DB:
We do not implement an application-level cache at the DB. The DB's own buffer pool caches data pages. We don't control the keys or TTL. Stampede defense is handled by the DB's transaction isolation and locking.
However, if the problem expects a cache at the DB layer (like a query cache), we can say:
DB (query cache, if enabled):
Keys: The SQL query string with parameters normalized (e.g., using prepared statement placeholders).
TTL: Set by the DB configuration (e.g., in MySQL, query_cache_size and query_cache_limit, but note that query cache is deprecated in MySQL 8.0).
Stampede: The DB's query cache invalidates on table changes, so it's automatically invalidated. But stampede might not be a problem because the query cache is shared and the DB handles it.
But given that query cache is often disabled in modern systems, I think the first interpretation is better.
Let me adjust: the hierarchy is from CDN (closest to user) to DB (farthest). So we want to cache as much as possible at the upper layers.
Edge: caches dynamic responses by a normalized request key. TTL short. Stampede: lock per key.
Service: caches data by business key. TTL medium. Stampede: refresh or lock.
DB: no application cache.
But the problem says "cache hierarchy" and lists DB as the last. Maybe they want to say that we should cache at the DB too? Or maybe they mean that we have a cache between the service and the DB? But then it would be CDN->edge->service->cache->DB.
Since the problem says "CDN→edge→service→DB", I think we are to design for these four layers, and the DB is the last layer without cache.
However, to be safe, I'll include a note that the DB does not have an application-level cache, but we rely on the DB's buffer pool.
Alternatively, we can think of the service layer as having a cache that stores the results of DB queries, and then the service layer is the one that goes to the DB. So the DB is the source and we cache at the service.
So, final answer:
Layer 1: CDN
- Keys: URL (with versioning for static assets)
- TTL: Long (e.g., 1 year for static assets, set via Cache-Control headers)
- Stampede defense: CDN's revalidation (If-Modified-Since) and serving stale while revalidating.
Layer 2: Edge (e.g., reverse proxy cache)
- Keys: Normalized request (URL + headers that affect the response, e.g., Accept-Language, User-Agent if needed). We generate a hash of the normalized request.
- TTL: Short (1-5 minutes, set per endpoint)
- Stampede defense: Use a lock (mutex) per cache key. When an entry expires, the first request that notices acquires the lock and regenerates the cache. Subsequent requests for the same key wait for the lock and then serve the updated cache (or the old cache if the lock holder has already updated).
Layer 3: Service (in-memory cache, e.g., Caffeine)
- Keys: Business logic keys, e.g., "user:{id}:profile", "product:{id}:details". Also, for service methods, we can use the method signature and arguments.
- TTL: Medium (5-15 minutes, configurable per data type)
- Stampede defense: Use a cache that supports automatic refresh (like Caffeine's refreshAfterWrite) so that when an entry expires, the next access triggers a background refresh and the old value is served until the refresh is complete. Alternatively, use a lock similar to the edge layer.
Layer 4: DB
- We do not have an application-level cache at the DB. The DB's own buffer pool caches data pages. We don't control the keys or TTL. Stampede defense is handled by the DB's transaction isolation and row-level locking.
However, if we are allowed to have a cache between service and DB, then we would have:
Layer 3: Service (in-memory cache) -> Layer 4: Distributed cache (like Redis) -> DB
But the problem says service->DB, so I think we are to stop at the service layer.
Given the above, I'll write the answer accordingly.
Here's a comprehensive cache hierarchy with defense mechanisms:
Cache Hierarchy: CDN → Edge → Service → DB
1. CDN Layer
Keys: Full URL paths (e.g., /static/app.min.js, /images/logo.png) Static assets with version hashes in filenames for busting
TTL:
Static assets: 1 year (immutable via versioning)
API responses: 0 seconds (bypass for dynamic content)
TTL Hierarchy Rule: CDN_TTL ≥ Edge_TTL ≥ Service_TTL Higher layers provide "safety net" for lower-layer failures
Stampede Defense Cascade:
CDN → coalesces 1000s of requests to 1
Edge → merges 100s of requests to 1
Service → prevents 10s of concurrent recomputes
Example Flow: Product Page Request
code
1. CDN: Check `/products/123.html` (TTL:1y) → MISS (dynamic)
2. Edge: Check `GET:/api/product/123` (TTL:10s) → HIT (stale)
- Schedule async revalidation in background
3. Service: Check `product:123:details` (TTL:30s) → HIT
4. DB: Never hit for this request
Monitoring & Fallbacks
Metrics per layer: hit/miss ratios, latency p99, stampede events
❌ Cache penetration (no null caching for DB misses)
❌ Stampede on startup (no cold-start warming)
❌ Key explosion (over-fragmenting cache keys)
This hierarchy provides progressive defense against thundering herds while maintaining freshness where needed. The most aggressive defenses (single-flight) are placed at the edge where request volume is highest, while service layer uses lighter-weight refresh mechanisms since process-level locking is cheaper.