DEV Community

Cover image for Speed Up Your NestJS App with SWR Caching and RedisX
Suren Krmoian
Suren Krmoian

Posted on

Speed Up Your NestJS App with SWR Caching and RedisX

Let's talk about something cool: Stale-While-Revalidate (SWR) caching. Imagine your app serves up slightly outdated data right away, while quietly updating it in the background. This means users get speedy responses without waiting for fresh data to load. Sweet, right? So, how do we get this running in a NestJS app? Meet RedisX.

Why Choose SWR?

Sometimes you need both speed and fresh data. SWR gives you that balance. Users get data fast, while your system updates in the background. Perfect for long data fetches, like big datasets or slow APIs.

Getting SWR Rolling with NestJS and RedisX

Ready to dive into setting up SWR? Here's how you can do it in a NestJS app using RedisX.

Step 1: Install Everything

First things first, install the necessary packages. Fire up your terminal:

npm install @nestjs-redisx/core @nestjs-redisx/cache
Enter fullscreen mode Exit fullscreen mode

Step 2: Configure AppModule

Time to set up your AppModule. We'll hook in the Redis module and smuggle in the Cache plugin with SWR enabled. Use forRootAsync() to make the magic happen with NestJS's dependency injection.

import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { RedisModule } from '@nestjs-redisx/core';
import { CachePlugin } from '@nestjs-redisx/cache';

@Module({
  imports: [
    ConfigModule.forRoot({ isGlobal: true }),
    RedisModule.forRootAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      plugins: [
        CachePlugin.registerAsync({
          imports: [ConfigModule],
          inject: [ConfigService],
          useFactory: (config: ConfigService) => ({
            l1: { enabled: true, maxSize: 1000, ttl: 60 },
            defaultTtl: config.get('CACHE_TTL', 300),
            swr: { enabled: true, maxStale: 3600 },
          }),
        }),
      ],
      useFactory: (config: ConfigService) => ({
        clients: {
          type: 'single',
          host: config.get('REDIS_HOST', 'localhost'),
          port: config.get('REDIS_PORT', 6379),
        },
      }),
    }),
  ],
})
export class AppModule {}
Enter fullscreen mode Exit fullscreen mode

Step 3: Use the @Cached Decorator

Here's where the magic happens. Use the @Cached decorator to slap caching onto your service methods. It'll let you define keys, TTLs, and SWR settings for each method.

import { Injectable } from '@nestjs/common';
import { Cached } from '@nestjs-redisx/cache';

@Injectable()
export class ProductService {
  @Cached({ key: 'product:{0}', ttl: 300, swr: { maxStale: 3600 } })
  async getProduct(id: string): Promise<Product> {
    return this.db.findProduct(id);
  }
}
Enter fullscreen mode Exit fullscreen mode

In this setup, getProduct will serve stale data if it's there and refresh it in the background. Seamless for the user.

Why RedisX Rocks for SWR

RedisX makes SWR easy with its plugin system that uses just one Redis connection. Less overhead, more features. You get L1+L2 caching, tag-based invalidation, and more.

  • Performance Boost: Serve data instantly from the cache.
  • User Happiness: Less waiting for fresh data.
  • Simple Setup: Async support makes configuration a breeze.

Wrapping It Up

Setting up SWR in your NestJS app with RedisX is a breeze and super beneficial. Your apps stay fast and data stays fresh. Want to dive deeper? Check out the NestJS RedisX documentation.

By using RedisX, your NestJS apps don't just get faster—they become more robust and scalable. Redis magic at your fingertips.

Top comments (0)