Cache: where it stands and what breaks in it
A cache keeps frequently read data in a fast store, but the copy can drift from the source. Almost all cache problems come down to how long the copy may be stale. For each type of data the promised delay must be known and checked with a wait that has an upper bound, not a fixed pause. Cache keys are tested with two users, plus an unavailable cache and a stampede.
System design · Backend
After a transfer the app shows the old balance while the database already has the new one. Where did the state get stuck?
A user made a transfer and refreshed the page: the balance did not change. Half a minute later it did. A test reads the balance from the API right after the transfer and fails only sometimes. The database is right, there is no error in the logs. The culprit is a cache: the balance was read from a store that does not know about the change yet. A cache is fast and useful, but it hides the most insidious bugs. The lesson covers where a cache sits, which patterns are used and what breaks in it.
How it works and why. A cache keeps frequently read data in a fast store (for example Redis in memory) to avoid going to the DB each time. The speed gap between memory and disk is large and most reads repeat. The price: a copy of the data may diverge from the source. Almost all cache problems are forms of one question: how long may the copy be stale and who controls it.
Cache-aside: read and write
Patterns.
- Cache-aside: the service looks in the cache and, if it is missing, reads from the DB and stores it. The most common.
- Write-through: a write goes to the cache and the DB together, so the cache is always fresh, but writes are slower.
- TTL: an entry lives in the cache for a limited time and disappears. It is insurance against forever stale data.
The hardest part is invalidation. For a product catalogue, 30 seconds of a stale price is often acceptable. For an account balance it is not. So for each data type you need to know which delay is promised and test exactly that.
Example: stale data and somebody else's data. The first check: after a change the new value must appear within the promised time. Instead of a fixed pause we use expect.poll and verify the upper bound:
test('a price change reaches readers within the TTL', async ({ request }) => {
await request.put('/api/products/sku-1', { data: { price: 120 } });
await expect
.poll(
async () => {
const res = await request.get('/api/products/sku-1');
return (await res.json()).price;
},
{ timeout: 35_000, intervals: [1000] }, // TTL 30 s + margin
)
.toBe(120);
});
The second check is about security. A wrong cache key (without the user id or currency) gives one user another user's data. That is a security incident, not a cosmetic issue:
test('the balance is not shared between users', async ({ browser }) => {
const a = await userContext(browser, 'alice');
const b = await userContext(browser, 'bob');
const balA = await (await a.get('/api/balance')).json();
const balB = await (await b.get('/api/balance')).json();
expect(balB.accountId).not.toBe(balA.accountId);
});
(userContext here is a project helper that returns a user's API context.) The order is what matters in the test: the first user warms the cache, the second reads the same keys.
The cache key
balance
One key for everyone. After the first read every user sees the balance of whoever warmed the cache.
balance:user:42:EUR
The key contains everything the response depends on: the user and the currency. Private data is also marked private for HTTP caches.
What else can break.
- Cache stampede. A popular key expired and thousands of requests go to the DB at once. Cured by letting one request refresh while others wait, TTL spread (jitter) or background refresh. Checked by a load test.
- Cache unavailable. The service must run slower but run, not return 500. Checked by turning the cache off in the test environment.
- Negative answers. If "not found" is cached, a freshly created record will be unavailable for a while. This is easy to check with a "create and read at once" test.
Limits and alternatives. For tests a cache adds one more problem: the test reads data that a previous test or run put into the cache. In test environments it helps to have a way to flush the cache (an admin endpoint or a separate key prefix per run) or short TTLs. Not every read is worth caching: data that changes on every request only adds complexity. For money data some choose not to cache at all and read from the primary DB, keeping the cache for reference data.
Common mistakes.
- Checking an update with a fixed pause instead of waiting for a condition with an upper bound.
- Not checking the cache key with two different users.
- Not flushing the cache between runs: the result depends on what the previous run left.
- Assuming a cache is only an optimisation: it changes behaviour and its failure must be tested too.
Check yourself
The catalogue promises "the price updates within 30 seconds" and a test with waitForTimeout(5000) after a price change fails. What is wrong with the test?
Answer
The test checks the wrong bound: a 5-second pause is shorter than the promised 30 and the failure is not a bug. The right thing is to wait for a condition with an upper bound, TTL plus margin (expect.poll with a timeout of about 35 seconds). It would be a bug if the new value did not appear even after that time.
User Bob sees Alice's balance after Alice opened the page. What is the most likely cause and why is it critical?
Answer
The cache key does not contain the user identifier: the first request filled the shared key and the second read it. This is a leak of someone else's data, a security incident. The fix: include in the key everything the response depends on and add a test with two users where the first warms the cache.
expect.poll and an upper bound. Separately I test cache keys with two users, behaviour when the cache is unavailable, a stampede under load and cache flushing between runs. I do not cache balances and similar data without a clear invalidation strategy.