Skip to main content
GitHub Repository

You can find the project source code on GitHub.

NestJS caching (@nestjs/cache-manager) keeps entries in memory by default. That works for one process, but as soon as your API runs on more than one instance (Docker containers behind a load balancer, several replicas on Railway, Render, Fly.io or Kubernetes) every instance has its own cold cache. A value cached by one instance is computed again by the next, and deleting a key on one instance leaves stale copies on the others. The cache is also lost on every restart or deploy.

@nestjs/cache-manager uses cache-manager, which stores data through Keyv adapters. Point it at an Upstash Redis database with the official @keyv/redis adapter and every instance reads and writes the same cache.

This tutorial uses:

PackageVersion
@nestjs/core12
@nestjs/cache-manager12
cache-manager7
keyv / @keyv/redis6
Note

@keyv/redis 6 requires Node.js 22.19 or newer. The examples use the ES module project that nest new generates in NestJS 12, so local imports end in .js. In a CommonJS project, drop the .js suffix.

Database Setup#

Create a Redis database in the Upstash Console or with the Upstash CLI. On the database page, open Connect, choose the TCP tab and copy the Redis URL. It starts with rediss:// because Upstash requires TLS. Upstash Redis also has a REST API over HTTP; see Using the REST API instead of TCP below. Add the URL to a .env file:

.env

Project Setup#

Create a Nest app, or use an existing one:

Install the cache module, cache-manager, Keyv and the Redis adapter:

Register the cache#

Register CacheModule once in your root module. isGlobal: true makes CACHE_MANAGER and CacheInterceptor available in every module without importing CacheModule again.

src/app.module.ts

A few things to know about this configuration:

  • TTLs are in milliseconds. Since cache-manager v6, every TTL (the module ttl, @CacheTTL() and cache.set(key, value, ttl)) is in milliseconds, not seconds. 60_000 is one minute.
  • namespace prefixes every key, so a key product:42 is stored as my-api::product:42. Use a different namespace per app or environment if they share a database.
  • Attach an error listener. Without it, a Redis connection error is an unhandled error event.
Warning

If Redis can’t be reached, cache calls wait for the client to reconnect instead of falling back to your handler, so requests stall until the connection comes back. Keep the database in the same region as your API, and treat the cache as part of your request path when you set timeouts and health checks.

Cache a route with CacheInterceptor#

CacheInterceptor caches the response of a route handler. @CacheKey() sets the Redis key (by default the key is the request URL, including the query string) and @CacheTTL() overrides the default TTL for that route.

src/products/products.controller.ts
Warning

CacheInterceptor only caches GET requests, and its key does not include the user. Do not put it on routes whose response depends on who is logged in, unless you build a per-user key with @CacheKey() or a custom trackBy().

You can also apply the interceptor to a whole controller with @UseInterceptors(CacheInterceptor) on the class, or to every route by providing it as APP_INTERCEPTOR.

Cache values manually with CACHE_MANAGER#

For more control, inject the cache manager and use get, set and del directly. This is the cache-aside pattern: read from the cache, fall back to the slow source on a miss, store the result, and delete the key when the data changes.

src/products/products.service.ts

update() also deletes products:all, the key the interceptor uses for GET /products, so the list is refreshed on the next request instead of after its TTL. Because the cache lives in Redis, the delete reaches every instance.

Register the controller and service in a module:

src/products/products.module.ts

Verify across two instances#

Build the app and start two instances on different ports. Node.js loads the .env file with --env-file:

Request the same product from both. The first request takes about a second (the simulated database query). The second instance answers from Redis with the same loadedAt and the process ID of the first instance in loadedBy:

Look at the key in Redis, with redis-cli or the Data Browser in the Upstash Console. The key carries the namespace, and PTTL shows the remaining TTL in milliseconds:

Update the product on the first instance. The second instance misses the cache and loads the product again:

The interceptor-cached list behaves the same way. GET /products on one instance is served from the cache on the other, and after the 10 second @CacheTTL the key expires in Redis and the next request loads it again.

Running in Docker#

Nothing changes for containers: pass REDIS_URL as an environment variable (for example with docker run -e REDIS_URL=... or your platform’s secrets) and start the app with node dist/main. Use a Node.js 22 base image such as node:22-slim to meet the @keyv/redis Node.js requirement. Every replica connects to the same database, so scaling out does not start with a cold cache.

Using the REST API instead of TCP#

@keyv/redis keeps a TCP connection to Upstash, which is the right choice for long-running Nest servers. If your environment cannot open outbound TCP connections, the community keyv-upstash adapter talks to Upstash over HTTP with @upstash/redis. It is not maintained by Upstash. Pass it as a Keyv store:

Cost#

Each cache read, write and delete is one Redis command, so a cache hit through CacheInterceptor or cache.get() costs one command and a miss costs two (a GET and a SET). CacheInterceptor never caches POST, PUT, PATCH or DELETE requests, so only reads add cache traffic. See Pricing to estimate the cost for your traffic.