Redis Caching Tutorial: Speed Up Node.js API Responses

by Fahim Mahmud Chisti

If every request to your Node.js API waits on the same slow database query, Redis caching is the quickest fix. This tutorial adds Redis caching to an Express API with a reusable middleware, a TTL on every key and cache invalidation on updates, so repeated reads come from memory instead of the database.

Quick answer: Put a small Express middleware in front of your GET routes. It looks up the request URL in Redis and returns the cached JSON on a hit; on a miss it lets the route run and stores the response with a TTL. Delete the key whenever that data changes.

  1. Install express, redis and dotenv, and start a Redis server.
  2. Create one shared client with createClient() and connect it at startup.
  3. Add a middleware that calls get() and, on a miss, saves the response with setEx() and a TTL.
  4. Delete the matching key in every route that updates or deletes the data.
  5. Call the same URL twice with curl: the first request is a miss, the second a hit.
In this guide
  1. Before You Start
  2. What You Will Build
  3. How Redis Caching Speeds Up a Node.js API
  4. Step 1: Install the Packages and Add a .env File
  5. Step 2: Connect to Redis from Node.js
  6. Step 3: Write the Cache Middleware
  7. Step 4: Cache a GET Route and Clear It on Update
  8. Step 5: Start the Express Server
  9. Test It: Confirm the Cache Hit and the Invalidation
  10. Cache-Aside vs Write-Through: Which Pattern to Use
  11. Check Your Cache Hit Rate
  12. Avoid These Common Redis Caching Mistakes
  13. If It Still Doesn’t Work
  14. Frequently Asked Questions
  15. Next Steps
A developer workspace showing a terminal running Redis CLI and a code editor with Node.js caching middleware.

Before You Start

  • Node.js 18 or newer (a current LTS release is best). Check with node -v.
  • A running Redis server. The quickest local option is Docker: docker run -d --name redis-cache -p 127.0.0.1:6379:6379 redis. Check it with docker exec redis-cache redis-cli ping, which should print PONG.
  • An empty project folder and a terminal open in it. The whole tutorial takes about 20 minutes.
  • A staging copy if you are adding this to a live API. A wrong cache key can serve one caller’s data to another, so test there first.

What You Will Build

By the end you will have five files in your project folder:

  • .env – the port and the Redis connection URL.
  • redisClient.js – one shared Redis connection.
  • cacheMiddleware.js – the reusable caching middleware.
  • productRoutes.js – a sample GET route that is cached and a PUT route that clears the cache.
  • server.js – starts Express and mounts the routes.

How Redis Caching Speeds Up a Node.js API

Redis keeps data in memory, so reading a key is much faster than running a database query. You store the result of a frequent query in Redis and answer later requests from there.

The flow is simple. When a request arrives, the app checks Redis for the data first. If it is there (a cache hit), the app returns it right away and the database is never touched. If it is missing (a cache miss), the app queries the database, saves the result in Redis and then responds.

A cache also protects your database during traffic spikes. Without one, many users asking for the same page send the same query over and over, which can exhaust connections and cause timeouts. With a cache, those repeated reads are answered from memory and the database is left free for writes.

Step 1: Install the Packages and Add a .env File

Run these commands in your project folder. They create a package.json and install Express for routing, the official Redis client and dotenv for settings:

npm init -y
npm install express redis dotenv

Next, create a file named .env in the project root. It holds the server port and the Redis connection string:

PORT=3000
REDIS_URL=redis://localhost:6379

If Redis runs on another machine or a cloud service, put that URL here instead. Use rediss:// (two s’s) when the provider requires TLS.

Step 2: Connect to Redis from Node.js

Create a file named redisClient.js. It creates one client, connects it when the app starts and exports it so every other file shares the same connection. The node-redis client documentation lists the other connection options.

const redis = require('redis');
require('dotenv').config();
const client = redis.createClient({ url: process.env.REDIS_URL });
client.on('error', (err) => console.error('Redis Client Error', err));
(async () => {
  await client.connect();
  console.log('Connected to Redis successfully');
})();
module.exports = client;

When the app starts you should see Connected to Redis successfully in the terminal. If you see an ECONNREFUSED error instead, jump to the troubleshooting section below.

Step 3: Write the Cache Middleware

The middleware runs before your route handler. For each request it uses the URL as the cache key, returns cached data if the key exists, and otherwise lets the route run and caches what it sends. Putting this in middleware for the Express framework keeps your route handlers free of caching code.

Create a file named cacheMiddleware.js and add this:

const redisClient = require('./redisClient');
const cacheMiddleware = (ttl = 3600) => {
  return async (req, res, next) => {
    const key = req.originalUrl || req.url;
    try {
      const cachedData = await redisClient.get(key);
      if (cachedData !== null) {
        console.log(`Cache hit for key: ${key}`);
        return res.json(JSON.parse(cachedData));
      }
      console.log(`Cache miss for key: ${key}`);
      res.sendResponse = res.json;
      res.json = (body) => {
        // Only cache successful responses, and never let a failed cache write break the request
        if (res.statusCode >= 200 && res.statusCode < 300) {
          redisClient.setEx(key, ttl, JSON.stringify(body)).catch((err) => console.error('Cache write error:', err));
        }
        return res.sendResponse(body);
      };
      next();
    } catch (error) {
      console.error('Cache middleware error:', error);
      next();
    }
  };
};
module.exports = cacheMiddleware;

Here is what the code does:

  • It wraps res.json. When the route sends its response, the wrapper saves a copy in Redis with a Time-To-Live (TTL), the number of seconds before Redis deletes the key.
  • It only caches 2xx responses, so a temporary error is never served from the cache.
  • If Redis fails, the request carries on to the database instead of failing.

The cache key is just the URL. Only use this middleware on routes that return the same data to every caller. For per-user data, add the user ID to the key or skip the cache.

Step 4: Cache a GET Route and Clear It on Update

Every cache needs a rule for removing old data, or users will see outdated results. Two mechanisms work together:

  • TTL: every key expires on its own after a set time, even if you forget to clear it.
  • Invalidation: when the data changes, you delete the key straight away so the next read fetches fresh data.

Create a file named productRoutes.js. The GET route is cached for 600 seconds, and the PUT route deletes the same key after an update:

const express = require('express');
const router = express.Router();
const redisClient = require('./redisClient');
const cacheMiddleware = require('./cacheMiddleware');
// Mock database query
const getProductFromDb = async (id) => {
  return { id, name: 'Developer Laptop', price: 1299 };
};
// GET route with caching
router.get('/api/products/:id', cacheMiddleware(600), async (req, res) => {
  const product = await getProductFromDb(req.params.id);
  res.json(product);
});
// UPDATE route that invalidates cache
router.put('/api/products/:id', async (req, res) => {
  const productId = req.params.id;
  const cacheKey = `/api/products/${productId}`;
  // Update database logic here...
  // Invalidate cache
  await redisClient.del(cacheKey);
  console.log(`Cache cleared for key: ${cacheKey}`);
  res.json({ message: 'Product updated and cache cleared' });
});
module.exports = router;

The key you delete must match the key the middleware saved, which is the full request URL. If clients add query strings, such as ?currency=eur, each variation is a separate key.

Step 5: Start the Express Server

Create a file named server.js. It loads the settings, mounts the routes with app.use() and starts listening:

require('dotenv').config();
const express = require('express');
const productRoutes = require('./productRoutes');
const app = express();
app.use(express.json());
app.use(productRoutes);
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

Start it from your project folder:

node server.js

You should see Server running on port 3000 and Connected to Redis successfully.

Test It: Confirm the Cache Hit and the Invalidation

Open a second terminal and request the same product twice:

curl http://localhost:3000/api/products/1
curl http://localhost:3000/api/products/1

Both calls return the same JSON: {"id":"1","name":"Developer Laptop","price":1299}. The difference shows in the server terminal: the first request logs Cache miss for key: /api/products/1 and the second logs Cache hit for key: /api/products/1.

Now update the product and request it again:

curl -X PUT http://localhost:3000/api/products/1
curl http://localhost:3000/api/products/1

The PUT returns {"message":"Product updated and cache cleared"}, the server logs Cache cleared for key: /api/products/1, and the next GET is a miss again. That proves invalidation works.

To see the key inside Redis, run docker exec redis-cache redis-cli ttl /api/products/1 right after a GET. It prints the seconds left before the key expires (600 or less).

Cache-Aside vs Write-Through: Which Pattern to Use

The middleware above uses the cache-aside pattern: the app reads from the cache first and falls back to the database on a miss. The other common pattern is write-through, where every write goes to the cache and the database at the same time.

Most web apps use cache-aside because it is simple and survives a Redis outage. If Redis goes down, requests can fall back to the database without breaking the app.

For that fallback to happen with node-redis, the client has to fail fast. By default it queues commands while it reconnects, so requests wait instead of falling through. Create the client with disableOfflineQueue: true so cache calls reject immediately and the middleware’s catch block sends the request on to the database. The official Redis documentation covers persistence and clustering if you need them later.

  • Choose cache-aside for read-heavy APIs where slightly stale data for a short time is acceptable. It loads data lazily, recovers easily and only caches what is actually requested.
  • Choose write-through when reads must always match the latest write. It keeps the cache consistent, but every write takes longer and the cache may hold data nobody reads.

Check Your Cache Hit Rate

The best sign that caching works is a high ratio of cache hits to misses. Redis tracks both. Run this on the machine where Redis runs (with Docker, prefix it with docker exec redis-cache):

redis-cli info stats

Look for keyspace_hits and keyspace_misses in the output. If misses grow as fast as hits, your TTL may be too short or your keys may vary more than you expect, for example because of query strings.

To compare response times with and without the cache, run a load-testing tool such as autocannon against the route, for example npx autocannon -c 50 -d 10 http://localhost:3000/api/products/1, once with the middleware and once without it. With a real database behind the route, the cached run should show lower latency.

Avoid These Common Redis Caching Mistakes

Cache stampedes

A cache stampede happens when a popular key expires and many requests miss at the same moment, so they all hit the database together. Add a small random amount to each TTL so keys do not expire at the same moment, or let only one request rebuild the key while the others wait. The same problem appears at the CDN layer, where it is solved with origin shield and request collapsing.

Running out of memory

Without a limit, Redis keeps every key until it expires. Set a memory limit and an eviction policy in your redis.conf file:

maxmemory 256mb
maxmemory-policy allkeys-lru

The allkeys-lru policy removes the least recently used keys when the limit is reached, so your app keeps working instead of getting out-of-memory errors. Use this only on a Redis instance that holds cache data. Job queues such as BullMQ need noeviction, so give them their own instance, as explained in the guide on handling API rate limits with BullMQ and Redis.

Large payloads

Every cached value is serialised with JSON.stringify() and parsed again on each hit. Cache only the fields the client needs rather than whole database rows, so values stay small and quick to parse.

If It Still Doesn’t Work

  • ECONNREFUSED 127.0.0.1:6379: Redis is not running or listens on another port. Start the container again with docker start redis-cache and check it with redis-cli ping.
  • ECONNREFUSED ::1:6379: localhost resolved to the IPv6 address, but Redis only listens on IPv4. Change REDIS_URL to redis://127.0.0.1:6379.
  • Every request is a cache miss: the route may be returning an error status (errors are never cached), or the URL changes between requests. Check the logged key on each request.
  • Old data after an update: the key deleted in the PUT route does not match the cached URL exactly. Log both keys and compare them, including any query string.
  • Requests hang while Redis is down: the client is queuing commands. Add disableOfflineQueue: true to createClient() so the middleware falls back to the database.

Frequently Asked Questions

How do I handle Redis connection drops in Node.js?

The node-redis client reconnects automatically when a connection drops. You can control the wait between attempts with the socket.reconnectStrategy option, for example to back off exponentially. Always attach an error listener as in Step 2, because an unhandled error event can crash the process.

Can I store JavaScript objects directly in Redis?

No, a plain Redis key holds a string, so you convert objects first. Serialise with JSON.stringify() before saving and turn the value back into an object with JSON.parse() when you read it, as the middleware does. Redis also has hashes, lists, sets and sorted sets for data you need to update field by field.

How long should my cache TTL be?

Use the longest TTL your users can accept stale data for. Product details or settings that change rarely can be cached for minutes or hours, while prices or stock levels may need seconds. Combine any TTL with invalidation on writes, so a change shows up right away even when the TTL is long.

What is the difference between Redis and Memcached?

Both are in-memory stores, but Redis does more. Redis supports rich data types, persistence to disk, replication and clustering. Memcached is a simpler, multithreaded key-value cache. If you only need a basic cache either works; if you also want queues, sessions or rate limiting, Redis covers them with one service.

Next Steps

You now have a cached Express API with a TTL on every key and invalidation on updates. Apply the middleware to your slowest GET routes first, check keyspace_hits after a day of traffic, and adjust TTLs from there. To protect the same API from abusive traffic with the Redis server you already run, follow the guide to building a Redis sliding window rate limiter in Node.js.

all_in_one_marketing_tool