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-caching3description: 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.4---56# Redis Caching
78Implement Redis as a production support layer, not as a second database.
910## When to Use
1112- Add cache-aside or write-through caching around Prisma or API reads.
13- Protect expensive routes with rate limiting.
14- Store short-lived sessions, verification state, locks, or counters.
15- Add pub/sub or stream-backed event fanout.
16- Review Redis key design, TTLs, invalidation, or connection handling.
1718For BullMQ job queue architecture, use `nestjs-queue-architect` instead of duplicating queue patterns here.
1920## First Decisions
21221. Choose the runtime.
23 - Long-lived Node.js or NestJS process: use `ioredis`.
24 - Serverless or edge runtime: prefer the Upstash Redis SDK or REST API.
25 - Background jobs: use BullMQ guidance from `nestjs-queue-architect`.
262. Define the cache contract before coding.
27 - Source of truth: Prisma/database, upstream API, computed result, or session authority.
28 - Freshness: hard TTL, stale-while-revalidate, explicit invalidation, or write-through.
29 - Failure mode: fail open for cache reads, fail closed for auth/session/rate-limit writes.
303. Design keys and invalidation together.
31 - Namespace every key: `app:env:entity:id:variant`.
32 - Keep keys stable and inspectable.
33 - Add TTLs to every cache, lock, session, and rate-limit key.
3435## Installation
3637```bash
38bun add ioredis
3940# Optional serverless Redis
41bun add @upstash/redis @upstash/ratelimit
42```
4344Use one Redis client per process (a module-level singleton guarded against
45hot-reload duplication). Do not create a new TCP client per request. Wire
46`error`, `connect`, and `reconnecting` events into the app logger or APM. Avoid
47logging credentials from connection URLs.
4849See `references/examples.md` (§ Redis Client Singleton) for the full setup.
5051## Cache-Aside With Prisma
5253Use cache-aside for reads where brief staleness is acceptable: check the
54cache, on miss call the loader, write back with a jittered TTL (`baseTtl +
55random(0, jitter)`) so hot keys don't all expire in the same instant.
5657See `references/examples.md` (§ Cache-Aside With Prisma) for the `getCached`
58helper and a Prisma-backed usage example.
5960## Stampede Protection
6162Protect hot keys with a short `SET key val EX 10 NX` lock. Only the holder
63(matched by a random token) releases it; losers wait briefly and re-check the
64cache before falling through to a direct load.
6566See `references/examples.md` (§ Stampede Protection) for the full
67lock-and-release implementation.
6869## Invalidation
7071Prefer direct invalidation for known keys. Use tag sets (a Redis set per tag,
72mapping to the keys written under it) when one mutation affects many keys —
73write through a pipeline, invalidate by reading the tag's key set and
74`UNLINK`-ing them. Use `SCAN` instead of `KEYS` for emergency pattern cleanup.
75Do not put pattern invalidation on hot request paths.
7677See `references/examples.md` (§ Tag-Based Invalidation) for the
78`cacheSetWithTags` / `invalidateTag` implementation.
7980## Rate Limiting
8182Use sorted sets for sliding-window limits when exactness matters: trim
83expired entries, add the current request, count members, and set the key's
84expiry — all in one `MULTI`. For public traffic, set response headers:
85`X-RateLimit-Limit`, `X-RateLimit-Remaining`, and `Retry-After`.
8687See `references/examples.md` (§ Sliding-Window Rate Limiting) for the full
88`slidingWindowRateLimit` implementation.
8990## Sessions And Verification State
9192- Store opaque session IDs or token hashes, not raw JWTs or long-lived secrets.
93- Set TTL on every session key.
94- Regenerate sessions after privilege changes.
95- Delete sessions on logout, account deletion, and password reset.
96- Treat Redis write failure as auth failure for login, logout, MFA, and password reset flows.
9798See `references/examples.md` (§ Session Storage) for a `createSession` example.
99100## Pub/Sub And Streams
101102- Use pub/sub for ephemeral fanout where missed messages are acceptable.
103- Use streams when consumers need replay, backpressure, or durable delivery.
104- Keep payloads small; store large objects elsewhere and publish IDs.
105- Add consumer observability: lag, dead letters, retries, and handler errors.
106107## Production Checklist
108109- [ ] All cache, lock, session, and rate-limit keys have TTLs.
110- [ ] Cache reads fail open where possible; auth and rate-limit writes fail closed.
111- [ ] Hot keys use TTL jitter or stampede protection.
112- [ ] No request path uses `KEYS`, unbounded `SMEMBERS`, or large `HGETALL`.
113- [ ] Invalidation is tested alongside the write path.
114- [ ] Redis metrics cover latency, hit rate, memory, evictions, blocked clients, and reconnects.
115- [ ] Local tests cover cache hit, cache miss, Redis down, invalidation, and rate-limit exceeded.
Run npx skillmds 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. 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.