Caching
Do the expensive thing once, then stop doing it.
Read this diagram as text
- Application
- Checks the cache before it touches the database.
- Database
- Consulted only on a miss, then the result is written back.
- Cache
- Returns in microseconds when the key is present.
- Application → Cache (1 · read)
- Cache → Database (2 · on miss)
- Database → Cache (3 · populate)
- The same expensive computation or query runs over and over for results that barely change. Read-heavy systems spend most of their capacity re-deriving answers they already had.
- Keep the result somewhere fast (in memory, in Redis, at the CDN), keyed by whatever the result depends on. Reads check the cache first. Writes either invalidate the key or let it expire.
- Every cache introduces a window where the world has changed and your answer has not. You are trading correctness-in-time for speed, and you have to decide how much of it you can afford, key by key rather than globally.
- The data is written as often as it is read, the query is already fast, or the correct answer changes per user in ways the key cannot capture. Caching a slow query is also how a missing index survives to production.