Building fast and reliable web applications is more important than ever in today's digital landscape. Users have high expectations when it comes to website performance. Slow loading times or downtime can lead to customer frustration and reputational damage.

One way of achieving fast and reliable web applications is through the use of caching. There are different kinds of caches you can implement in your application, including in-memory cache, browser cache, database cache, and CDN cache.

What is caching, and how does in-memory caching differ? How can you increase your Nest.js application's performance with in-memory caching?

What Is Caching?

Caching is the process of storing frequently accessed data in a temporary location to improve the performance of an application or system. The cached data can be quickly retrieved and served to the user without having to retrieve it again from the original source.

Applications use caching to deliver content more quickly and efficiently, which leads to a better user experience and reduced load on the underlying systems. The most common types of caching include in-memory caching, CDN caching, browser caching, and database caching.

What Is In-Memory Caching?

In-memory caching is a type of caching in which an application temporarily stores frequently accessed data in the server's memory. Instead of making expensive database calls each time the app processes a request to access data, it can fetch that data from memory.

Caching the data in memory means the application accesses data faster, and this results in improved performance.

How to Implement In-Memory Caching in a Nest.js Application

Nest.js has built-in support for caching using drivers like Redis, Memcached, and many more. However, for easy understanding, this article uses the built-in memory cache module that Nest.js provides.

This section assumes you already have a Nest.js application created with the Nest CLI command: nest new [app name]. To implement the in-memory cache in an endpoint, you should have the module, service, and controller files already, or generate them using the nest generate command. You can find out more about nest generate in the Nest CLI documentation.

The first step to implement an in-memory cache is to import the CacheModule from @nestjs/common into your endpoint's module as seen below:

        // example.module.ts
import { Module, CacheModule } from '@nestjs/common';

@Module({
  imports: [CacheModule.register()],
})

export class ExampleModule {}

Next, you need to import CacheService and inject it into the Nest.js service that communicates with a database like MongoDB. You can see how the following code example does this:

        // example.service.ts
import { Injectable, CacheService } from '@nestjs/common';

@Injectable()
export class ExampleService {
  constructor(private readonly cacheService: CacheService) {}

  async getData(): Promise<any> {
    const cacheKey = 'my_data';
    let data = await this.cacheService.get(cacheKey);

    if (!data) {
      // fetch data from database or API
      data = await this.fetchData();

      // cache data for future use
      await this.cacheService.set(cacheKey, data, { ttl: 60 });
    }

    return data;
  }

  private async fetchData(): Promise<any> {
    // fetch data from database
  }
}

In the example code above, the ExampleService uses CacheService as a dependency. The getData method checks if the data is available in the cache using a key (cacheKey), if the data is not in the cache, it goes ahead to fetch it from the database and caches it for later use.

The CacheService has a set method that takes in an object as an argument. In this case, you can see how the value { ttl: 60 } sets the time-to-live to 60 seconds. This implies that the service will automatically remove the cached data after one minute.

Some important advantages of in-memory caching include the following:

  • Improved scalability: In-memory caching can help improve the scalability of applications by reducing the load on the underlying data source.
  • Faster response time: Caching frequently accessed data in memory reduces the time it takes to retrieve the data, resulting in faster response times.
  • Better user experience: Faster response times and improved scalability can help provide a better user experience by reducing the wait time and improving the overall performance of the application.
  • Reduced costs: By reducing the load on the data source, in-memory caching can help reduce the cost of running the application.

Optimizing Nest.js Applications With In-Memory Caching

In-memory caching is a very effective way to improve overall application performance. You’ve seen how to implement an in-memory cache in Nest.js and how it improves scalability and user experience. It can also improve response time, and reduce the costs of running your application.

Try putting the concept of caching to practical use when building your next Nest.js API or application.