Implementing Redis Caching to Reduce API Response Times
Cache-aside with Redis, done carefully: keys, TTLs, invalidation and protection against stampedes.
- redis
- caching
- node.js
- performance
On this page ยท 15 sections
A cache is the cheapest performance win in most APIs and the easiest way to serve wrong data. Redis makes the first part simple: it keeps data in memory and answers in well under a millisecond. The second part is about design: what to cache, for how long, how to invalidate it, and what happens when it fails. This guide implements the cache-aside pattern in Node.js with TypeScript and covers the details that decide whether a cache helps or hurts.
The problem
Some endpoints do the same expensive work for every request: aggregate queries, joins across several tables, calls to a slow third-party API. Making the database faster has limits. Not doing the work at all is better, and a cache lets you reuse a recent result instead.
The cache-aside pattern
Read path
- 1Request arrives
build the cache key
- 2Check Redis
hit: return the cached value
- 3Miss: query the database
the slow path
- 4Store in Redis with a TTL
then return the result
Write path
- 1Write to the database
the source of truth
- 2Delete or update the cached key
so readers do not see old data
The database stays the source of truth. The cache only ever holds a copy that is allowed to be slightly old.
Setup
npm install ioredisdocker run -d --name redis -p 6379:6379 redis:7// src/cache/redis.tsimport Redis from "ioredis";export const redis = new Redis(process.env.REDIS_URL ?? "redis://localhost:6379", { maxRetriesPerRequest: 1, // fail fast instead of queueing forever enableOfflineQueue: false, // do not buffer commands while disconnected connectTimeout: 2000,});redis.on("error", (err) => { console.error("[redis] error", err.message);});maxRetriesPerRequest and enableOfflineQueue: false matter: when Redis is unreachable, commands should fail quickly so your fallback to the database runs instead of requests hanging.
Design keys carefully
A key naming convention prevents collisions and makes invalidation possible:
app:v1:product:123app:v1:user:42:profileapp:v1:products:list:category=books:page=2- A prefix (
app:) lets several apps share an instance. - A version (
v1) lets you invalidate everything by bumping it when the cached shape changes. - Every input that changes the result (user id, filters, page, locale) must be in the key. If it is not, one user can receive another user's cached response.
A reusable getOrSet helper
// src/cache/cache.tsimport { redis } from "./redis";interface Options { ttlSeconds: number; /** Spread expirations so many keys do not expire together. */ jitterRatio?: number;}export async function getOrSet<T>( key: string, loader: () => Promise<T>, { ttlSeconds, jitterRatio = 0.1 }: Options,): Promise<T> { // 1. Try the cache; a Redis failure must not break the request. try { const cached = await redis.get(key); if (cached !== null) return JSON.parse(cached) as T; } catch (err) { console.error("[cache] read failed", key, err); } // 2. Miss: load from the source of truth. const value = await loader(); // 3. Store with TTL + jitter. Never let a write failure fail the request. try { const jitter = Math.floor(ttlSeconds * jitterRatio * Math.random()); await redis.set(key, JSON.stringify(value), "EX", ttlSeconds + jitter); } catch (err) { console.error("[cache] write failed", key, err); } return value;}export async function invalidate(...keys: string[]) { if (keys.length === 0) return; try { await redis.del(...keys); } catch (err) { console.error("[cache] invalidate failed", keys, err); }}Using it in a service:
// src/products/product.service.tsimport { getOrSet, invalidate } from "../cache/cache";export class ProductService { constructor(private repo: ProductRepository) {} getProduct(id: string) { return getOrSet( `app:v1:product:${id}`, () => this.repo.findById(id), { ttlSeconds: 300 }, ); } async updateProduct(id: string, input: UpdateProductInput) { const updated = await this.repo.update(id, input); await invalidate(`app:v1:product:${id}`); // keep readers from seeing old data return updated; }}JSON serialization has limits: Date objects become strings, and undefined, Map and class instances do not round-trip. Convert on the way out, or keep cached values as plain data.
Cache negative results
If a lookup for a missing record is expensive, caching "not found" for a short time protects the database from repeated misses (including malicious ones). Store a sentinel with a short TTL, such as 30 seconds, and make sure creating the record invalidates it.
Prevent cache stampedes
When a popular key expires, hundreds of concurrent requests can miss at once and all hit the database. Use a short lock so one request recomputes while others wait or serve stale data.
// src/cache/lock.tsimport { randomUUID } from "node:crypto";import { redis } from "./redis";const releaseScript = `if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("del", KEYS[1])endreturn 0`;export async function withLock<T>( key: string, ttlMs: number, fn: () => Promise<T>, onBusy: () => Promise<T>,): Promise<T> { const token = randomUUID(); const acquired = await redis.set(`lock:${key}`, token, "PX", ttlMs, "NX"); if (acquired !== "OK") return onBusy(); try { return await fn(); } finally { // Only release the lock if we still own it. await redis.eval(releaseScript, 1, `lock:${key}`, token); }}SET ... NX PX creates the lock only if it does not exist and gives it an expiry, so a crashed process cannot hold it forever. The Lua script releases the lock only when the stored token matches yours, so one request cannot delete a lock another request now holds. For onBusy, either wait briefly and re-read the cache, or return the previous value if you stored one with a longer "stale" TTL.
Within a single Node process you can also coalesce requests: keep a Map<string, Promise<T>> of in-flight loads and let concurrent callers await the same promise.
Invalidation strategies
| Strategy | How | Trade-off |
|---|---|---|
| TTL only | Let entries expire | Simplest; data may be stale up to the TTL |
| Delete on write | Remove keys when data changes | Fresh data; must know every affected key |
| Write-through | Update cache and database together | Always warm; more write complexity |
| Versioned keys | Include a version in the key | Easy mass invalidation; old keys expire on their own |
When invalidation logic gets complicated, a short TTL is often safer than a clever scheme that has a bug.
Security considerations
- Never cache responses that contain secrets or another user's private data under a shared key.
- Do not store session tokens or passwords in cache unless the cache is secured and the data is encrypted or hashed appropriately.
- Require authentication and TLS for Redis, bind it to a private network, and never expose port 6379 to the internet.
- Treat cached values as untrusted input if other systems can write to the same Redis.
Performance considerations
- Keep values small. Large values increase network time and memory.
- Use pipelines or
MGETto fetch many keys in one round trip. - Set a
maxmemorylimit and an eviction policy such asallkeys-lruso Redis evicts old entries instead of running out of memory. - Avoid the
KEYScommand in production because it blocks the server; useSCAN. - Watch latency: a slow Redis call that happens on every request can negate the benefit of caching.
Measure the hit ratio
redis-cli INFO stats | grep -E "keyspace_(hits|misses)"Hit ratio is hits / (hits + misses). Track it over time next to your API latency and database load. A low ratio means keys are too specific, TTLs too short, or the data is not read repeatedly, and the cache may not be worth keeping.
Testing
- Unit test
getOrSetwith a fake loader: the second call must not invoke the loader, and a Redis error must still return the loader's value. - Integration test against a real Redis (for example via Docker in CI) to cover serialization and TTLs.
- Test invalidation: update a record and assert the next read returns the new value.
- Test the failure mode: stop Redis and confirm the endpoint still works, only slower.
Common mistakes
- Leaving user-specific inputs out of the cache key.
- Caching without a TTL, so stale data lives forever.
- Treating Redis as a database and losing data when it restarts (persistence is optional and a cache can be flushed).
- Letting Redis errors become 500s.
- Invalidating on write in some code paths but not others.
- Caching error responses.
Best practices
- Cache read-heavy, expensive, tolerance-for-staleness data first.
- Always set a TTL, with jitter.
- Fail open: if Redis is down, serve from the database.
- Namespace and version keys.
- Measure hit ratio and latency before and after.
Conclusion
A good cache is small and boring: a key convention, a TTL, a fallback and a way to invalidate. Start with one expensive read endpoint, measure its latency and hit ratio, and expand only where the numbers justify it. The goal is not to cache everything. It is to make the slowest, most repeated work happen once.
Frequently asked questions
+What is the cache-aside pattern?
The application checks the cache first. On a miss it loads from the database, stores the result in the cache with a TTL, and returns it. Writes go to the database and invalidate or update the cached entry.
+How do I choose a TTL?
Base it on how stale the data may be and how expensive it is to recompute. Short TTLs (seconds to minutes) suit fast-changing data; longer TTLs suit reference data. Add a little random jitter so many keys do not expire at the same moment.
+What is a cache stampede and how do I prevent it?
When a hot key expires, many concurrent requests miss at once and all hit the database. Prevent it with a short lock so only one request recomputes, serving stale data briefly, or coalescing in-process requests for the same key.
+Should the app fail if Redis is down?
Usually not. Treat the cache as an optimization: catch Redis errors, log them, and fall back to the database, ideally with a timeout so a slow Redis does not slow every request.
+How do I invalidate cached data after a write?
Delete or overwrite the affected keys in the same code path that performs the write, and design key names so related entries are easy to find. When invalidation is hard, prefer a short TTL over complex logic.
+What should I not cache?
Data that must always be exact (balances, inventory at checkout), highly personalized responses unless the user is part of the key, and anything large that is rarely read again.
+How do I know the cache is working?
Track the hit ratio (keyspace_hits and keyspace_misses from INFO stats), latency with and without the cache, and database load. A cache with a low hit ratio adds complexity without benefit.