Sub topic 1
What a Cache Is and When It Pays Off
Assume you know basic Python, client-server requests, databases, latency, and throughput. A cache is a fast storage layer that keeps copies of data so later requests can avoid slower work.
Prerequisites
You should understand basic programming, database reads, and request latency.
What a Cache Is and When It Pays Off
A cache helps when the same data is requested repeatedly and the cached copy remains useful for some time. A cache hit returns data from the cache. A cache miss requires reading from the original data source.
The hit ratio is the fraction of requests served by the cache:
hits / (hits + misses)
A cache pays off when its lookup latency plus maintenance cost is lower than repeatedly accessing the source. It also reduces database load. However, cached data can become stale, and cache failures add another failure mode.
| Result | Effect |
|---|---|
| High hit ratio | Lower latency and source load |
| Low hit ratio | Extra complexity with little benefit |
| Stale entry | Faster but possibly incorrect response |
The Layers Where Caching Happens
Caching can occur at several layers:
- A browser stores responses on the client.
- A content delivery network (CDN) stores public content near users.
- An application cache stores objects in process memory or a shared service.
- A database may cache query pages or index data internally.
Each layer has a different owner, scope, and invalidation method. A browser cache is local to one user. A shared application cache can serve many users but must handle concurrency and consistency.
Designing Cache Keys
A cache key identifies one cached value. Include every input that changes the result. For example, user:42:en can represent user 42’s English-language profile. Use stable formatting, explicit versions, and a namespace such as user: or report:.
Do not put secrets or unbounded raw input into keys. Keep keys specific enough to prevent one request from receiving another request’s data.
Cache-Aside: the Default Read Pattern
With cache-aside, the application checks the cache first. On a miss, it reads the database, stores the result, and returns it. After a write, it updates the database and invalidates the related cache entry.
cache = {}
def get_user(user_id, db):
key = f"user:{user_id}"
if key in cache:
return cache[key]
value = db.fetch_user(user_id)
cache[key] = value
return value
def update_user(user_id, data, db):
db.save_user(user_id, data)
cache.pop(f"user:{user_id}", None)Read-Through Caching
With read-through caching, the cache owns the miss handling. The application asks the cache for a value, and the cache calls the database loader when needed. This centralizes loading logic, but it requires a cache library or service that supports loaders.
Exercise
A report is requested once per hour by many users. Which cache property should you measure first?
Show answer
Measure the hit ratio and compare cache latency with the report-generation latency.