Sub topic 3
Designing Cache Keys
This chapter assumes you know what a cache is, what a hit and a miss are, and how to read basic Python. A cache key is the string or value that identifies one cached entry. A poor key design causes wrong answers, not only wasted memory.
What a key must do
A good key has two properties:
- Complete. Every input that changes the result is part of the key. If it is not, two different requests share one entry and one user sees another user's data.
- Minimal. Inputs that do not change the result are left out or normalized. Otherwise equal requests get different keys and the hit ratio drops.
Build keys from a pattern
Use a consistent layout: a namespace, the entity, the identifier, and a version. The cache-aside example uses user:{user_id}. A fuller form looks like this:
def user_key(user_id, version=1):
return f"app:v{version}:user:{user_id}"The v1 part lets you retire every old entry at once. When the stored shape changes, bump the version. Old keys are never read again and expire or get evicted.
Normalize the inputs
Different spellings of the same request should produce the same key. Sort query parameters, lowercase case-insensitive values, and drop parameters that do not affect the result.
import hashlib
import json
IGNORED_PARAMS = {"utm_source", "utm_medium", "session"}
def search_key(params):
relevant = {
k: str(v).strip().lower()
for k, v in params.items()
if k not in IGNORED_PARAMS
}
canonical = json.dumps(relevant, sort_keys=True, separators=(",", ":"))
digest = hashlib.sha256(canonical.encode("utf-8")).hexdigest()
return f"app:v1:search:{digest}"
a = search_key({"q": "Shoes", "page": 2, "utm_source": "ad"})
b = search_key({"page": "2", "q": " shoes "})
print(a == b) # TrueHashing keeps long parameter sets to a fixed length. The cost is that you can no longer read a key and tell what it holds, so log the canonical string while debugging.
Include what varies the response
| Varies by | Put in the key | Example |
|---|---|---|
| User | User ID | `app:v1:cart:u42` |
| Language | Locale | `app:v1:home:fr-FR` |
| Permissions | Role or tenant ID | `app:v1:report:t7:admin` |
| Pagination | Page and size | `app:v1:items:p2:s20` |
Shared data, such as a public product page, should not include the user ID. Adding it would give every user a separate copy of identical data.
Common errors
- Ambiguous joins. Joining parts with no separator makes
("1", "23")and("12", "3")both become"123". Use a delimiter that cannot appear inside the parts, or escape the parts. - Unbounded keys. Keys built from free-text input can fill the cache with entries that are never read again. Normalize, hash, or skip caching for those requests.
- Unstable serialization. Dictionary order or float formatting that changes between processes produces different keys for the same input. Always sort and format explicitly.
- No version. Without a version, a change to the stored shape serves old-format values to new code.
Exercise
A cache stores product pages under the key product:{id}. The page now shows prices in the visitor's currency, and users report seeing prices in the wrong currency. What is wrong, and how do you fix it?
Show answer
The key leaves out currency, which changes the response, so the first visitor's currency is served to everyone. Add the currency to the key, for example app:v1:product:{id}:{currency}. Since the stored shape also changed, bump the version so the old entries are not reused.