How does NestJS caching with Redis work?
In short, it works by putting a shared Redis lookup in front of expensive reads. Nest checks Redis for a computed key before running a handler or service method. It returns the stored value on a hit, and on a miss it runs the real work and stores the result with a TTL. The rest of this section explains the layers that make that happen.
NestJS caching has three layers. At the top, CacheModule gives you Nest-friendly entry points: the CacheInterceptor for caching whole route responses, and an injectable cache instance (via the CACHE_MANAGER token) for caching inside services. Underneath, CacheModule wraps cache-manager, a store-agnostic library that provides get, set and del operations plus TTL handling. At the bottom is the store. By default this is an in-process memory store, which disappears on restart and is private to each Node process. A Redis store adapter replaces it with a cache that every instance shares.
A cached read follows this path:
- A request reaches the interceptor, or a service method calls the cache directly.
- A key is computed and looked up in Redis.
- On a hit, the stored value is returned and the database is skipped.
- On a miss, the handler queries the database, writes the result to Redis with a TTL, and returns it.
The shared store matters once you scale horizontally. With per-process memory, ten instances keep ten separate caches. Each instance has its own cold start, hit rates are lower, and when one instance invalidates a key, the other nine keep serving stale copies. Redis gives you one view of cached data, so a read-heavy endpoint warms once and a single delete invalidates the key everywhere. Backend engineers get simpler correctness reasoning. Platform engineers get load taken off the database that does not depend on instance count.
A caution: store packages, the configuration shape and TTL units (seconds vs. milliseconds) have changed across major versions of cache-manager and its Redis adapters. Check the documentation for the versions you have installed, and treat online examples, including older Nest snippets, as possibly out of date.
HTTP requests (load balanced across instances)
| |
v v
+---------------------------+ +---------------------------+
| Nest instance A | | Nest instances B..N |
| CacheInterceptor (route) | | CacheInterceptor (route) |
| or svc via CACHE_MANAGER | | or svc via CACHE_MANAGER |
| | | | | |
| v | | v |
| CacheModule | | CacheModule |
| | | | | |
| v | | v |
| cache-manager get/set/del | | cache-manager get/set/del |
| | | | | |
| v | | v |
| Redis store adapter | | Redis store adapter |
+------------+--------------+ +------------+--------------+
| 1. get(key) |
v v
+-------------------------------------------+
| Redis: shared cache, one view for all |
+-------------------------------------------+
hit -> return stored value, skip DB
miss -> handler queries DB, set(key, TTL)
|
v
+-------------------------------------------+
| Database (only reached on cache miss) |
+-------------------------------------------+
Each Nest instance routes cached reads through CacheInterceptor or an injected CACHE_MANAGER, then CacheModule, cache-manager and a Redis store adapter, so all instances share one Redis cache and only reach the database on a miss.
Who should use a NestJS Redis cache?
A Redis-backed cache is worth the extra moving part when most of these are true:
- You run more than one instance of the app. This could be several pods, containers or processes behind a load balancer. Per-process memory caches diverge in that setup, and a shared store is the main reason to add Redis.
- Your workload is read-heavy. The same data is requested far more often than it changes, for example catalogues, reference data, configuration, profiles or aggregated dashboards.
- Reads are expensive. The database query, downstream HTTP call or computation behind a response costs noticeably more than a network round trip to Redis.
- You can state a staleness tolerance. For each cached data type, someone can say how long readers may see an old value. Without that answer you cannot set TTLs responsibly.
The people who usually own this are backend engineers writing Nest services, who decide what to cache and how to invalidate it, and platform or SRE engineers, who run Redis, size it, and watch hit rates and database load.
It is a poor fit, or at least premature, in other situations:
- A single instance with cheap queries. The default in-memory store, or no cache at all, avoids running Redis.
- Data that must always be current, such as balances, inventory at checkout or authorization decisions. Here a stale read is a bug, not a trade-off.
- Write-heavy data. Invalidation would remove entries faster than they are reused.
How do you register a global NestJS Redis cache module?
Register the module once, at the root, with CacheModule.registerAsync and isGlobal: true. The async form matters because the Redis store has to be built from configuration that isn't available until the config module has loaded. With a static register call you end up reading process.env at import time, which skips validation and makes per-environment overrides awkward. isGlobal lets any feature module inject the cache without re-importing the module, so every part of the app shares one connection pool and one set of defaults.
In the factory, inject your configuration service and read host, port, password (or a full connection URL), TLS settings and the default TTL from it. Validate these values at boot. A missing password should stop the process rather than produce a client that silently retries an unauthenticated connection. Keep the default TTL short and conservative, and let individual call sites raise it explicitly.
The store factory you pass, and its import path, depend on which cache-manager and Redis adapter versions you have installed. Copy the exact name from the adapter's own README, not from a blog post.
TTL units have also changed between versions. Some versions expect seconds and others milliseconds. To check yours, set a key with a TTL of 60 and inspect it with redis-cli PTTL. A result near 60,000 means seconds were assumed. A result near 60 means milliseconds.
Finally, confirm connectivity at startup. In an onModuleInit hook, write a sentinel key, read it back and fail fast if the round trip errors. Without this check, a misconfigured cache tends to surface only as unexplained latency once the app is under traffic.
import { Inject, Injectable, Module, OnModuleInit } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { CacheModule, CACHE_MANAGER } from '@nestjs/cache-manager';
import { Cache } from 'cache-manager';
// Adapter name and import path vary by version. Copy them from the installed adapter's README.
import { redisStore } from 'cache-manager-redis-yet';
@Injectable()
class CacheHealthCheck implements OnModuleInit {
constructor(@Inject(CACHE_MANAGER) private readonly cache: Cache) {}
// Fail fast at boot instead of discovering a broken cache under traffic.
async onModuleInit() {
const key = 'startup:sentinel';
await this.cache.set(key, 'ok', 60); // then run: redis-cli PTTL startup:sentinel
if ((await this.cache.get(key)) !== 'ok') {
throw new Error('Redis cache round trip failed at startup');
}
}
}
@Module({
imports: [
ConfigModule.forRoot({ isGlobal: true }),
CacheModule.registerAsync({
isGlobal: true, // one shared client and one set of defaults for every feature module
inject: [ConfigService],
useFactory: async (config: ConfigService) => ({
store: await redisStore({
socket: { host: config.getOrThrow<string>('REDIS_HOST'), port: Number(config.getOrThrow('REDIS_PORT')) },
password: config.getOrThrow<string>('REDIS_PASSWORD'), // a missing secret aborts boot
}),
ttl: Number(config.getOrThrow('CACHE_DEFAULT_TTL')), // short default. Check the unit with PTTL.
}),
}),
],
providers: [CacheHealthCheck],
})
export class AppModule {}
Global async CacheModule registration with a Redis store built from validated config, plus an onModuleInit sentinel round trip that fails fast and can be checked with redis-cli PTTL to confirm the TTL unit.
What does the NestJS cache interceptor actually cache, and when is it unsafe?
The built-in CacheInterceptor only caches GET requests. Other methods pass through untouched. The cache key comes from its trackBy() method, which by default returns the request URL, including the query string. You can apply the interceptor to a single route or a whole controller with @UseInterceptors(CacheInterceptor), or to every route by registering it under the APP_INTERCEPTOR token. @CacheTTL() overrides the TTL for one handler, and @CacheKey() replaces the generated key with a fixed one.
The URL-based key causes a data leak when a response depends on who is asking. Take GET /me/orders or GET /dashboard. The URL is the same for every caller, but the body differs per user or tenant. The first authenticated request fills the cache, and every later caller receives that user's data until the TTL expires. The interceptor never sees the Authorization header, so nothing in the default behaviour prevents this.
The fix is to subclass CacheInterceptor and override trackBy() so it prefixes the URL with the tenant ID or user ID from the authenticated request. If that identity is missing, return undefined, which tells the interceptor to skip caching for that request.
When the interceptor fits: public, read-heavy GET endpoints such as catalogues, reference data and feature metadata. On these, a short TTL is an acceptable staleness bound.
When to avoid it:
- Per-user data, unless you add scoped keys as described above.
- Responses that must be invalidated precisely on writes. URL-derived keys are hard to enumerate when you need to delete them.
import { CacheInterceptor, CacheTTL } from '@nestjs/cache-manager';
import { Controller, ExecutionContext, Get, Injectable, UseGuards, UseInterceptors } from '@nestjs/common';
import { JwtAuthGuard } from './auth/jwt-auth.guard'; // your existing auth guard
import { OrdersService } from './orders.service';
@Injectable()
export class ScopedCacheInterceptor extends CacheInterceptor {
protected trackBy(context: ExecutionContext): string | undefined {
// Reuse the default logic: GET-only check, @CacheKey() metadata, URL with query string.
const baseKey = super.trackBy(context);
if (!baseKey) return undefined;
// Guards run before interceptors, so request.user is already populated here.
const request = context.switchToHttp().getRequest();
const user = request.user as { id?: string; tenantId?: string } | undefined;
// No identity means no safe scope: returning undefined skips caching for this request.
if (!user?.id || !user?.tenantId) return undefined;
// Scope the key so two callers hitting the same URL never share an entry.
return `tenant:${user.tenantId}:user:${user.id}:${baseKey}`;
}
}
@Controller('me')
@UseGuards(JwtAuthGuard)
@UseInterceptors(ScopedCacheInterceptor)
export class MeController {
constructor(private readonly orders: OrdersService) {}
@Get('orders')
@CacheTTL(30_000) // milliseconds with cache-manager v5+; keep it short for per-user data
findMyOrders() {
return this.orders.findForCurrentUser();
}
}
A CacheInterceptor subclass that overrides trackBy() to prefix the default URL key with tenant and user IDs, and skips caching when no authenticated identity is present.
When should you use cache-manager directly instead of the interceptor?
Reach for the injected cache manager when the thing worth caching is a domain object rather than an HTTP response. Suppose ProductService.findById feeds the product page, the cart and an admin endpoint. If you cache it once in the service using cache-aside, all three callers share the same entry. The flow is simple: call get on a key such as product:42, return the value on a hit, and on a miss load from the database and set it with a TTL. A write path calls del on that exact key, and because your code built the key, it knows which key to delete.
The catch is serialization. A Redis store sends values through JSON, so a Date comes back as an ISO string and a class instance comes back as a plain object without its methods or prototype. Code that calls product.createdAt.getTime() or product.isAvailable() will work against the database and fail on a cache hit. To avoid this, rehydrate deliberately: parse dates and construct the class (or map to a DTO) in one helper that every hit goes through, so cached and uncached reads return the same shape.
| Interceptor | Service-level cache-manager | In-process memory | |
|---|---|---|---|
| Flexibility | Route-level only | Any method, any key | Any method, any key |
| Invalidation granularity | Coarse, URL-derived | Precise, per entity | Precise, but local only |
| Consistency across instances | Shared | Shared | Each instance diverges |
| Latency | Network round trip | Network round trip | Fastest, no network |
| Maintenance cost | Lowest | Moderate (keys, rehydration) | Low, until you scale out |
import { Inject, Injectable } from '@nestjs/common';
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { Cache } from 'cache-manager';
import { Product } from './product.entity'; // class with methods, e.g. isAvailable()
import { ProductRepository } from './product.repository';
const PRODUCT_TTL_MS = 5 * 60 * 1000; // ttl is in milliseconds in cache-manager v5+
@Injectable()
export class ProductService {
constructor(
@Inject(CACHE_MANAGER) private readonly cache: Cache,
private readonly repo: ProductRepository,
) {}
private key(id: number): string {
return `product:${id}`; // one key builder, shared by reads and invalidation
}
async findById(id: number): Promise<Product | null> {
const cached = await this.cache.get<Record<string, any>>(this.key(id));
if (cached) return this.rehydrate(cached); // every hit goes through rehydrate
const product = await this.repo.findById(id); // miss: load from the database
if (product) await this.cache.set(this.key(id), product, PRODUCT_TTL_MS);
return product;
}
async update(id: number, changes: Partial<Product>): Promise<void> {
await this.repo.update(id, changes);
await this.cache.del(this.key(id)); // precise invalidation: we built this key
}
// JSON round trip turns Dates into strings and drops the prototype; restore both.
private rehydrate(raw: Record<string, any>): Product {
return Object.assign(new Product(), raw, { createdAt: new Date(raw.createdAt) });
}
}
A NestJS service applies cache-aside with the injected cache manager's get, set and del. Every cache hit passes through one rehydrate helper that restores Date fields and the Product prototype, so a cached read returns the same shape as a database read.
How do you choose TTLs and design cache keys for targeted invalidation?
Start from two questions per data type: how often does it change, and how long can a reader tolerate seeing the old value? The TTL is the ceiling on staleness if invalidation fails, so set it from the tolerance, not from the hit rate you want. Apply TTLs per route with the TTL decorator, or per key when calling set on the cache directly, rather than relying on one global default. Confirm the unit for your installed versions: the cache-manager ecosystem has used both seconds and milliseconds across releases, and a unit mismatch silently produces caching for 1,000 times longer or shorter than you intended.
| Data type | Illustrative TTL | Reasoning |
|---|---|---|
| Country list, static config | Hours | Changes rarely; stale reads are harmless |
| Product catalog entry | 5–15 minutes | Edited occasionally; explicit invalidation covers edits |
| User profile | 1–5 minutes | User expects to see their own edits quickly |
| Inventory count, pricing | Seconds, or not cached | Stale values cause real errors |
These are illustrative choices, not measured values.
Name keys service:entity:id:version, for example catalog:product:42:v3. On a write you know exactly which key to delete. In redis-cli the key shows who owns it and what it holds. Bumping the version segment when the payload shape changes orphans old entries, which then expire on their own instead of being deserialized into the wrong shape.
Do not plan to find keys by pattern at request time. KEYS walks the entire keyspace in one call and blocks Redis while it runs. SCAN avoids blocking because it iterates in small batches, but a full pass takes many round trips. It is also not atomic: keys written during the scan may be missed. Build the key from the entity you just changed instead of searching for it.
How do you invalidate a NestJS Redis cache on writes without stale reads?
Delete only after the transaction commits. If you delete before commit, a concurrent reader can miss, load the still-old row, and cache it again. If the transaction then rolls back, you have also paid for a pointless miss.
Delete-after-commit still has a race. A reader loads the old row just before commit. The writer commits and deletes the key. Then the slow reader writes its stale value back, and that value lives until its TTL expires. You can narrow this window but not close it:
- Short TTL backstop: limits how long a stale value can survive.
- Delayed second delete: a repeat delete a few hundred milliseconds later catches most late writers.
- Versioned keys: store a per-entity or per-namespace counter, embed it in the key, and increment it on write. Old entries become unreachable, so one increment replaces deleting every list page. The cost is an extra read on every lookup, and orphaned keys stay in memory until their TTL expires. Read replicas with replication lag can still feed stale rows into a fresh version.
When several services or instances write the same data, publish an event after commit, ideally through an outbox. A consumer deletes the affected keys. Delivery is usually at-least-once, so deletes must be idempotent, which they naturally are.
The larger cost is coupling. Every write path must know every key derived from the data. A bulk SQL update, a migration, or a new cached projection can skip the delete. The resulting staleness depends on timing and often expires before anyone investigates. To reduce this, have readers and writers use the same key builders from a single shared module.
| Strategy | Stale window | Cost | Fits |
|---|---|---|---|
| Delete after commit | Race until TTL | Low | Single-entity keys |
| Delayed second delete | Mostly closed | Timer/queue | Hot, frequently read keys |
| Versioned keys | Narrow | Extra read, orphaned keys | Lists, namespaces |
| Event-driven | Event lag | Broker, outbox | Multi-service writers |
What happens when Redis fails or a hot key expires?
Hot keys and stampedes
When a heavily read key expires, every concurrent request misses at once and runs the same database query. The cost of that burst depends on how expensive the query is, not on Redis. Three mitigations, from cheapest to most involved:
- TTL jitter: add a small random offset to each TTL so keys written together don't expire together.
- Request coalescing: within one instance, keep a map of in-flight loader promises keyed by cache key, so concurrent misses await the same promise. This does nothing across replicas.
- Short-lived lock: one caller sets a lock key with
NXand a TTL of a few seconds, then recomputes. The others briefly serve the stale value or retry.
If a miss costs a few milliseconds, skip the lock. It adds failure modes, such as a lock that is never released or a caller that waits too long, and the problem it solves may not exist.
Redis failures
Decide per call site whether a Redis error falls back to the database or fails the request. For read-through caching, falling back is usually correct. Set explicit connect and command timeouts on the client. Without them, a hung Redis turns every request into a hung request. Catch cache errors in your wrapper so an outage costs latency, not availability.
Testing and observability
Unit-test cache logic against an in-memory store. Run integration tests against a real Redis container to catch serialization and TTL behaviour. Emit hit/miss counters per key prefix and track key counts. When a stale-data bug comes in, those numbers tell you quickly whether the cache is involved, which keeps caching cheap to run over time.
How can a NestJS Redis cache save engineering time?
The main saving is that you stop solving caching problems ad hoc. Engineers often add one-off caching in individual handlers using module-level maps, hand-rolled Redis calls or memoization helpers. A single, global CacheModule backed by Redis replaces those with one integration that every team uses the same way. Here is where the time comes back:
- Less bespoke plumbing.
CacheInterceptorplus@CacheTTL()caches a publicGETroute with a decorator instead of new code in the handler. For service-level caching, the injected cache manager gives every module the sameget/set/delAPI, so nobody writes their own Redis client wrapper, connection handling or serialization. - Fewer scale-out bugs to chase. Per-process caches behave correctly on a laptop and then diverge across replicas in production, which produces stale-data reports that are hard to reproduce. A shared store removes that class of bug.
- Cheaper performance work. When an endpoint is slow because of a repeated expensive read, caching it is often a small, reviewable change: a decorator, or a cache-aside wrapper around one service method. The alternatives, such as query rewrites, denormalization or adding read replicas, take more effort. Caching does not replace fixing a bad query, but it is a fast option when the data tolerates staleness.
- Faster debugging. Consistent
service:entity:id:versionkeys, shared key builders and per-prefix hit/miss metrics let an engineer check inredis-clior a dashboard whether the cache explains a bug. Without them, they have to reason about scattered caching code. - Safer defaults encoded once. The startup sentinel check, validated config, explicit timeouts, the scoped
trackBy()interceptor and the rehydration helper are each written once and reused. Every new endpoint inherits them instead of each team rediscovering the same failure modes.
The time cost moves to the places this article covers: choosing TTLs, keeping invalidation in step with every write path, and maintaining rehydration helpers. Budget for those explicitly. A cache that saves query time but generates recurring stale-data investigations has not saved engineering time.
How OneEnv can help
Disclosure: OneEnv is the product behind this blog.
OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.
Applied to nestjs redis cache, this is where it helps:
Saves time
- Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
- One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
- Changing a shared variable is one edit and one review instead of editing every service's
.envby hand.
Saves cost
- Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
- Less duplicated configuration to maintain: one shared definition inherited by many services.
- A wrong or stale value is caught at review time by the services it affects, not by a failed deploy.
- OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.
These are qualitative benefits, not measured results — how much you save depends on how many services share the value.
Want to try it? Start at oneenv.io.