Application caching Cache keys

Application caching

Cache keys

Deep diveAbout 10 minutes AI-generated

A cache key names an answer that another request can reuse. The application builds the key before it looks in the cache, so every distinction the lookup needs must already be there. A store can return exactly the value it was given and still return the wrong answer, because two different questions were given the same name.

For the shop’s blue mug, knowing the product is not enough. The card also belongs to a shop, a language and a currency. Those distinctions belong in its name; the browser that asked for it does not.

The examples hold the source state fixed while comparing requests. That lets us decide which requests may share an entry. Freshness and invalidation takes the next question: what happens when the source or the permission to read it changes.

The key names an answer

The product ID P7 is unique inside shop north, but south can use it for another product. A key containing only that ID lets one shop find the other’s card. The cache reports a hit, even though the application has answered the wrong question.

Adding the shop separates those two products. But a product card also has a language and a currency, and another operation might store a stock record under the same product ID. The key needs to identify the operation and its context, as well as the product.

Figure 1. Each field preserves a distinction the answer needs. A request identifier would divide otherwise identical answers.

The complete card key is product:v1:north:P7:en-GB:GBP: operation, format, shop, product, language and currency. Each field prevents different answers from being mistaken for one another. The source supplies the requested language and currency; the cache only keeps the result. A prefix reserves an application naming convention, not a protected part of the store.

At a fixed source state, requests mapped to one key must be able to use the same answer. North and south fail that test even if their prices happen to match today. They are independent products and can differ. Conversely, two requests for north’s P7 in en-GB and GBP can share the card even when they come from different browsers.

This is an application decision. An in-process dictionary, a cache library and a shared store such as Redis all need the same identity. Moving the value to another store cannot restore a distinction that the application left out.

Which inputs change the result

Build the key from the inputs to the work you are saving. For a product card those inputs are small. For a list of products, the question includes its filter, sort order, page and selected fields. Caching only “north’s products” would make different lists share a result.

Suppose the list asks for products below GBP 21.00, sorted by price, ten per page. P7 belongs to it at GBP 20.00. A page number changes which slice to return; a descending sort changes which products come first. Even before the catalogue changes, those requests need different answers.

Changing one input to the product-list request
ChangeWhat the result can changeKey decision
Price limit: 2100 → 1900 penceP7 leaves the result.Include the filter.
Ascending → descending priceThe order and first page can differ.Include the sort.
Page 1 → page 2A different slice of the ordered result.Include the page and page size.
Names only → names and pricesThe returned fields differ.Include the projection, or cache data that builds both.
A new request IDNothing in the list’s contents.Leave it out.

A request ID identifies one attempt, which is useful in a trace. Including it in the key would give every attempt its own entry. A timestamp taken on arrival can destroy reuse in the same way. Extra fields are not harmless: each one can divide requests that should have shared a copy.

Personalisation can make this division necessary. A full response containing a reader’s saved favourites differs for each reader. Often the useful shared result is smaller: cache the public product card, then add the reader’s favourite marker afterwards. Deciding what and where to cache explains how that choice changes the work a hit saves.

Normalising equivalent requests

Different request spellings can mean the same thing. Define the list’s contract to default to page 1 and ascending price. Under that contract, ?max_price_pence=2100 and ?page=1&sort=price_asc&max_price_pence=2100 ask for the same list. Parse and validate both into the same typed fields before making the key.

The canonical form might be the tuple ["north", "en-GB", "GBP", 2100, "price_asc", 1, 10, "card"]. Its field order is fixed: shop, locale, currency, price limit, sort, page, page size and projection. Both requests then have one spelling at the cache boundary.

This normalisation follows the query’s meaning. Sorting parameter names is safe only if their order is irrelevant. Repeated parameters might be a list whose order matters. An omitted search term can mean “all products” while an explicit empty term is invalid. Lowercasing an identifier is safe only when the source treats those cases as identical. Preserve distinctions until the application’s contract says they can be removed.

Encoding the parts without collisions

Choosing the right fields is only half the job. Their encoding must keep them separate. Our baseline key uses colons because its identifiers are validated to contain only ASCII letters, digits, underscores and hyphens. None can contain the separator. The fixed number and order of fields make the boundaries unambiguous.

Allow the separator inside a field and the boundaries become ambiguous. Suppose one request names shop north:outlet and product P7, while another names shop north and product outlet:P7. Joining either pair with a colon produces north:outlet:P7. The remaining key fields are identical, so the complete keys collide too.

Figure 2. Only the shop and product fields are drawn. The operation, version, language and currency are identical in both requests.

The two field boundaries described different products, but their joined bytes no longer do. The cache cannot recover that distinction. The collision happened in the application’s naming scheme, before any store-specific hashing.

A fixed JSON array is one unambiguous encoding for these string fields. Quoting and escaping preserve commas, colons and quote characters inside each string. The function below gives that alternative its own product-json:v1: prefix, so it cannot be mistaken for the original colon format.

function productKey(shop, id, locale, currency) {
  const parts = [shop, id, locale, currency];
  if (!parts.every(part => typeof part === 'string')) {
    throw new TypeError('Key fields must be strings');
  }
  return 'product-json:v1:' + JSON.stringify(parts);
}

Every reader, writer and invalidator must use the same construction. Agree the field order, accepted types, string normalisation and byte encoding across languages. JSON describes values, but permits different spellings of the same value; a fixed encoder convention is still needed to produce identical keys. Avoid arbitrary object serialisation whose field order may differ between callers. A length-delimited binary encoding is another option when all clients share its definition.

A digest can shorten a long encoded request. For example, a readable operation prefix can precede a SHA-256 digest of the complete canonical bytes. That introduces the digest’s collision risk, so a design may also retain and compare the original context. Hashing cannot fix either earlier mistake: omitted fields and ambiguous joins already produce identical input bytes.

Redis accepts binary-safe keys, and colons are only a naming convention. They do not create folders or permissions. Other stores and client APIs impose different character or length limits, so check the whole storage path before choosing an encoding. Keep raw credentials and sensitive request text out of key names, which can appear in diagnostic tools and logs. A digest is not encryption and does not make guessable sensitive input secret.

Sharing data without sharing permission

The catalogue so far is public. Consider a separate variation: an application view that only authorised readers may open. A permitted request fills the cache. A denied reader then asks for the same view. If the hit path returns immediately, it has skipped the decision that protected the miss.

Figure 3. A restricted-view example. The server checks the current caller before returning data, including on a cache hit.

Sharing the data does not mean sharing an earlier reader’s permission. The application checks the current caller against the requested resource. If checking access needs some product attributes, it may retrieve those internally first, but it must still make the decision before returning restricted data.

A different design caches the already filtered response. If one audience can see fields that another cannot, their responses need separate identities. Include the relevant audience, or the principal when the answer is individual. Derive that context from the application’s authenticated and authorised request, rather than trusting a caller-supplied audience label.

A shop prefix separates names; it neither authenticates a reader nor grants access. Likewise, putting a user ID in a key does not make an old permission decision current. Revocation and policy changes can invalidate a previously permitted response, which is part of the freshness problem. Permissions on the shared store itself are covered in Operating a cache.

Changing the cached representation

A cache entry can outlive the application process that wrote it. During a deployment, old and new readers may also use the store at the same time. Each needs to understand what the stored fields mean.

A price stored as integer pence and a price stored as display text need different decoding. Changing that format is separate from changing the price itself.

Figure 4. The format describes how to read a value. The source revision identifies which product state it describes.

A compatible decoder can keep using the same namespace when it understands every format it may encounter. Adding an optional field can work if older readers safely ignore it and newer readers tolerate its absence. An incompatible change can use a new namespace, such as product:v2:, so each reader asks for its own representation.

The source revision identifies the product state, not how it is encoded. Updating a price can leave the key and format unchanged. Renaming the format on every product update would leave readers needing another way to find the current key.

The worked adapter stores an envelope: metadata around the product that tells the reader how to interpret it. Its format is explicit, as is the request context.

{
  "schema": 1,
  "context": {
    "shop": "north", "id": "P7",
    "locale": "en-GB", "currency": "GBP"
  },
  "kind": "product",
  "product": {
    "id": "P7", "name": "Blue mug",
    "price_pence": 2000, "currency": "GBP",
    "revision": 1
  }
}

Decoding JSON is the first check. The reader also requires a supported schema, the expected context and a recognised kind. A product result needs the required fields with their expected types and units. Its ID and currency must agree with the context. The context check can catch a wrongly constructed key or a misdirected fill; it does not replace correct key construction.

Malformed JSON, an unsupported schema or the wrong context makes the cached value unusable. None proves that the product is absent. Treat it as no usable cached answer and follow the bounded source path developed in Caching with Redis. Keep rejected entries observable so repeated bad fills can be repaired.

A new namespace starts without useful entries while old ones still occupy memory. It can therefore increase both source demand and cache occupancy. Operating a cache follows the deployment and rollback consequences. The key’s format version prevents one kind of confusion; it does not make the rollout free.

Remembering that a result was absent

A successful source lookup can establish that a product does not exist. If the application saves nothing, repeated requests each pay for that same lookup. Negative caching saves the established absence as an answer.

An empty cache and a missing product are different facts. A source failure is different again.

Source outcomeSave for reuse
Product existsThe product card
Product is absentA not-found result
Lookup failsNothing
Figure 5. A failed lookup is not evidence of absence.

For the missing product P99, the key is still product:v1:north:P99:en-GB:GBP. The value records the absence explicitly:

{
  "schema": 1,
  "context": {
    "shop": "north", "id": "P99",
    "locale": "en-GB", "currency": "GBP"
  },
  "kind": "not-found"
}

A usable kind: "not-found" value is a cache hit. The application has an answer without a source call. An absent cache entry is a miss. A product with a zero price is a present product, and an empty result list can be a present list. Testing truthiness would blur these cases; use an explicit miss marker separate from valid result values.

A timeout establishes none of them. The source might hold P99 while being unable to answer. The worked adapter propagates source failures and does not save them as not-found results. That choice keeps a temporary failure from becoming a false claim about the catalogue.

The absence belongs to its context just as a product does. P99 being absent from north says nothing about south. A result filtered by access also belongs to the audience that was checked. Later creation of P99 ends the truth of the cached absence. The adapter illustrates a five-second lifetime for negative entries and thirty seconds for product entries; these are example choices. Freshness and invalidation explains expiry and the changes that require invalidation.

Checking a key design

Check the design with pairs of requests. Hold the source state fixed and change one input. If the requests can need different answers, their cache identities must remain separate. Then change an input that does not affect the answer, such as the request ID, and check that useful sharing survives.

Pairs to keep beside the key constructor
PairExpected result
North P7 / south P7Different keys: independent products.
Same product, another locale or currencyDifferent keys: another requested representation.
Same list, another filter, sort or pageDifferent keys: another query result.
Implicit page 1 / explicit page 1Same key under the declared default.
Same public card, another request IDSame key: no change to the card.
Two audiences with different filtered fieldsDifferent response keys, or share underlying data and filter after retrieval.
Incompatible v1 / v2 readersSeparate namespaces unless decoding is made compatible.

Give all read, fill and delete paths the same constructor. Exercise separator characters and invalid types at its boundary. Then check the decoder with a valid product, a valid not-found result, a missing entry and malformed or unsupported content. The tests should establish why each result can be used, not merely that a string was returned.

A key is useful when it separates answers that can differ while preserving sharing where they cannot. The value must then be something the reader understands and is permitted to use. With that identity established, the next question is how long the answer remains acceptable.

Sources and further reading

← Back to application caching