← Lessons

quiz vs the machine

Silver1120

Databases

Query Result Caching

Reuse a stored answer instead of recomputing the same query.

4 min read · intro · beat Silver to climb

Skipping Repeated Work

If the same expensive query runs again and again with the same inputs, recomputing it each time wastes resources. Query result caching stores the result so a repeat request returns the cached answer instead of touching the tables.

Where Caching Lives

  • In the application, where you store results in a fast key value store keyed by the query.
  • In a proxy that sits in front of the database and serves repeated reads.
  • Some databases offer a built in result cache for identical query text.

The Hard Part Is Invalidation

A cached answer goes wrong the moment the underlying data changes. You must decide how to keep it fresh.

  • Time based expiry drops the entry after a set age and accepts brief staleness.
  • Event based invalidation clears the entry when a related write happens.

When It Helps

Caching shines for read heavy workloads where data changes slowly and the same questions repeat. It hurts when data changes constantly, since you would invalidate as fast as you cache.

Key idea

Query result caching reuses stored answers to avoid recomputing repeated queries, and its central challenge is invalidating entries before they serve stale data.

Check yourself

Answer to earn rating on the learn ladder.

1. What is the hardest part of query result caching?

2. When does result caching help most?