> ## Documentation index
> Fetch the complete documentation index at: https://upstash.com/docs/llms.txt
> Ask it with GET https://upstash.com/docs/ask?q=<keywords or question>. Short keywords rank best.
> Use these to discover all available pages before exploring further.
> Feature requests: https://upstash.com/docs/common/help/feature-requests.md lists what users asked for and how to vote for a request or add one.
> Page rating: `GET https://upstash.com/docs/feedback?path=/docs/redis/tutorials/nestjs_caching&helpful={true|false}&comment={comment}` records whether this page helped. The `comment` (URL-encoded, at most 500 characters) says what helped, or what was missing or wrong; a `helpful=false` rating needs it. It is anonymous and needs no key. Comments hold no code, secrets or personal data.

# Caching in NestJS with Upstash Redis

> Share the NestJS cache (CacheModule, CacheInterceptor, CACHE_MANAGER) across every instance of your API by using Upstash Redis as the cache-manager store.

<Card title="GitHub Repository" icon="github" href="https://github.com/upstash/redis-js/tree/main/examples/nestjs-cache" horizontal>
  You can find the project source code on GitHub.
</Card>

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](https://github.com/jaredwray/cacheable/tree/main/packages/cache-manager),
which stores data through [Keyv](https://keyv.org) 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:

| Package | Version |
| --- | --- |
| `@nestjs/core` | 12 |
| `@nestjs/cache-manager` | 12 |
| `cache-manager` | 7 |
| `keyv` / `@keyv/redis` | 6 |

<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.
</Note>

## Database Setup

Create a Redis database in the [Upstash Console](https://console.upstash.com/redis)
or with the [Upstash CLI](https://github.com/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](#using-the-rest-api-instead-of-tcp)
below. Add the URL to a `.env` file:

```shell .env
REDIS_URL="rediss://default:<YOUR_PASSWORD>@<YOUR_ENDPOINT>:6379"
```

## Project Setup

Create a Nest app, or use an existing one:

```shell
npx @nestjs/cli new my-api
cd my-api
```

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

```shell
npm install @nestjs/cache-manager cache-manager keyv @keyv/redis
```

## 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.

```ts src/app.module.ts
import { Module } from '@nestjs/common';
import { CacheModule } from '@nestjs/cache-manager';
import { createKeyv } from '@keyv/redis';
import { ProductsModule } from './products/products.module.js';

@Module({
  imports: [
    CacheModule.registerAsync({
      isGlobal: true,
      useFactory: () => {
        const store = createKeyv(process.env.REDIS_URL, {
          namespace: 'my-api',
        });
        store.on('error', (err) => console.error('Cache error:', err));

        return {
          stores: [store],
          ttl: 60_000, // default TTL in milliseconds
        };
      },
    }),
    ProductsModule,
  ],
})
export class AppModule {}
```

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.
</Warning>

## 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.

```ts src/products/products.controller.ts
import {
  Body,
  Controller,
  Get,
  Param,
  Patch,
  UseInterceptors,
} from '@nestjs/common';
import { CacheInterceptor, CacheKey, CacheTTL } from '@nestjs/cache-manager';
import { ProductsService, type Product } from './products.service.js';

@Controller('products')
export class ProductsController {
  constructor(private readonly products: ProductsService) {}

  @Get()
  @UseInterceptors(CacheInterceptor)
  @CacheKey('products:all')
  @CacheTTL(10_000) // 10 seconds
  findAll() {
    return this.products.findAll();
  }

  @Get(':id')
  findOne(@Param('id') id: string) {
    return this.products.findOne(id);
  }

  @Patch(':id')
  update(@Param('id') id: string, @Body() changes: Partial<Product>) {
    return this.products.update(id, changes);
  }
}
```

<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()`.
</Warning>

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.

```ts src/products/products.service.ts
import { Inject, Injectable } from '@nestjs/common';
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import type { Cache } from 'cache-manager';

export interface Product {
  id: string;
  name: string;
  price: number;
  loadedAt: string;
  loadedBy: number;
}

@Injectable()
export class ProductsService {
  constructor(@Inject(CACHE_MANAGER) private readonly cache: Cache) {}

  async findOne(id: string): Promise<Product> {
    const key = `product:${id}`;

    const cached = await this.cache.get<Product>(key);
    if (cached) return cached;

    const product = await this.loadFromDatabase(id);
    await this.cache.set(key, product, 5 * 60_000); // 5 minutes
    return product;
  }

  async update(id: string, changes: Partial<Product>): Promise<void> {
    // Write `changes` to your database here, then drop the cached copies
    await this.cache.del(`product:${id}`);
    await this.cache.del('products:all');
  }

  async findAll(): Promise<Product[]> {
    return Promise.all(['1', '2', '3'].map((id) => this.loadFromDatabase(id)));
  }

  // Stand-in for a slow database query
  private async loadFromDatabase(id: string): Promise<Product> {
    await new Promise((resolve) => setTimeout(resolve, 1000));
    return {
      id,
      name: `Product ${id}`,
      price: 10 * Number(id),
      loadedAt: new Date().toISOString(),
      loadedBy: process.pid,
    };
  }
}
```

`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:

```ts src/products/products.module.ts
import { Module } from '@nestjs/common';
import { ProductsController } from './products.controller.js';
import { ProductsService } from './products.service.js';

@Module({
  controllers: [ProductsController],
  providers: [ProductsService],
})
export class ProductsModule {}
```

## Verify across two instances

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

```shell
npm run build
PORT=3001 node --env-file=.env dist/main &
PORT=3002 node --env-file=.env dist/main &
```

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`:

```shell
curl localhost:3001/products/42
# {"id":"42","name":"Product 42","price":420,"loadedAt":"2026-11-18T12:46:54.257Z","loadedBy":60570}

curl localhost:3002/products/42
# {"id":"42","name":"Product 42","price":420,"loadedAt":"2026-11-18T12:46:54.257Z","loadedBy":60570}
```

Look at the key in Redis, with `redis-cli` or the Data Browser in the
[Upstash Console](https://console.upstash.com/redis). The key carries the
namespace, and `PTTL` shows the remaining TTL in milliseconds:

```shell
redis-cli --tls -u "$REDIS_URL" --scan --pattern 'my-api::*'
# my-api::product:42

redis-cli --tls -u "$REDIS_URL" PTTL my-api::product:42
# 297573
```

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

```shell
curl -X PATCH localhost:3001/products/42 \
  -H "Content-Type: application/json" \
  -d '{"price":99}'

curl localhost:3002/products/42
# {"id":"42","name":"Product 42","price":420,"loadedAt":"2026-11-18T12:46:58.057Z","loadedBy":60572}
```

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`](https://www.npmjs.com/package/keyv-upstash)
adapter talks to Upstash over HTTP with [`@upstash/redis`](/redis/sdks/ts/overview).
It is not maintained by Upstash. Pass it as a Keyv store:

```ts
import { Keyv } from 'keyv';
import { KeyvUpstash } from 'keyv-upstash';

const store = new Keyv({
  store: new KeyvUpstash({
    url: process.env.UPSTASH_REDIS_REST_URL,
    token: process.env.UPSTASH_REDIS_REST_TOKEN,
  }),
  namespace: 'my-api',
});
```

## 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](https://upstash.com/pricing/redis) to estimate the cost for your
traffic.
