Nest.js Tutorial

Implementing in-memory cache to increase the performance

Marcin Wanago
JavaScriptNestJSTypeScript

There are quite a few things we can do when tackling our application’s performance. We sometimes can make our code faster and optimize the database queries. To make our API even more performant, we might want to completely avoid running some of the code.

Accessing the data stored in the database is quite often time-consuming. It adds up if we also perform some data manipulation on top of it before returning it to the user. Fortunately, we can improve our approach with caching. By storing a copy of the data in a way that it can be served faster, we can speed up the response in a significant way.

Implementing in-memory cache

The most straightforward way to implement cache is to store the data in the memory of our application. Under the hood, NestJS uses the cache-manager library. We need to start by installing it.

1npm install cache-manager

To enable the cache, we need to import the CacheModule in our app.

posts.module.ts
1import { CacheModule, Module } from '@nestjs/common';
2import PostsController from './posts.controller';
3import PostsService from './posts.service';
4import Post from './post.entity';
5import { TypeOrmModule } from '@nestjs/typeorm';
6import { SearchModule } from '../search/search.module';
7import PostsSearchService from './postsSearch.service';
8 
9@Module({
10  imports: [
11    CacheModule.register(),
12    TypeOrmModule.forFeature([Post]),
13    SearchModule,
14  ],
15  controllers: [PostsController],
16  providers: [PostsService, PostsSearchService],
17})
18export class PostsModule {}

By default, the amount of time that a response is cached before deleting it is 5 seconds. Also, the maximum number of elements in the cache is 100 by default. We can change those values by passing additional options to the CacheModule.register() method.

1CacheModule.register({
2  ttl: 5,
3  max: 100
4});

Automatically caching responses

NestJS comes equipped with the CacheInterceptor. With it, NestJS handles the cache automatically.

posts.controller.ts
1import {
2  Controller,
3  Get,
4  UseInterceptors,
5  ClassSerializerInterceptor,
6  Query, CacheInterceptor,
7} from '@nestjs/common';
8import PostsService from './posts.service';
9import { PaginationParams } from '../utils/types/paginationParams';
10 
11@Controller('posts')
12@UseInterceptors(ClassSerializerInterceptor)
13export default class PostsController {
14  constructor(
15    private readonly postsService: PostsService
16  ) {}
17 
18  @UseInterceptors(CacheInterceptor)
19  @Get()
20  async getPosts(
21    @Query('search') search: string,
22    @Query() { offset, limit, startId }: PaginationParams
23  ) {
24    if (search) {
25      return this.postsService.searchForPosts(search, offset, limit, startId);
26    }
27    return this.postsService.getAllPosts(offset, limit, startId);
28  }
29  // ...
30}

If we call this endpoint two times, NestJS does not invoke the getPosts method twice. Instead, it returns the cached data the second time.

In the twelfth part of this series, we’ve integrated Elasticsearch into our application. Also, in the seventeenth part, we’ve added pagination. Therefore, our /posts endpoint accepts quite a few query params.

A very important thing that the official documentation does not mention is that NestJS will store the response of the getPosts method separately for every combination of query params. Thanks to that, calling /posts?search=Hello and /posts?search=World can yield different responses.

Although above, we use CacheInterceptor for a particular endpoint, we can also use it for the whole controller. We could even use it for a whole module. Using cache might sometimes cause us to return stale data, though. Therefore, we need to be careful about what endpoint do we cache.

Using the cache store manually

Aside from using the automatic cache, we can also interact with the cache manually. Let’s inject it into our service.

posts.service.ts
1import { CACHE_MANAGER, Inject, Injectable } from '@nestjs/common';
2import Post from './post.entity';
3import { InjectRepository } from '@nestjs/typeorm';
4import { Repository } from 'typeorm';
5import PostsSearchService from './postsSearch.service';
6 
7@Injectable()
8export default class PostsService {
9  constructor(
10    @InjectRepository(Post)
11    private postsRepository: Repository<Post>,
12    private postsSearchService: PostsSearchService,
13    @Inject(CACHE_MANAGER) private cacheManager: Cache
14  ) {}
15 
16  // ...
17 
18}

An important concept to grasp is that the cache manager provides a key-value store. We can:

  • retrieve the values using the cacheManager.get('key') method,
  • add items using cacheManager.set('key', 'value),
  • remove elements with cacheManager.del('key'),
  • clear the whole cache using cacheManager.reset().

It can come in handy for more sophisticated cases. We can even use it together with the automatic cache.

Invalidating cache

If we would like to increase the time in which our cache lives, we need to figure out a way to invalidate it. If we want to cache the list of our posts, we need to refresh it every time a post is added, modified, or removed.

To do use the cacheManager.del function to remove the cache, we need to know the key. The CacheInterceptor under the hood creates a key for every route we cache. This means that it creates separate cache keys both for /posts and /posts?search=Hello.

Instead of relying on CacheInterceptor to generate a key for every route, we can define it ourselves with the @CacheKey decorator. We can also use @CacheTTL  to increase the time during which the cache lives.

postsCacheKey.constant.ts
1export const GET_POSTS_CACHE_KEY = 'GET_POSTS_CACHE';
posts.controller.ts
1@UseInterceptors(CacheInterceptor)
2@CacheKey(GET_POSTS_CACHE_KEY)
3@CacheTTL(120)
4@Get()
5async getPosts(
6  @Query('search') search: string,
7  @Query() { offset, limit, startId }: PaginationParams
8) {
9  if (search) {
10    return this.postsService.searchForPosts(search, offset, limit, startId);
11  }
12  return this.postsService.getAllPosts(offset, limit, startId);
13}

The above creates a big issue, though. Because now our custom key is always used for the getPosts method, it means that different query parameters yield the same result. Both /posts and /posts?search=Hello now use the same cache.

To fix this, we need to extend the CacheInterceptor class and change its behavior slightly. The trackBy method of the CacheInterceptor returns a key that is used within the store. Instead of returning the cache key, let’s add the query params to it.

To view the original trackBy method, check out this file in the repository.
httpCache.interceptor.ts
1import { CACHE_KEY_METADATA, CacheInterceptor, ExecutionContext, Injectable } from '@nestjs/common';
2 
3@Injectable()
4export class HttpCacheInterceptor extends CacheInterceptor {
5  trackBy(context: ExecutionContext): string | undefined {
6    const cacheKey = this.reflector.get(
7      CACHE_KEY_METADATA,
8      context.getHandler(),
9    );
10 
11    if (cacheKey) {
12      const request = context.switchToHttp().getRequest();
13      return `${cacheKey}-${request._parsedUrl.query}`;
14    }
15 
16    return super.trackBy(context);
17  }
18}
request._parsedUrl property is created by the parseurl library

If we don’t provide the @CacheKey decorator with a key, NestJS will use the original trackBy method through super.trackBy(context).

Otherwise, the HttpCacheInterceptor will create keys like POSTS_CACHE-null and POSTS_CACHE-search=Hello.

Now we can create a clearCache method and use it when we create, update, and delete posts.

1import { CACHE_MANAGER, Inject, Injectable } from '@nestjs/common';
2import CreatePostDto from './dto/createPost.dto';
3import Post from './post.entity';
4import UpdatePostDto from './dto/updatePost.dto';
5import { InjectRepository } from '@nestjs/typeorm';
6import { Repository } from 'typeorm';
7import PostNotFoundException from './exceptions/postNotFound.exception';
8import User from '../users/user.entity';
9import PostsSearchService from './postsSearch.service';
10import { Cache } from 'cache-manager';
11import { GET_POSTS_CACHE_KEY } from './postsCacheKey.constant';
12 
13@Injectable()
14export default class PostsService {
15  constructor(
16    @InjectRepository(Post)
17    private postsRepository: Repository<Post>,
18    private postsSearchService: PostsSearchService,
19    @Inject(CACHE_MANAGER) private cacheManager: Cache
20  ) {}
21 
22  async clearCache() {
23    const keys: string[] = await this.cacheManager.store.keys();
24    keys.forEach((key) => {
25      if (key.startsWith(GET_POSTS_CACHE_KEY)) {
26        this.cacheManager.del(key);
27      }
28    })
29  }
30 
31  async createPost(post: CreatePostDto, user: User) {
32    const newPost = await this.postsRepository.create({
33      ...post,
34      author: user
35    });
36    await this.postsRepository.save(newPost);
37    this.postsSearchService.indexPost(newPost);
38    await this.clearCache();
39    return newPost;
40  }
41 
42  async updatePost(id: number, post: UpdatePostDto) {
43    await this.postsRepository.update(id, post);
44    const updatedPost = await this.postsRepository.findOne(id, { relations: ['author'] });
45    if (updatedPost) {
46      await this.postsSearchService.update(updatedPost);
47      await this.clearCache();
48      return updatedPost;
49    }
50    throw new PostNotFoundException(id);
51  }
52 
53  async deletePost(id: number) {
54    const deleteResponse = await this.postsRepository.delete(id);
55    if (!deleteResponse.affected) {
56      throw new PostNotFoundException(id);
57    }
58    await this.postsSearchService.remove(id);
59    await this.clearCache();
60  }
61 
62  // ...
63}

By doing the above, we invalidate our cache when the list of posts should change. With that, we can increase the Time To Live (TTL) and increase our application’s performance.

Summary

In this article, we’ve implemented an in-memory cache both by using the auto-caching and interacting with the cache store manually. Thanks to adjusting the way NestJS tracks cache responses, we’ve also been able to appropriately invalidate our cache.

While the in-memory cache is valid in a lot of cases, it has its disadvantages. For example, it is not shared between multiple instances of our application. To deal with this issue, we can use Redis. We will cover this topic in upcoming articles, so stay tuned!