M. Kodirov

STAGE 07 / LESSON 04

Caching and stale data

Caching trades some freshness and complexity for faster or cheaper reads.

THE IDEA

Understand it.

Choose what can safely be cached and for how long. Public product descriptions and a private user’s authorization decision have very different sensitivity and freshness requirements.

When underlying data changes, invalidate or refresh the relevant cache entry. Account for failures and concurrency: a short TTL limits how long data is stale, but does not eliminate stale data entirely.

SEE IT IN CONTEXT

A task update

1. Read task 42 from database and cache it.
2. User updates task 42 in the database.
3. Invalidate or refresh the cached task.
4. A later read obtains the updated value.

The exact ordering and failure handling depend on the consistency the feature requires.

LEARN FROM REAL WEBSITES

See it in the real world.

These simplified structures come from public sources. Company systems change, and the sources may describe only one project or an earlier design.

Shopify

Shopify engineering, 2021

Keep a feed cache fresh

Shopify's Shop app team described a Memcached strategy that invalidated a cache entry around a database update.

  1. Invalidate cache
  2. Update database
  3. Revalidate cache

What to learn: When underlying data changes, cached values need a freshness strategy. The article discusses a specific 2021 system.

Read the source: Shopify Shop app caching

GitHub

GitHub engineering, 2017

A cache separate from durable data

GitHub described using Redis as a cache for computations over data persisted elsewhere, while moving persistent uses out of Redis.

  1. Durable data
  2. Computed result
  3. Redis cache

What to learn: A cache is a copy or derived result; decide how it is refreshed or discarded when the source changes.

Read the source: GitHub Redis caching

TRY IT YOURSELF

Practice.

Why should one user’s private task list not use a shared cache key such as 'tasks' for everyone?

Show one possible answer

The cached response could be served to the wrong user. Include the appropriate user or tenant scope and still enforce authorization.

GO DEEPER

Official references.