Sub topic 3
Designing cache keys
A cache key is the identifier a cache uses to find a stored value. A bad key causes wrong answers, not just slow ones. If two different requests share a key, one user gets another's data. If one logical request maps to many keys, the hit ratio drops and memory fills with duplicates.
This chapter assumes you know basic Python, how a client-server request works, and what a cache hit and miss are from the fundamentals chapter.
What a key must do
A good key satisfies three rules.
- Uniqueness. Two requests that can produce different results must never share a key.
- Stability. Two requests that produce the same result should share a key, so they hit the same entry.
- Predictability. Any code that writes or invalidates an entry must be able to rebuild the exact key without a lookup.
Uniqueness protects correctness. Stability protects the hit ratio. The two pull against each other: adding more fields to a key makes it safer and also splits entries into more pieces.
Build keys from the inputs that change the result
Ask one question: which inputs, if changed, change the output? Put exactly those inputs in the key.
Consider a function that returns a product listing.
def list_products(category, page, page_size, currency, locale):
...The output depends on all five arguments. A key built from only category and page would return prices in the wrong currency to some users. A key that also included the user's session ID would be correct but would never be shared, because every user would get a separate entry for identical data.
| Input | Changes the output? | In the key? |
|---|---|---|
| `category`, `page`, `page_size` | Yes | Yes |
| `currency`, `locale` | Yes | Yes |
| Session ID | No | No |
| Request timestamp | No | No |
A readable key format
Use a consistent structure with a namespace, an entity type, and an identifier. Colons are a common separator.
def product_list_key(category, page, page_size, currency, locale):
return f"shop:v3:products:{category}:{page}:{page_size}:{currency}:{locale}"Each part has a job:
shopis the namespace. It prevents collisions when several services share one cache server.v3is a version. Changing it makes every old entry unreachable at once (see below).productsnames the entity type, which helps when you inspect keys by hand.- The remaining fields are the inputs, in a fixed order.
Keep the order fixed. a:b and b:a are different keys, so two code paths that build the same logical key in different orders will each miss.
Normalize inputs before building the key
Equivalent inputs should produce the same key. Normalization is the step that makes that true. Typical cases:
- Case.
Shoesandshoesshould become one value. - Whitespace. Trim leading and trailing spaces.
- Defaults. A missing
pageandpage=1mean the same thing. - Parameter order. In a URL,
?a=1&b=2and?b=2&a=1are the same request. - Types.
42and"42"become the same text once formatted into a string.
The following function normalizes a set of query parameters into a stable key.
from urllib.parse import urlencode
DEFAULTS = {"page": "1", "sort": "relevance"}
def search_key(path, params):
merged = {**DEFAULTS, **params}
cleaned = {
name.strip().lower(): str(value).strip().lower()
for name, value in merged.items()
if value is not None and str(value).strip() != ""
}
query = urlencode(sorted(cleaned.items()))
return f"web:v1:search:{path}?{query}"
print(search_key("/shoes", {"Color": "Red", "page": 1}))
print(search_key("/shoes", {"page": "1", "color": " red "}))Both calls print web:v1:search:/shoes?color=red&page=1&sort=relevance. Without normalization they would be two entries.
Only normalize what the backend also treats as equal. If the database search is case-sensitive, lowercasing the key would merge requests that return different results. That is a correctness bug.
Include everything that varies the result
Some inputs are easy to forget because they are not function arguments.
- User or tenant. Per-user data needs the user ID. In a multi-tenant system, every key needs the tenant ID, or one customer can read another's data.
- Permissions. If the response differs by role, include the role or a permission group, not just the user.
- Language and region. Include the locale when content is translated.
- API version or feature flags. A new response shape must not be served from an old entry.
- Request headers. For HTTP caches, headers such as
Accept-LanguageorAccept-Encodingcan change the body. TheVaryheader tells HTTP caches which request headers to add to the key.
Long and untrusted values
Keys have limits. Redis allows large keys but they cost memory and time. Memcached limits keys to 250 bytes and forbids spaces and control characters. Two problems follow.
- Length. A key built from a long search string or a large filter object can exceed the limit.
- Unsafe characters. User text may contain spaces, newlines, or separators like
:.
The usual fix is to hash the variable part and keep the readable prefix.
import hashlib
import json
def filter_key(namespace, filters):
canonical = json.dumps(filters, sort_keys=True, separators=(",", ":"))
digest = hashlib.sha256(canonical.encode("utf-8")).hexdigest()[:32]
return f"{namespace}:filters:{digest}"
key_a = filter_key("shop:v3", {"brand": "acme", "price": [10, 50]})
key_b = filter_key("shop:v3", {"price": [10, 50], "brand": "acme"})
print(key_a == key_b) # Truesort_keys=True makes the JSON text identical no matter how the dictionary was built, so the hash is stable. Truncating a SHA-256 digest to 32 hex characters leaves 128 bits, which makes accidental collisions negligible. Do not use Python's built-in hash() for keys. It is randomized per process for strings, so different servers compute different values.
The cost of hashing is that you can no longer read the key. Keep a readable prefix so you can still find entries by type, and log the original inputs when debugging.
Key cardinality and memory
Cardinality is the number of distinct keys a design can produce. A key including a timestamp to the second has near-infinite cardinality, so every request misses and the cache fills with entries that are never read again. Watch for these sources of runaway cardinality:
- Raw timestamps or random values.
- Full URLs including tracking parameters such as
utm_source. Strip parameters that do not change the response. - Free-text search strings. Consider caching only the most common queries.
Low hit ratio together with a rising eviction count often points to a key with too much variation.
Versioning keys
When the shape of cached data changes, old entries can break new code. Including a version in the key avoids a manual purge: bump v3 to v4, and the new code reads and writes a separate set of entries. The old ones are never read again and are removed by TTL or eviction.
For entities that change often, a per-entity version works too. Store a counter such as user:42:version and include its value in dependent keys. Incrementing the counter orphans every key built from the old value in one operation. The cost is one extra lookup per read.
Keys and invalidation
The invalidation chapter covers this in depth, but key design decides how easy it is. The cache-aside code from the earlier chapter deletes user:{user_id} after a write. That works because the writer can rebuild the key from the user ID alone.
Compare that with the filter key above. After a product changes, which hashed keys contain it? You cannot tell from the digest. Keys that bundle many entities make precise invalidation hard. Common responses are short TTLs on list-style entries, version counters, or tracking which keys belong to an entity in a separate set.
Common mistakes
- Omitting an input that changes the output, which returns wrong data.
- Including an input that does not change the output, which lowers the hit ratio.
- Building keys by string concatenation in several places. Put key construction in one function per entity.
- Putting
Noneor an empty value in a key so it reads as"None", which can collide with a real value. - Using ambiguous separators. With
:as separator, the parts("a:b", "c")and("a", "b:c")both givea:b:c. Escape or hash values that may contain the separator.
Exercise
A service caches search results with the key search:{query}. Users report that some people see results in the wrong language, and the hit ratio is low because Shoes and shoes are cached separately. Name the two changes you would make to the key design and explain what each fixes.
Show answer
First, add the locale (and any other input that changes the output) to the key, for example search:v1:{locale}:{normalized_query}. This stops one language's results from being served to users of another. Second, normalize the query by trimming whitespace and lowercasing it, but only if the search backend treats those forms as equal. This merges Shoes and shoes into one entry and raises the hit ratio.
Exercise
Why is hash(text) a poor choice for building cache keys shared by several servers, and what should you use instead?
Show answer
Python randomizes the built-in hash() for strings per process, so each server computes a different value for the same text and they never share entries. Use a stable digest such as SHA-256 from hashlib over a canonical form of the input.