Redis caching, rate limiting, session storage, pub/sub, and production integration patterns for TypeScript, Next.js, NestJS, and Prisma applications. Use when adding cache-aside or write-through caching, rate limiting, session or lock storage, pub/sub fanout, or reviewing Redis key design and TTLs.
Implement Redis as a production support layer, not as a second database.
When to Use
Add cache-aside or write-through caching around Prisma or API reads.
Protect expensive routes with rate limiting.
Store short-lived sessions, verification state, locks, or counters.
Add pub/sub or stream-backed event fanout.
Review Redis key design, TTLs, invalidation, or connection handling.
For BullMQ job queue architecture, use nestjs-queue-architect instead of duplicating queue patterns here.
First Decisions
Choose the runtime.
Long-lived Node.js or NestJS process: use ioredis.
Serverless or edge runtime: prefer the Upstash Redis SDK or REST API.
Background jobs: use BullMQ guidance from nestjs-queue-architect.
Define the cache contract before coding.
Source of truth: Prisma/database, upstream API, computed result, or session authority.
Freshness: hard TTL, stale-while-revalidate, explicit invalidation, or write-through.
Failure mode: fail open for cache reads, fail closed for auth/session/rate-limit writes.
Design keys and invalidation together.
Namespace every key: app:env:entity:id:variant.
Keep keys stable and inspectable.
Add TTLs to every cache, lock, session, and rate-limit key.
Installation
bun add ioredis
# Optional serverless Redis
bun add @upstash/redis @upstash/ratelimit
Use one Redis client per process (a module-level singleton guarded against
hot-reload duplication). Do not create a new TCP client per request. Wire
error, connect, and reconnecting events into the app logger or APM. Avoid
logging credentials from connection URLs.
See references/examples.md (§ Redis Client Singleton) for the full setup.
Cache-Aside With Prisma
Use cache-aside for reads where brief staleness is acceptable: check the
cache, on miss call the loader, write back with a jittered TTL (baseTtl + random(0, jitter)) so hot keys don't all expire in the same instant.
See references/examples.md (§ Cache-Aside With Prisma) for the getCached
helper and a Prisma-backed usage example.
Stampede Protection
Protect hot keys with a short SET key val EX 10 NX lock. Only the holder
(matched by a random token) releases it; losers wait briefly and re-check the
cache before falling through to a direct load.
See references/examples.md (§ Stampede Protection) for the full
lock-and-release implementation.
Invalidation
Prefer direct invalidation for known keys. Use tag sets (a Redis set per tag,
mapping to the keys written under it) when one mutation affects many keys —
write through a pipeline, invalidate by reading the tag's key set and
UNLINK-ing them. Use SCAN instead of KEYS for emergency pattern cleanup.
Do not put pattern invalidation on hot request paths.
See references/examples.md (§ Tag-Based Invalidation) for the
cacheSetWithTags / invalidateTag implementation.
Rate Limiting
Use sorted sets for sliding-window limits when exactness matters: trim
expired entries, add the current request, count members, and set the key's
expiry — all in one MULTI. For public traffic, set response headers:
X-RateLimit-Limit, X-RateLimit-Remaining, and Retry-After.
See references/examples.md (§ Sliding-Window Rate Limiting) for the full
slidingWindowRateLimit implementation.
Sessions And Verification State
Store opaque session IDs or token hashes, not raw JWTs or long-lived secrets.
Set TTL on every session key.
Regenerate sessions after privilege changes.
Delete sessions on logout, account deletion, and password reset.
Treat Redis write failure as auth failure for login, logout, MFA, and password reset flows.
See references/examples.md (§ Session Storage) for a createSession example.
Pub/Sub And Streams
Use pub/sub for ephemeral fanout where missed messages are acceptable.
Use streams when consumers need replay, backpressure, or durable delivery.
Keep payloads small; store large objects elsewhere and publish IDs.
Add consumer observability: lag, dead letters, retries, and handler errors.
Production Checklist
All cache, lock, session, and rate-limit keys have TTLs.
Cache reads fail open where possible; auth and rate-limit writes fail closed.
Hot keys use TTL jitter or stampede protection.
No request path uses KEYS, unbounded SMEMBERS, or large HGETALL.
Invalidation is tested alongside the write path.
Redis metrics cover latency, hit rate, memory, evictions, blocked clients, and reconnects.
Local tests cover cache hit, cache miss, Redis down, invalidation, and rate-limit exceeded.
1---
2name: redis-caching
3description: "Redis caching, rate limiting, session storage, pub/sub, and production integration patterns for TypeScript, Next.js, NestJS, and Prisma applications. Use when adding cache-aside or write-through caching, rate limiting, session or lock storage, pub/sub fanout, or reviewing Redis key design and TTLs."
4metadata:
5 version: "1.0.1"
6 tags: "redis, caching, rate-limiting, sessions, prisma, nestjs, nextjs"
7---
89# Redis Caching
1011Implement Redis as a production support layer, not as a second database.
1213## When to Use
1415- Add cache-aside or write-through caching around Prisma or API reads.
16- Protect expensive routes with rate limiting.
17- Store short-lived sessions, verification state, locks, or counters.
18- Add pub/sub or stream-backed event fanout.
19- Review Redis key design, TTLs, invalidation, or connection handling.
2021For BullMQ job queue architecture, use `nestjs-queue-architect` instead of duplicating queue patterns here.
2223## First Decisions
24251. Choose the runtime.
26 - Long-lived Node.js or NestJS process: use `ioredis`.
27 - Serverless or edge runtime: prefer the Upstash Redis SDK or REST API.
28 - Background jobs: use BullMQ guidance from `nestjs-queue-architect`.
292. Define the cache contract before coding.
30 - Source of truth: Prisma/database, upstream API, computed result, or session authority.
31 - Freshness: hard TTL, stale-while-revalidate, explicit invalidation, or write-through.
32 - Failure mode: fail open for cache reads, fail closed for auth/session/rate-limit writes.
333. Design keys and invalidation together.
34 - Namespace every key: `app:env:entity:id:variant`.
35 - Keep keys stable and inspectable.
36 - Add TTLs to every cache, lock, session, and rate-limit key.
3738## Installation
3940```bash
41bun add ioredis
4243# Optional serverless Redis
44bun add @upstash/redis @upstash/ratelimit
45```
4647Use one Redis client per process (a module-level singleton guarded against
48hot-reload duplication). Do not create a new TCP client per request. Wire
49`error`, `connect`, and `reconnecting` events into the app logger or APM. Avoid
50logging credentials from connection URLs.
5152See `references/examples.md` (§ Redis Client Singleton) for the full setup.
5354## Cache-Aside With Prisma
5556Use cache-aside for reads where brief staleness is acceptable: check the
57cache, on miss call the loader, write back with a jittered TTL (`baseTtl +
58random(0, jitter)`) so hot keys don't all expire in the same instant.
5960See `references/examples.md` (§ Cache-Aside With Prisma) for the `getCached`
61helper and a Prisma-backed usage example.
6263## Stampede Protection
6465Protect hot keys with a short `SET key val EX 10 NX` lock. Only the holder
66(matched by a random token) releases it; losers wait briefly and re-check the
67cache before falling through to a direct load.
6869See `references/examples.md` (§ Stampede Protection) for the full
70lock-and-release implementation.
7172## Invalidation
7374Prefer direct invalidation for known keys. Use tag sets (a Redis set per tag,
75mapping to the keys written under it) when one mutation affects many keys —
76write through a pipeline, invalidate by reading the tag's key set and
77`UNLINK`-ing them. Use `SCAN` instead of `KEYS` for emergency pattern cleanup.
78Do not put pattern invalidation on hot request paths.
7980See `references/examples.md` (§ Tag-Based Invalidation) for the
81`cacheSetWithTags` / `invalidateTag` implementation.
8283## Rate Limiting
8485Use sorted sets for sliding-window limits when exactness matters: trim
86expired entries, add the current request, count members, and set the key's
87expiry — all in one `MULTI`. For public traffic, set response headers:
88`X-RateLimit-Limit`, `X-RateLimit-Remaining`, and `Retry-After`.
8990See `references/examples.md` (§ Sliding-Window Rate Limiting) for the full
91`slidingWindowRateLimit` implementation.
9293## Sessions And Verification State
9495- Store opaque session IDs or token hashes, not raw JWTs or long-lived secrets.
96- Set TTL on every session key.
97- Regenerate sessions after privilege changes.
98- Delete sessions on logout, account deletion, and password reset.
99- Treat Redis write failure as auth failure for login, logout, MFA, and password reset flows.
100101See `references/examples.md` (§ Session Storage) for a `createSession` example.
102103## Pub/Sub And Streams
104105- Use pub/sub for ephemeral fanout where missed messages are acceptable.
106- Use streams when consumers need replay, backpressure, or durable delivery.
107- Keep payloads small; store large objects elsewhere and publish IDs.
108- Add consumer observability: lag, dead letters, retries, and handler errors.
109110## Production Checklist
111112- [ ] All cache, lock, session, and rate-limit keys have TTLs.
113- [ ] Cache reads fail open where possible; auth and rate-limit writes fail closed.
114- [ ] Hot keys use TTL jitter or stampede protection.
115- [ ] No request path uses `KEYS`, unbounded `SMEMBERS`, or large `HGETALL`.
116- [ ] Invalidation is tested alongside the write path.
117- [ ] Redis metrics cover latency, hit rate, memory, evictions, blocked clients, and reconnects.
118- [ ] Local tests cover cache hit, cache miss, Redis down, invalidation, and rate-limit exceeded.
Run npx skillmds@latest add shipshitdev/redis-caching in your terminal (requires Node.js), paste this page's agent-chat prompt into Claude, Cursor, or any MCP-connected agent, or download the SKILL.md file and copy it into your agent's skills directory.
Redis caching, rate limiting, session storage, pub/sub, and production integration patterns for TypeScript, Next.js, NestJS, and Prisma applications. Use when adding cache-aside or write-through caching, rate limiting, session or lock storage, pub/sub fanout, or reviewing Redis key design and TTLs. It is listed under Web & Frontend on SkillMD.
This skill has not completed SkillMD's automated safety review yet. Independent scanners report: SkillSpector: PASS, Skill Scanner: PASS. Capability flags: reads secrets. SkillMD never runs a skill's scripts for you; review the SKILL.md before installing.
This skill is tagged as working with Claude Code, Claude.ai, OpenAI Codex. SKILL.md is an open format, so most agents that read a skills directory can load it too.
Yes. Installing skills from SkillMD is free, and the skill stays under its author's original license.
shipshitdev (@shipshitdev) published this skill. Their other Agent Skills are listed on their SkillMD profile.