In the previous lesson we made each request cost less. In this one we will go a step further: making most of the work never happen at all. A category's listing is identical for every customer and changes a few times a day, and the photo of an olive tree never changes. Computing and sending them again on every visit is a waste. You will learn what a cache is, at which levels it can sit, which strategies exist for reading and writing it, and what its real difficulty is: knowing when what is stored has stopped being true. You will also learn about content delivery networks, which bring files closer to the customer. Verdalia will apply both techniques to its catalog and its images.
What a Cache Is and Why It Works
A cache is a copy of a piece of data, kept in a place from which it can be obtained faster than from its origin. The origin may be a database, an expensive calculation, or a distant server. When the data is in the cache there is a hit, and when it is not, a miss, which forces a trip to the origin. The hit rate is the proportion of reads resolved by the cache, and it is the measure of its usefulness.
A cache works because data usage is not uniform. Three conditions hold:
| Condition | Meaning | At Verdalia |
|---|---|---|
| Locality | A few pieces of data concentrate most of the queries | 300 of the 15,000 products receive 70% of the visits |
| More reads than writes | The data is read many times between one change and the next | A product page is read thousands of times a day and modified once a month |
| Tolerance for staleness | Seeing slightly outdated data for a while is not serious | A description change may take 5 minutes to show |
If any of them fails, the cache stops paying off. Data that changes as often as it is read, or that must be exact at all times, is not a good candidate.
It is worth remembering the warning from Module 3: a cache is a copy, never the primary store. It must be possible to wipe it entirely without losing information.
Cache Levels
Between the customer and the database there are several places to keep copies. The closer to the customer, the more work is saved.
flowchart LR
browser["Browser cache"] --> cdn["CDN"]
cdn --> proxy["Reverse proxy"]
proxy --> app["Application cache"]
app --> db["Database cache"]
| Level | Where it is | What it stores | Who shares it |
|---|---|---|---|
| Browser | On the customer's device | Images, style sheets, JavaScript | Only that customer |
| CDN | On servers spread around the world | Static files and, sometimes, pages | All customers |
| Reverse proxy | In front of the application, for example in Nginx | Complete responses | All customers |
| Application | In the process's memory or in a store such as Redis | Data and calculation results | Depends on the variant |
| Database | Inside the engine | Disk pages and query plans | All queries |
The database cache works on its own and hardly needs attention. The application cache has two variants, which are worth distinguishing:
| Aspect | In the process's memory | Distributed, in Redis |
|---|---|---|
| Speed | Maximum: no network | Very high: one trip over the local network |
| Shared between servers | No: each process has its own copy | Yes |
| After an application restart | Lost | Kept |
| Invalidation | Hard: every process has to be notified | Deleted once |
| Fits | Nearly fixed data, such as a table of provinces | Everything else, when there are several servers |
The global variable with the list of categories, which we found in Verdalia's state inventory, was a cache in the process's memory, with no expiration and no invalidation.
The Browser Cache: Cache-Control and ETag
The server tells the browser, and the intermediate caches, what they may store and for how long. It does so with HTTP headers in the response. The main one is Cache-Control:
| Value | Meaning |
|---|---|
max-age=3600 |
The copy is valid for 3,600 seconds |
public |
Any cache may store it, including shared ones |
private |
Only the customer's browser may store it |
no-cache |
It may be stored, but the server must be asked before using it |
no-store |
It may not be stored anywhere |
immutable |
The content will never change: no need to ask |
When the copy expires, the browser does not necessarily have to download it again. It can ask whether it has changed. That is what the ETag header is for, an identifier of the content's version:
sequenceDiagram
participant N as Browser
participant S as Server
N->>S: GET /product/2087
S-->>N: 200 OK, with ETag a41f and the content
Note over N: The copy expires
N->>S: GET /product/2087, with If-None-Match a41f
S-->>N: 304 Not Modified, without content
The 304 response carries no content: it takes up a few bytes and saves the download.
Files With the Version in the Name
For static files a simple technique is used: including a fingerprint of the content in the name, as in styles.3f9a1c.css. If the file changes, its name changes, and the pages point to the new one. The file can then be stored for a whole year, because that URL will never have any other content.
| Verdalia resource | Header |
|---|---|
| Style sheets and JavaScript, with a fingerprint in the name | Cache-Control: public, max-age=31536000, immutable |
| Product images | Cache-Control: public, max-age=604800 |
| Catalog pages | Cache-Control: private, no-cache, with ETag |
| Cart, checkout, and customer account | Cache-Control: no-store |
Read and Write Strategies
The strategies describe who checks the cache, who fills it, and what happens on a write.
| Strategy | Read | Write | Advantage | Drawback |
|---|---|---|---|---|
| Cache-aside | The application looks in the cache; on a miss, it reads from the origin and stores the copy | The application writes to the origin and deletes the copy | Simple; if the cache goes down, the application keeps working | The logic lives in the application; the first read is slow |
| Read-through | The application only asks the cache, which reads from the origin on a miss | As above | The application gets simpler | The cache must know how to read from the origin |
| Write-through | Either of the above | The write goes to the cache, which writes to the origin before responding | The cache is always up to date | Every write is slower |
| Write-behind | Either of the above | The write goes to the cache, which writes to the origin later | Very fast writes | If the cache goes down before writing, the data is lost |
Cache-aside is the most widespread and the one Verdalia will use. Write-behind is the riskiest: it only fits data whose loss is tolerable, such as a visit counter.
Expiration, Invalidation, and What Must Not Be Cached
An outdated cache shows false data. There are three ways to keep it up to date:
| Mechanism | What it consists of | Advantage | Drawback |
|---|---|---|---|
| Expiration | Each entry has a time to live, or TTL, and is discarded when it is up | Requires no additional code | The data may be stale for all that time |
| Explicit invalidation | When the data is modified, its copy is deleted | The change is visible immediately | It has to be remembered at every point where the data is modified |
| Versioned keys | The data's version is part of the key | Nothing has to be deleted | Old versions take up memory until they expire |
The usual approach combines the first two: invalidation so that changes show up soon, and expiration as a safety net, in case some invalidation is forgotten.
When choosing the TTL, the question is the same one we asked about messages in Module 3: how much staleness is acceptable for this data. The answer belongs to the business, and it is different for each piece of data.
What Must Not Be Cached
- Data on which a decision with consequences depends. Stock may be displayed a few seconds late, but at the moment of confirming the order it is checked against the database. The same applies to prices when charging and to balances.
- Personal data, in shared caches. If a CDN or a proxy stores Ana's “My account” page, the next visitor may receive it. It is not a theoretical risk: it is a data leak, with legal consequences. Every personalized response must carry
privateorno-store. - Error responses. A passing failure cached for an hour becomes a one-hour failure.
A warning: the processing of personal data is subject to data protection regulations. In a real system, the caching policy for pages with customer data must be reviewed by a compliance professional.
Classic Problems
| Problem | What happens | Solutions |
|---|---|---|
| Cache stampede | A heavily requested entry expires, and hundreds of simultaneous requests miss and all go to the origin to compute the same thing | Let only one request recompute while the others wait or receive the old data; refresh before it expires |
| Mass expiration | Many entries were stored at the same time and expire at the same time | Add a random variation to the TTL |
| Hot keys | A single key receives a huge share of the traffic, such as the home page product | An additional copy in the process's memory, with a TTL of a few seconds |
| Cold start | After a restart, the cache is empty and the origin receives the whole load | Warm up: fill the cache with the most requested data before opening the traffic |
The cold start matters at Verdalia for a concrete reason: if Redis restarted in the middle of the campaign, the database would suddenly receive a load five times higher than usual.
Content Delivery Networks
What It Is and How It Works
A content delivery network, or CDN, is a network of geographically distributed servers that keep copies of the content and serve it from the point closest to each customer.
| Concept | What it is |
|---|---|
| Origin | The server where the original content lives. At Verdalia, the object storage |
| Point of presence | Each CDN site that keeps copies and serves nearby customers |
| Purge | The order to delete a copy from every point of presence |
sequenceDiagram
participant C as Customer in Seville
participant P as Madrid point of presence
participant O as Origin
C->>P: GET /products/2087/main.webp
Note over P: Miss: it has no copy
P->>O: GET /products/2087/main.webp
O-->>P: Image, with Cache-Control
P-->>C: Image
Note over P: Stores the copy
C->>P: The same request, from another customer
P-->>C: Image, without going to the origin
The CDN obeys the same Cache-Control headers as the browser. It brings three things: less latency, because the content travels less; less load on the origin, because most requests never reach it; and capacity to absorb spikes, because its network is sized for traffic far greater than a store's.
What It Can Serve
| Content | Through the CDN? | Remarks |
|---|---|---|
| Images, style sheets, JavaScript, fonts | Yes, always | They are the same for everyone and change little |
| Public pages identical for everyone | Possible | Requires that the page contain nothing personal |
| Personalized pages and operations | No | They must reach the application |
Cache-Aside in Python
In-Memory Implementation
import random
import time
class TTLCache:
"""In-memory cache with expiration and hit and miss counters."""
def __init__(self):
self._data = {}
self.hits = 0
self.misses = 0
def get(self, key):
value, expires_at = self._data.get(key, (None, 0))
if time.monotonic() >= expires_at:
self._data.pop(key, None)
self.misses += 1
return None
self.hits += 1
return value
def set(self, key, value, seconds):
self._data[key] = (value, time.monotonic() + seconds)
def delete(self, key):
self._data.pop(key, None)
def hit_rate(self):
return self.hits / (self.hits + self.misses)
class ProductRepository:
"""Simulates the database: each query takes 2 milliseconds."""
def __init__(self):
self._prices = {n: 10.0 for n in range(1, 501)}
self._prices[2087] = 33.00
def find(self, product_id):
time.sleep(0.002)
return {"id": product_id, "price": self._prices[product_id]}
def change_price(self, product_id, price):
self._prices[product_id] = price
class Catalog:
PRODUCT_TTL_SECONDS = 300
def __init__(self, repository, cache):
self._repository = repository
self._cache = cache
def product(self, product_id):
key = f"product:{product_id}"
product = self._cache.get(key)
if product is None: # miss: go to the origin
product = self._repository.find(product_id)
self._cache.set(key, product, self.PRODUCT_TTL_SECONDS)
return product
def change_price(self, product_id, price, invalidate=True):
self._repository.change_price(product_id, price) # 1. write to the origin
if invalidate:
self._cache.delete(f"product:{product_id}") # 2. delete the copy
# 1. Visits are not evenly spread: 50 products receive 80%
random.seed(3)
popular = list(range(1, 51))
rest = list(range(51, 501))
visits = [random.choice(popular if random.random() < 0.8 else rest) for _ in range(2000)]
repository = ProductRepository()
start = time.perf_counter()
for product_id in visits:
repository.find(product_id)
print(f"Without cache: {(time.perf_counter() - start) * 1000:.0f} ms")
cache = TTLCache()
catalog = Catalog(repository, cache)
start = time.perf_counter()
for product_id in visits:
catalog.product(product_id)
print(f"With cache: {(time.perf_counter() - start) * 1000:.0f} ms, "
f"{cache.hits} hits, {cache.misses} misses, "
f"{cache.hit_rate():.0%} hit rate")
# 2. Price change, without invalidating and with invalidation
print("Initial price: ", catalog.product(2087)["price"])
catalog.change_price(2087, 29.90, invalidate=False)
print("Without invalidation:", catalog.product(2087)["price"])
catalog.change_price(2087, 29.90)
print("With invalidation: ", catalog.product(2087)["price"])Output. The times vary from one computer to another:
Without cache: 4166 ms With cache: 647 ms, 1691 hits, 309 misses, 85% hit rate Initial price: 33.0 Without invalidation: 33.0 With invalidation: 29.9
Explanation:
TTLCacheresembles the store from the first lesson of the module, with two additions: the counters and thedeletemethod. A cache that is not measured cannot be known to be useful.Catalog.productis the complete cache-aside pattern, in five lines: look in the cache and, on a miss, read from the origin and store the copy.change_pricewrites to the origin first and deletes the copy afterwards. It deletes it instead of updating it: the next read will fill it with the data from the origin, which is the only one that rules. Theinvalidateparameter exists only for the demonstration.- The simulated visits concentrate 80% on 50 products out of 500. That is the locality we were talking about.
Interpretation:
- The cache divides the time by 6, with an 85% hit rate. The 309 misses are the first visits to each product.
- Without invalidation, the old price keeps showing, and it would for up to 5 minutes. One customer would see €33.00 on the product page and a different amount in the cart.
- The hit rate depends on the traffic, not only on the code. With visits spread evenly across the 15,000 products it would be much lower.
The Equivalent With Redis
import json
import redis
store = redis.Redis(host="verdalia-aux-01", port=6379, decode_responses=True)
class Catalog:
PRODUCT_TTL_SECONDS = 300
def __init__(self, repository, store):
self._repository = repository
self._store = store
def product(self, product_id):
key = f"product:{product_id}"
try:
text = self._store.get(key)
except redis.RedisError:
text = None # slower without the cache, but it carries on
if text is not None:
return json.loads(text)
product = self._repository.find(product_id)
self.store_copy(key, product)
return product
def store_copy(self, key, product):
try:
self._store.setex(key, self.PRODUCT_TTL_SECONDS, json.dumps(product))
except redis.RedisError:
passThe structure is the same. Two things change: the data travels as JSON text, and every access to Redis is protected with try. That is the advantage of cache-aside: if the cache does not respond, the product is read from the database. The store runs slower, but it works. Redis counts hits and misses on its own, which are queried with the INFO stats command.
Verdalia: Design and Measurement
What Is Cached and for How Long
| Data | Key | TTL | Invalidation |
|---|---|---|---|
| Product page | product:<id> |
5 minutes | When the name or the price changes |
| Listing of a category | listing:<category>:<page> |
2 minutes | By expiration only |
| List of categories | categories |
1 hour | When a category is modified |
| Displayed stock | stock:<id> |
10 seconds | By expiration only |
| Search results | Not cached | Almost every search is different | |
| Cart, orders, and customer data | Not cached | They are personal and must be exact |
The design decisions:
- Cache-aside on Redis, the same one that holds sessions and carts on
verdalia-aux-01. The catalog cache takes up about 60 MB. - Listings are not invalidated. A price change affects a number of listings that is hard to know. With a 2-minute TTL, the mismatch is brief, and Andrés has accepted it.
- Stock is displayed 10 seconds late, but it is always checked on confirmation. The “Last units” notice may be somewhat out of date. Deducting stock is still the conditional
UPDATEfrom Module 3, against the database. The last olive tree still cannot be sold twice. - The TTL carries a random variation of up to 10%, to avoid mass expirations.
- Before the campaign, the cache is warmed up with the 300 most visited products and the 60 categories.
- Images and static files are served through a CDN, whose origin is the object storage. Pages do not go through the CDN, because their header shows the customer's name and the number of items in their cart.
A note on sharing Redis. A cache may evict data when memory fills up, and a cart store must not. As long as the cache takes up 60 MB on an 8 GB machine, there is no conflict. If it grew, it would have to be separated into another instance.
Measurement
The changes were deployed on Tuesday, February 23. Lucía repeated the 250-user load test on Wednesday, February 24:
| Measure | February 17 | February 24 |
|---|---|---|
| Hit rate of the catalog cache | No cache | 92% |
| Queries per second to the database | 95 | 21 |
| Server time for the listing, median | 41 ms | 9 ms |
| Image requests that reach Verdalia | All | 6% |
| 95th percentile of the catalog, 250 users | 640 ms | 290 ms |
| 99th percentile of the catalog, 250 users | 1.7 s | 0.9 s |
| Limit of the single server | 420 users | 600 users |
| Capacity of a size M application server | 52 requests per second | 85 |
The cost is €12 a month for the CDN and €4 for the object storage. With 85 requests per second per server, the servers_needed function gives 3 application servers for 1,000 users: two to serve the load and one spare. We started the module with 7.
Common Mistakes and Tips
- Caching to cover up a problem. A slow query that is cached is still slow on every miss. First you optimize and then you cache, in that order.
- Not setting an expiration. An entry with no TTL and no invalidation is false data waiting for its moment.
- Updating the copy instead of deleting it. Two simultaneous writes can leave the older value in the cache. Deleting is safer.
- Caching personalized responses in shared caches. It is the fastest way to show one customer another customer's data.
- Deciding with cached data. To display, the copy. To charge or deduct, the origin.
- Depending on the cache to function. If the store cannot handle the load with an empty cache, a Redis restart is an outage. You have to know that limit and warm up.
- Not measuring the hit rate. Below 50%, it is worth reviewing what is cached and with which keys.
- Practical tip. For every piece of data you are about to cache, write one sentence: “If this data is up to X minutes stale, what happens is...” If the sentence ends badly, reduce X or do not cache it.
Exercises
Exercise 1: Which Header Applies
Give the appropriate Cache-Control header for each resource, and whether it can be served through the CDN:
- Verdalia's logo, in the file
logo.8c21e0.svg. - The “My orders” page.
- The guide “How to care for a potted olive tree,” identical for every visitor, which is corrected from time to time.
- The API response that says whether there is stock left, at the moment of paying.
Exercise 2: The Mother's Day Stampede
The home page product receives 40 visits per second. Its product page takes 300 ms to compute when it is not in the cache, and it has a 5-minute TTL. Explain what happens at the instant it expires and modify the product method to reduce the problem.
Solutions
Solution to Exercise 1
| Resource | Header | CDN? |
|---|---|---|
| 1. Logo with fingerprint | public, max-age=31536000, immutable |
Yes |
| 2. “My orders” | no-store |
No |
| 3. Care guide | public, max-age=300, with ETag |
Yes |
| 4. Stock at checkout | no-store |
No |
In case 3, a short TTL with ETag lets corrections show up within 5 minutes without downloading the guide again when it has not changed. In case 4, the data is used to make a decision, and it must always come from the origin.
Solution to Exercise 2
During the 300 ms the product page takes to compute, 12 requests arrive. All of them find the cache empty and all of them compute the same thing at once. If the database is loaded, the computation gets longer, more requests arrive, and the problem feeds itself. A simple solution, with a lock:
import threading
lock = threading.Lock()
def product(self, product_id):
key = f"product:{product_id}"
product = self._cache.get(key)
if product is None:
with lock: # only one request recomputes
product = self._cache.get(key) # another one may have filled it already
if product is None:
product = self._repository.find(product_id)
self._cache.set(key, product, self.PRODUCT_TTL_SECONDS)
return productThe first request takes the lock and computes. The others wait and, when they get in, look in the cache again, which is already filled. There are two limitations: threading.Lock only works within a single process, so with several servers the lock would have to live in Redis, and a single lock for all keys makes unrelated products wait. A real version would use one lock per key.
Conclusion
In this lesson you have learned that a cache is a copy placed closer to whoever needs it, and that it works when data access concentrates on a few items, reads outnumber writes, and some staleness is tolerated. You have gone through the cache levels, from the browser to the database, and the Cache-Control and ETag headers. You have compared the cache-aside, read-through, write-through, and write-behind strategies, seen how a cache is kept up to date, which data must not be cached, and which problems appear under high traffic. You have also learned about CDNs.
At Verdalia, the catalog is served with cache-aside on Redis, with a 92% hit rate, and the images reach customers from a CDN. The 95th percentile with 250 users has dropped from 640 to 290 ms, the single server reaches 600 users, and the application servers needed for the campaign are 3.
The time has come to spread out the store. The application keeps no state, each request costs little, and we know how many servers are needed. What is missing is the piece that receives the customers' requests and decides which server to send each one to. We will study it in the next lesson, “Load Balancing.”
