A question you know the answer to.
Should you set up caching in Node.js? Yes.
Why? Here are the reasons:
- Caching spreads the data among the proxy caches over the WAN; thereby lowering the workload of the remote web server.
- Caching lowers bandwidth consumption. The process reduces network traffic and prevents network congestion.
- Caching keeps the website running even when the remote server isn’t available because of network partitioning or crashing.
We know what you’re thinking, “Let’s hire Node.js developers to employ caching.”
However, you might wonder which tool to use for caching. We recommend Redis. In the next five minutes, we’ll tell you how to set up caching in Node.js using Redis. This article will discuss:
- Caching patterns with Redis in Node.js
- Things you must have before you begin setting up Node.js Redis cache
- Setting up caching in Node.js using Redis
- Benefits of using Redis in Node caching
- Caching best practices
Caching in Node.js using Redis — caching patterns
The cache-aside pattern
The caching pattern exists apart from the application on a different side of the system architecture. The process makes the application responsible for the orchestration between the database and the cache.
Here’s what the steps described in the image mean:
- In the first step, the system checks the cache to find if the required data is present in the cache. If the data is present, the system delivers the information to the user without calling the database.
- In the second step, if the required data isn’t present, the system calls the database to fetch the most up-to-date information.
- In the third step, after the system receives the latest version of the data, the system writes the same information to the cache as well for future use.
However, you can face issues if the system writes data to the database and the cache update fails. Develop a backup plan such as a TTL (Time to Live) set up for times like these. The TTL setup allows developers to build a timeout for invalidating specific data in the cache. Thus, when the cache data update fails, the app won’t handle the outdated data for prolonged periods.
The write-through pattern
The pattern offers the opposite approach to the cache-aside pattern. In this process, when the system detects any change, the system first writes to the cache before calling the database.
However, the process can experience database write failures. If the issue arises, you can establish a retry policy or throw a transactional error. The former method will save the database while the latter will roll back the previous cache write.
What you must have (or know) before you begin setting up caching
- Working knowledge of Node.js and Express.js
- A code editor (VsCode)
- Postman or web browser
The process of setting up caching
Create a new directory
Run the below-mentioned command on the terminal:
cd desktop && mkdir node-caching && cd noche-caching
Here’s what the commands mean:
- cd desktop: navigate to the desktop directory
- mkdir node-caching: create a new directory titled ‘node-caching’
- cd node-caching: navigate into the newly created node-caching directory
Afterward, run the following command to initialize the directory to create a package.json file:
npm init -y
Run the following command to Redis, Axios, and Express framework for Node.js:
npm install express redis axios
Open the folder in your chosen editor. The folder structure will look like this:
Afterward, create a simple Express server as shown in the image below:
Furthermore, paste the following code into the index.js file:
Run node index.js to start the server. Afterward, open postman to create a request to the recipe endpoint.
Note that to take full advantage of Redis offerings, you must compile Redis directly from the source. Run the below-mentioned command on your terminal to achieve this:
Run the command ‘make test’ to confirm the installation. Afterward, copy Redis to your path by running the command ‘sudo make install.’
Run the command ‘redis-server’ from your terminal to confirm that the Redis set-up is complete. On the last step, open a new terminal tab or window and run ‘redis-cli ping.’ If you receive PONG as the response, you’re all set.
Benefits of using Redis in Node caching
- Redis offers data processing operations within sub-milliseconds. The feature makes Redis best suited for apps relying on real-time data analysis.
- Redis offers session storage to process the user’s data including recent activities, credentials, and shopping carts as well.
- Redis allows you to queue app tasks that take a long time to complete. You can either implement delayed queues or FIFO (First In First Out) queues to delay task implementation to a pre-scheduled time as well.
Node.js Redis Caching best practices
Grasp the data usage pattern
- Check the frequency of data changes
- Check how frequently users access the same data
- Check the user usage mode and the timings of change in data
Set cache structure
- You must cache a data record in multiple formats to access the data using various properties
- Opt for direct caching to a database record
- Cache the data in a format that mixes multiple records
Define the data to be cached
Cache static data as caching continuous changing data (also known as dynamic content) can affect the app performance.
Never store compute data in a cache
The cache is a temporary data store that can vanish at any time. Thus, storing any computed or modified data can lead to the loss of the data.
Opt for the lazy caching design
The lazy caching design objects data that the system requests rather than seeding the data in advance. The process keeps the cache size in check and allows you to manage the cache memory with ease.
Establish data expiration in a cache
Check the data usage pattern to establish the expiration period for the objects and the Node-cache.
If you choose an expiration period that’s too short, the objects will expire quickly. If you choose an expiration period that’s too long, the data can turn stale and offer a poor user experience.
Establish an eviction strategy or policy for cache
A solid eviction strategy protects the cache from exceeding the memory. Develop the eviction strategy by analysing these three data usage patterns:
- Least Recently Used (LRU): Forcibly removes cached items that users rarely search for.
- First In First Out (FIFO): Removes cached items based on the item’s age. Removes old data first.
- Explicit Removal (ER): A custom eviction policy where you decide which cached items to remove.
Caching in Node.js using Redis — a key tool to speed up response time
When users send a request to the server with a new search term for the first time, the application can take over 7 seconds to respond. The reason? The application must retrieve the data from the external API.
However, with caching in Node.js using Redis, the response time lowers to 10 ms. Thus, users receive a faster and smoother user experience which in turn helps make them loyal to your brand.