By using this site, you agree to the Privacy Policy and Terms of Use.
Accept
World of SoftwareWorld of SoftwareWorld of Software
  • News
  • Software
  • Mobile
  • Computing
  • Gaming
  • Videos
  • More
    • Gadget
    • Web Stories
    • Trending
    • Press Release
Search
  • Privacy
  • Terms
  • Advertise
  • Contact
Copyright © All Rights Reserved. World of Software.
Reading: How to Master Distributed Cache in Nest.JS | HackerNoon
Share
Sign In
Notification Show More
Font ResizerAa
World of SoftwareWorld of Software
Font ResizerAa
  • Software
  • Mobile
  • Computing
  • Gadget
  • Gaming
  • Videos
Search
  • News
  • Software
  • Mobile
  • Computing
  • Gaming
  • Videos
  • More
    • Gadget
    • Web Stories
    • Trending
    • Press Release
Have an existing account? Sign In
Follow US
  • Privacy
  • Terms
  • Advertise
  • Contact
Copyright © All Rights Reserved. World of Software.
World of Software > Computing > How to Master Distributed Cache in Nest.JS | HackerNoon
Computing

How to Master Distributed Cache in Nest.JS | HackerNoon

News Room
Last updated: 2025/04/03 at 4:56 PM
News Room Published 3 April 2025
Share
SHARE

Caching can be a thorn in any developer’s side. I’ve spent too many hours wrestling with slow APIs and overburdened databases, searching for a solution that’s both effective and easy to implement.

That’s why I was thrilled when Karol (karol71927), a talented member of our open-source organization, Nestixis, created @nestixis/cache-manager.

This lightweight, Redis-powered library has streamlined caching in my NestJS projects, and I’m eager to share how it’s made a difference.

The Challenge: Caching Complexity in NestJS

The scenario is all too familiar: your application runs smoothly until traffic surges, and suddenly your database buckles under the load. Caching is the obvious fix—store data once, serve it quickly—but integrating it into NestJS often feels cumbersome. Redis offers powerful capabilities, but setting it up typically involves wrangling configurations, managing expiration policies, and defining custom cache keys.

I needed a tool that simplified the process while allowing precise control over what gets cached, like request parameters or queries.

So, Karol designed @nestixis/cache-manager to address these pain points with a clean, efficient approach. This package provides a straightforward API for managing Redis caching, complete with configurable TTLs and support for advanced caching strategies. It’s available at its GitHub repo, and its design reflects our team’s commitment to practical, reusable tools.

Getting Started: Seamless Setup

Installation is as simple as it gets:

npm i @nestixis/cache-manager

To integrate it into your NestJS app, register it in a module:

import { Module } from '@nestjs/common';
import { CacheModule } from '@nestixis/cache-manager';
import { ConfigModule, ConfigService } from '@nestjs/config';

@Module({
  imports: [
    CacheModule.registerAsync({
      isGlobal: true,
      imports: [ConfigModule],
      useFactory: (configService: ConfigService) => ({
        redis: {
          host: configService.get('REDIS_HOST') || 'localhost',
          port: +configService.get('REDIS_PORT') || 6379,
        },
        cachePrefix: 'cache:',
        defaultCacheTTL: 1000, // 1-second default
      }),
      inject: [ConfigService],
    }),
  ],
})
export class AppModule {}

This sets up Redis caching across your app with minimal effort. From there, you can interact with it manually in a service:

import { Injectable } from '@nestjs/common';
import { CacheManager } from '@nestixis/cache-manager';

@Injectable()
export class MyService {
  constructor(private readonly cacheManager: CacheManager) {}

  async getData(key: string) {
    const cached = await this.cacheManager.get(key);
    if (cached) return cached;

    const data = await this.fetchData();
    await this.cacheManager.add(key, data, 1000); // Cache for 1 second
    return data;
  }

  async clearData(key: string) {
    await this.cacheManager.remove(key);
  }

  private fetchData() {
    return new Promise((resolve) => setTimeout(() => resolve('Data'), 2000));
  }
}

What sets this package apart is its ability to cache based on specific request details—a feature Karol thoughtfully included. Take this

controller:

import { Controller, Get, Post, Delete, Param, UseInterceptors } from '@nestjs/common';
import { CacheInterceptor, CacheRemoveInterceptor, CacheTrackBy } from '@nestixis/cache-manager';
import { MyService } from './my.service';

@Controller('site/:token')
@CacheTrackBy({
  prefix: 'site',
  ttl: 10000, // 10 seconds
  by: [
    {
      by: 'param',
      name: 'token',
    },
  ],
})
export class SiteController {
  constructor(private readonly service: MyService) {}

  @Get()
  @UseInterceptors(CacheInterceptor)
  async get(@Param('token') token: string) {
    return this.service.getData(`site:${token}`);
  }

  // Will clear cache on add or remove of resource to keep fresh state
  @Post()
  @UseInterceptors(CacheRemoveInterceptor)
  async add(@Param('token') token: string) {
    await this.service.getData(`site:${token}`); // Refresh data
  }

  @Delete()
  @UseInterceptors(CacheRemoveInterceptor)
  async remove(@Param('token') token: string) {
    await this.service.clearData(`site:${token}`);
  }
}

The @CacheTrackBy decorator is the key here. It ensures caching is tied to the :token parameter, so /site/abc and /site/xyz each get their own cache entry.

You can adjust it to use queries or other criteria instead, offering the flexibility I’d always wanted. The CacheInterceptor handles GET requests, while CacheRemoveInterceptor clears the cache on updates—elegant and intuitive.

Sign Up For Daily Newsletter

Be keep up! Get the latest breaking news delivered straight to your inbox.
By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Share This Article
Facebook Twitter Email Print
Share
What do you think?
Love0
Sad0
Happy0
Sleepy0
Angry0
Dead0
Wink0
Previous Article Here are the best iPad deals you can get
Next Article E.U. Prepares Major Penalties Against Elon Musk’s X
Leave a comment

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Stay Connected

248.1k Like
69.1k Follow
134k Pin
54.3k Follow

Latest News

Here’s why ChatGPT needs to know how to make bioweapons
News
Uncertainty looms over next week’s launch of Huawei’s HarmonyOS NEXT system · TechNode
Computing
Amazon under UK investigation over alleged failure to pay suppliers on time
News
Telegram founder planning to leave fortune to his 100+ children
News

You Might also Like

Computing

Uncertainty looms over next week’s launch of Huawei’s HarmonyOS NEXT system · TechNode

1 Min Read
Computing

Everyone’s an AI User Now—But No One Read the Manual | HackerNoon

16 Min Read
Computing

Meituan shifts focus from GMV to order volume amid declining sales · TechNode

1 Min Read
Computing

Stop Prompting, Start Engineering: 15 Principles to Deliver Your AI Agent to Production | HackerNoon

45 Min Read
//

World of Software is your one-stop website for the latest tech news and updates, follow us now to get the news that matters to you.

Quick Link

  • Privacy Policy
  • Terms of use
  • Advertise
  • Contact

Topics

  • Computing
  • Software
  • Press Release
  • Trending

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

World of SoftwareWorld of Software
Follow US
Copyright © All Rights Reserved. World of Software.
Welcome Back!

Sign in to your account

Lost your password?