# Design a caching strategy with safe invalidation

Decides what to cache, where, and for how long, with invalidation rules and failure modes so the cache doesn't serve wrong data.

- Topic: Software Development
- Framework: Few-Shot
- Level: Standard
- Tags: Strategy, Write, Plan, Fill-in Template
- Source: https://www.thinkwithprompt.com/prompts/design-a-caching-strategy-with-safe-invalidation

## Prompt

```text
Help me design caching for a slow or expensive part of my system.

**What's slow or expensive:** [ENDPOINT, QUERY, OR COMPUTATION, WITH CURRENT LATENCY OR COST IF KNOWN]
**Read vs. write pattern:** [HOW OFTEN DATA IS READ AND CHANGED]
**How stale can data be?** [e.g. "must be exact", "a few minutes is fine", "varies by field"]
**Is data per-user or shared?** [DETAILS, INCLUDING ANY PERMISSIONS OR PRIVATE DATA]
**Stack and available tools:** [e.g. "Redis", "CDN", "in-process memory", "HTTP caching"]
**Scale:** [REQUESTS PER SECOND, NUMBER OF INSTANCES]

Design:
1. **Where to cache:** browser/HTTP headers, CDN, application memory, distributed cache, database materialized views. Recommend one or a combination, with reasons.
2. **Pattern:** cache-aside, read-through, write-through, or write-behind, and why.
3. **Keys:** a key scheme including versioning and tenant/user scope. Explicitly check that one user can never see another user's cached data.
4. **Expiry and invalidation:** TTLs per data type and event-based invalidation on writes. Point out where invalidation could be missed.
5. **Failure modes:** cache stampede, hot keys, cold start after a deploy or flush, stale data after failed invalidation, cache outage. Give a mitigation for each.
6. **Measurement:** hit rate, latency, and staleness metrics to confirm it's working.

Return: the design summary, a table (data, cache layer, key, TTL, invalidation trigger), example code for my stack, and a list of "don't cache this" items.
```

## What to fill in

- HOW OFTEN DATA IS READ AND CHANGED
- DETAILS, INCLUDING ANY PERMISSIONS OR PRIVATE DATA
- e.g. "Redis", "CDN", "in-process memory", "HTTP caching"
- REQUESTS PER SECOND, NUMBER OF INSTANCES

Free to copy and use. From ThinkWithPrompt (https://www.thinkwithprompt.com/), a library of 2,663 curated AI prompts.
