Redis caching strategy: keys, TTLs, invalidation and stampedes
Decide what to cache in Redis and how: a pattern per data type, key naming, jittered TTLs, invalidation, stampede protection, memory policy and sample code. Designed for ChatGPT, Claude, Gemini and Microsoft Copilot. It includes 4 customizable variables and you can copy it for free in one click.
Advanced · Code · Pending editorial review
Prompt
Act as a backend architect specializing in performance and Redis caching.
Context:
- Application and stack: {{application}}
- Data that could be cached and its read and write pattern: {{data}}
- Tolerance for stale data: {{staleness}}
- Current problem: {{problem}}
Deliverables:
1. What to cache and what not to: a table with each data item, estimated read/write ratio (or [FILL IN] if unknown), cost to recompute and the decision.
2. The pattern for each item (cache-aside, read-through, write-through or write-behind) and why.
3. Key design: naming convention, a version prefix for bulk invalidation, and how to avoid unbounded key growth.
4. TTLs per data type, with jitter so they do not all expire at once.
5. Invalidation: which events delete or update each key, how to avoid race conditions between the database write and the cache write, and what happens if invalidation fails.
6. Cache stampede protection: a lock with `SET NX` and expiry, probabilistic early refresh, or serving stale data while recomputing.
7. Redis configuration: `maxmemory`, the right eviction policy, serialization and maximum value size.
8. Behavior when Redis is down: short timeouts, falling back to the database, and protecting the database from overload.
9. Metrics to track (hit rate, latency, evictions, memory) and a gradual rollout plan.
10. Sample code in my stack for the main case, including stampede protection.
Constraints:
- Do not give invented improvement numbers; explain how to measure before and after.
- If volume or consistency details are missing, ask me before recommending.
- Flag any data that must never be cached in a shared way (for example another user's personal data).How to use it
- List your slowest or most-called endpoints or queries and how often their data changes.
- State how stale each item can be without causing problems.
- Roll out caching on one case first, measure the hit rate, then expand.
Usage example
App: Laravel store on PHP 8.3 · Data: catalog (changes a few times a day) and stock (changes every minute) · Problem: category page takes 1.8 s at peak.
Sample output
1. What to cache
| Data | Read/write | Decision |
|---|---|---|
| Catalog per category | Very high / a few per day | Cache-aside, TTL ~10 min |
| Stock | High / every minute | 30 s TTL or read from MySQL |
| Cart | Per user | Per-user key, never shared |
| Price at checkout | — | Do not cache: always from MySQL |
10. Code: catalog with stampede protection
public function productsForCategory(int $categoryId): array
{
$version = Cache::get('catalog:version', 1); // bump it to invalidate the whole catalog
$key = "v{$version}:category:{$categoryId}:products";
$ttl = 600 - random_int(0, 60); // jitter so keys do not expire together
if (($cached = Cache::get($key)) !== null) {
return $cached;
}
// Only one process rebuilds; the others wait up to 3 s
return Cache::lock("lock:{$key}", 10)->block(3, fn () =>
Cache::remember($key, $ttl, fn () => Product::query()
->where('category_id', $categoryId)
->where('active', true)
->get(['id', 'name', 'slug', 'image'])
->toArray())
);
}
If block() throws LockTimeoutException, serve the last copy or query MySQL behind a concurrency limit. Measure hit rate and the page's p95 latency before and after the rollout…
Key facts
- Category
- Programming & development · Software architecture
- Output type
- Code
- Level
- Advanced
- Designed for
- ChatGPT, Claude, Gemini and Microsoft Copilot
- Verified in
- Pending editorial verification
- Variables
- Application and stack, Data and access pattern, Stale data tolerance and Current problem
- Language
- English
- Price
- Free, no sign-up
- Updated
- Nov 7, 2026
Frequently asked questions
What is a cache stampede?
It happens when a hot key expires and hundreds of requests try to rebuild it at once, hammering the database. A lock so only one request regenerates it, or refreshing it before it expires, prevents it.
Why add jitter to TTLs?
If many keys are created together with the same TTL, they expire together and cause a load spike. A small random offset spreads those expirations out.
Which Redis eviction policy should I choose?
If Redis is only a cache, allkeys-lru or allkeys-lfu usually fit. If it shares an instance with data you cannot lose, such as queues, move that data to a separate instance.
What is this prompt for?
Decide what to cache in Redis and how: a pattern per data type, key naming, jittered TTLs, invalidation, stampede protection, memory policy and sample code.
Which AI tools does it work with?
It is designed for ChatGPT, Claude, Gemini and Microsoft Copilot. We have not verified it in these tools yet, so results may vary between them.
How do I customize the prompt?
Click “Customize” and fill in the variables (Application and stack, Data and access pattern, Stale data tolerance and Current problem). The text updates instantly and you can then copy it in one click. Values are stored only in your browser.
Do I need experience to use it?
It is advanced: it is meant for people with experience in the topic who can evaluate and adjust the result.
Is this prompt free?
Yes. Every HomeCasa Prompts prompt is free, with no sign-up or subscription. You can also use them in professional projects.
Can I trust the AI output?
Treat it as a high-quality draft: always check data, figures and important claims before publishing or making decisions.