Skip to content

alekspetrovv/caching-system-nestjs

Repository files navigation

REST API NestJS with Caching – Example Project

A fully functional example project built with NestJS, demonstrating how to create a REST API with Cache-Aside and Write-Through Caching Mechanisms.

Project Goal

This project aims to showcase caching mechanisms in the simplest way possible. It demonstrates Users CRUD API connected to a relational database while using a Map Data Structure for in-memory caching.

Project Caching Examples

The first caching use case is Write-Through. When a client makes a request to create or update a record through the API, the new or updated data is stored in both the database and the cache with Time-To-Live. Time-to-live automatically removes stale data from the cache after a specified duration. The data will be stored in both cache and in database to keep data in sync. (Figure 1.0)

Figure 1.0 Write-Through

The second caching use case is Cache-Aside. When a client requests a single user or multiple users, the system first checks the cache for the data. If the data is available, it is returned immediately; if not, the system retrieves it from the database and stores it in the cache for future requests. This approach significantly improves the performance of read operations since accessing data from memory is much faster than reading from disk-based storage. (Figure 2.0)

Figure 2.0 Cache-Aside

The cache will be cleaned to limit the amount of data stored in-memory with a cron job. This cron job will be checked for expired data, and if there is, it will delete cache data from in-memory. (Figure 3.0)

Figure 3.0 Cache-Aside

There is also an option to use FIFO (First-In, First-Out) eviction policy when the cache is full. This means the oldest item added to the cache is removed first to make space for new items. (Figure 4.0)

Figure 4.0 FIFO-CACHE

Project installation instructions

  1. Clone the project: git clone [email protected]:alekspetrovv/caching-system-nestjs.git
  2. Install Postgresql locally
  3. Install project dependencies: npm i
  4. Migrate database: npx prisma migrate dev --schema src/prisma/schema.prisma
  5. Generate database types: npx prisma generate --schema src/prisma/schema.prisma
  6. Run project: npm run start:prod

Swagger Documentation

Swagger documentation will be available with the user endpoints to test the caching when api is started: localhost:3000/docs:

Swagger

The caching will be indicated in the get user/users endpoint with the following response example in the request:

Swagger-Responses

Furthermore, the application contains logs to indicate if the cache is successfully made or not:

Swagger

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published