Spring Fresh Sale! - Up To 67% OFF BDIX Hosting + Free Domain
Node.js

How to Add Caching to a Node.js App with Redis and In-Memory Stores

Caching stores the results of expensive work so you can serve them instantly next time, instead of hitting your database or recomputing on every request. For a busy Node.js app it is one of the highest-impact performance upgrades, and you have two main options: in-memory and Redis.

In-memory caching: fast and simple

Storing values in a variable or a small library cache is the fastest option — the data lives right in your process. It is perfect for small, frequently-read data on a single instance. The limits: it is lost on restart, and it is not shared across multiple processes or servers.

Redis: shared and scalable

Redis is an in-memory data store that runs as a separate service, so a cache in Redis is shared across all your app instances. This matters the moment you run more than one process — which you will if you use clustering or multiple servers. Redis also survives your app restarting and supports expiry (TTL).

A typical caching pattern

let data = await redis.get(key);
if (!data) { data = await db.query(...); await redis.set(key, JSON.stringify(data), 'EX', 300); }

This "cache-aside" pattern checks the cache first, falls back to the database on a miss, and stores the result with a 5-minute expiry.

Cache invalidation: the hard part

Stale data is the main risk. Use sensible TTLs so entries refresh, and clear or update cache entries when the underlying data changes. Cache what is read often and changes rarely for the best return.

Frequently asked questions

In-memory or Redis — which should I use?

In-memory for a single small app instance; Redis once you scale to multiple processes or servers, because the cache must be shared. Many apps use both: a tiny in-memory layer in front of Redis.

Do I need a separate server for Redis?

Redis runs as its own service. On a VPS you can install it alongside your app; managed Redis is also common. On shared hosting, availability varies — check with your host.

What should I not cache?

Highly dynamic, per-user or sensitive data that must always be current. Cache stable, frequently-read data, and be careful never to serve one user's cached private data to another.

Was this article helpful?