A fully functional example project built with NestJS, demonstrating how to create a REST API with Cache-Aside and Write-Through Caching Mechanisms.
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.
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)
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)
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)
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)
- Clone the project:
git clone [email protected]:alekspetrovv/caching-system-nestjs.git - Install Postgresql locally
- Install project dependencies:
npm i - Migrate database:
npx prisma migrate dev --schema src/prisma/schema.prisma - Generate database types:
npx prisma generate --schema src/prisma/schema.prisma - Run project:
npm run start:prod
Swagger documentation will be available with the user endpoints to test the caching when api is started:
localhost:3000/docs:
The caching will be indicated in the get user/users endpoint with the following response example in the request:
Furthermore, the application contains logs to indicate if the cache is successfully made or not:






