Sub topic 2
The layers where caching happens
A request for data often passes through several caches before it reaches the original source. This chapter maps those layers, explains what each one is good at, and describes the errors that appear when layers interact. It assumes you know basic Python, how client-server requests and databases work, and the difference between latency and throughput. It builds on the previous chapter's terms: hit, miss, and hit ratio.
The path of a request
A cache sits between a consumer and a slower source of truth. In a real system, there is more than one such gap. A page view might travel from the browser to a content delivery network (CDN), then to a load balancer, an application server, and a database. Each hop can hold a copy of the data, and each copy answers some requests so the next hop never sees them.
The layers closer to the user are faster to reach and cover more traffic. They are also harder to control. You can clear your application cache with one command, but you cannot reach into every user's browser.
Browser cache
The browser cache stores responses on the user's own device. A hit costs no network round trip, so it is the fastest layer possible.
- What it holds: static files such as scripts, stylesheets, fonts, and images. It can also hold API responses if the server allows it.
- Who controls it: the server, indirectly. The server sends HTTP headers such as
Cache-Control, and the browser decides what to keep. A later chapter covers these headers in detail. - Scope: one cache per user and per browser profile. It is a private cache, so it must never hold data that belongs to a different user.
- Weakness: you cannot purge it. Once a browser stores a file for a year, you can only change the URL to make it fetch a new one.
That last weakness shapes how teams ship static files. A common practice is to put a content hash in the file name, such as app.3f9a1c.js. The file can then be cached for a very long time, because a new version gets a new name.
CDN cache
A content delivery network is a group of servers spread across many regions. Each server, called an edge, keeps copies of responses and serves users who are geographically close. The CDN is a shared cache: one stored copy can serve thousands of users.
- What it holds: static assets, public pages, and sometimes API responses that are identical for all users.
- Benefit: it cuts latency, because the response travels a shorter distance. It also shields your origin server from traffic spikes.
- Control: you can usually purge a URL or a group of URLs through the CDN's API, though propagation to all edges is not instant.
- Risk: a shared cache can leak private data. If a CDN caches a response that contains one user's account details and then serves it to another user, you have a data exposure incident. This usually happens when a response that depends on a cookie or an authorization header is cached by URL alone.
Application cache
The application cache lives inside or next to your backend code. It stores the results of expensive work: database queries, calls to other services, rendered fragments, or computed values. This is the layer you control most directly, and it is where the patterns in later chapters (cache-aside, write-through, and the rest) apply.
There are two common forms.
- In-process cache. A dictionary or similar structure in the memory of the application process. Reads take nanoseconds to microseconds, and there is no network hop. Each process has its own copy, so five servers hold five separate caches that can disagree.
- External cache. A separate service such as Redis or Memcached that all application servers share. Reads cost a network round trip, usually well under a millisecond inside one data center, but every server sees the same data.
The in-process form is fast but fragmented. The external form is consistent across servers but adds a dependency and a network call. Many systems use both: a small in-process cache in front of a shared external one.
import time
local = {} # key -> (value, expires_at); small, per-process, short TTL
LOCAL_TTL = 5
def get_product(product_id, shared_cache, db):
key = f"product:{product_id}"
entry = local.get(key)
if entry is not None and entry[1] > time.monotonic():
return entry[0] # layer 1: in-process hit
value = shared_cache.get(key) # layer 2: shared cache
if value is None:
value = db.fetch_product(product_id) # layer 3: source of truth
shared_cache.set(key, value, ttl=300)
local[key] = (value, time.monotonic() + LOCAL_TTL)
return valueThe local TTL is short on purpose. If another server updates the product and removes it from the shared cache, this server still serves its stale local copy for up to five seconds. A short TTL caps how long that can last.
Database caches
Databases cache internally, and you get this layer without writing any code.
- Buffer pool or page cache. The database keeps recently used disk pages in memory. A query that touches hot pages avoids disk reads. PostgreSQL relies on shared buffers and the operating system's page cache. MySQL's InnoDB uses its buffer pool.
- Query plan cache. Some databases reuse the parsed and planned form of a statement, which is why prepared statements can be faster for repeated queries.
- Query result cache. A few databases cache full results. MySQL removed its query cache in version 8.0 because invalidating it on every table write caused contention. Do not assume your database offers this.
The database layer helps with read speed, but it does not reduce the number of connections or requests that reach the database. That is why an application cache in front of it often matters more under heavy load.
Comparing the layers
| Layer | Typical hit latency | Shared across users | Can you purge it | Best for |
|---|---|---|---|---|
| Browser | None (no network) | No | No | Versioned static files |
| CDN | Tens of milliseconds | Yes | Yes, with delay | Public content, global traffic |
| In-process | Microseconds | Per process | Yes, per process | Hot values, tiny lookups |
| External (Redis) | About 1 ms or less | Yes | Yes, immediately | Query results, sessions, shared state |
| Database buffer | Sub-millisecond to milliseconds | Yes | Not directly | Automatic speedup of hot data |
Common errors across layers
Stacked staleness. Each layer adds its own time to live (TTL). If a CDN holds a response for 60 seconds and fetches it from an application cache that holds it for 300 seconds, a client can see data that is nearly six minutes old. In the worst case, the staleness of the layers adds up. Choose TTLs with the whole chain in mind.
Fixing the wrong layer. After you update a record, you purge the application cache and still see old data. The browser or the CDN is still holding a copy. When a change does not appear, check each layer in order, starting from the client.
Caching by the wrong key. A shared layer that ignores a request attribute, such as language, user, or device type, serves one variant to everyone. The next chapter covers key design.
Duplicate caching with no benefit. Caching the same data in many layers costs memory and adds failure modes. Add a layer because it removes load or latency that the layers in front of it cannot.
Treating a cache as a store. Any layer can be emptied by a restart, an eviction, or a purge. Your system must work, only more slowly, when a layer is empty.
Choosing where to cache
A useful rule is to cache as close to the user as the data's freshness and privacy allow.
- If the data is identical for everyone and changes rarely, push it to the browser and CDN.
- If it is expensive to compute and shared across requests, use the application layer.
- If it is personal, keep it private to the user: use
privateheaders, or the application cache with the user in the key. - Leave the database layer to the database, and tune it only after measuring.
Exercise
A product page is cached in the CDN for 120 seconds. The CDN fetches it from an application that caches the rendered HTML in Redis for 300 seconds. A price changes and you delete the Redis entry. What is the longest a user could still see the old price, and what would you do to shorten it?
Show answer
Up to 120 seconds, because the CDN may have fetched the page just before the price changed and will keep serving it until its own TTL ends. After the Redis entry is deleted, the next CDN refresh gets the new price. To shorten this, purge the page URL on the CDN when the price changes, or lower the CDN TTL.
Exercise
Why should an in-process cache usually have a shorter TTL than a shared external cache that sits behind it?
Show answer
Each process has its own copy, and an invalidation in the shared cache does not reach the other processes' local copies. A short local TTL limits how long those copies can stay stale after the shared entry changes.