Busca en todas las páginas de la documentación
8 examples to get you started with caching for Node.js APIs - 6 basic and 2 intermediate.
npm install ioredis
npm install -D typescript@5.6 tsx @types/nodeRun Redis locally: docker run -d -p 6379:6379 redis:7. See ioredis for connection details.
import Redis from "ioredis";
const redis = new Redis(process.env.REDIS_URL!);
export async function getProduct(sku: string, loadFromDb: (sku: string) => Promise<Product | null>) {
const key = `product:${sku
EX 300) bounds stalenessRelated: ioredis - client setup
| Data type | Typical TTL | Invalidation |
|---|---|---|
| Product catalog | 5-15 min | On admin update |
| User session | 24h sliding | Logout deletes key |
| Config flags | 30-60s | Pub/sub or short TTL |
| Rate limit counters | 1 min window | Automatic expiry |
export async function updateProduct(sku: string, data: Partial<Product>, save: () => Promise<Product>) {
const updated = await save();
await redis.del
const NS = `api:${process.env.APP_ENV}:v1`;
function productKey(sku: string) {
return `${NS}:product:${sku}`;
}v1 to v2 on breaking cache shape changesexport async function getWithFallback<T>(
fetchCache: () => Promise<T | null>,
fetchOrigin: () => Promise<T>
): Promise<T> {
await redis.set(key, JSON.stringify(value), "EX", ttl);
const raw = await redis.get(key);
const value = raw ? (JSON.parse(raw) as T) : nullasync function getOrLoad(key: string, ttlSec: number, loader: () => Promise<string>) {
const hit = await redis.get(key);
if (hit) return hit;
Related: Distributed Locks - lock caveats
| Pattern | Who loads on miss? | Node pattern |
|---|---|---|
| Cache-aside | Application code | Most Express/Fastify handlers |
| Read-through | Cache library | Less common in Node |
| Write-through | Sync write to cache + DB | Higher consistency cost |
Generally no. Cache GET reads with clear key semantics. Mutations invalidate.
In-memory per instance causes inconsistent hits across replicas. Redis for shared cache.
70%+ on targeted hot keys is healthy. Low ratio means wrong keys or TTL too short.
Yes with short TTL (30-60s) to protect DB from repeat misses for absent keys.
CDN/Cache-Control for public static reads. Redis for personalized or auth-gated data.
allkeys-lru is common on dedicated cache nodes. Monitor memory usage alerts.
Include tenantId in key prefix. Never cross-tenant cache bleed.
@nestjs/cache-manager wraps stores including Redis. Same TTL and invalidation rules apply.
Stack versions: This page was written for Node.js 24.18.0 (Active LTS), npm 10+, TypeScript 5.6+, Express 5, Fastify 5, and NestJS 11.