Caching in JavaScript: Redis, Memcached, and Built-in Solutions for Node.js

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Introduction: Why Caching in JavaScript is Needed

Modern web applications on Node.js process millions of requests daily. Without proper caching, every call to a database or external API creates a delay, increases server load, and degrades user experience. Caching is a technique of temporarily storing frequently requested data in fast storage, so that heavy operations are not performed again on subsequent requests.

In the JavaScript (Node.js) ecosystem, there are three main approaches to caching:

  • Built-in solutions (In-memory cache) — simple libraries that store data in the memory of the Node.js process.
  • Memcached — a distributed caching system that works in RAM.
  • Redis — an advanced in-memory data store with support for complex data structures.

In this article, we will analyze each approach in detail, provide code examples in JavaScript, and help you choose the optimal solution for your project.



Built-in Solutions for Caching in Node.js

The simplest way to organize caching is to use built-in JavaScript capabilities or lightweight libraries. Such solutions do not require installing external services and are ideal for small projects or prototypes.



Simple Object Cache

A basic example of caching using a regular JavaScript object:

class SimpleCache {  constructor() {    this.cache = {};  }

get(key) { return this.cache[key]; }

set(key, value, ttl = 60000) { this.cache[key] = value; setTimeout(() => { delete this.cache[key]; }, ttl); }

delete(key) { delete this.cache[key]; }

clear() { this.cache = {}; }}

// Usageconst cache = new SimpleCache();cache.set('user:123', { name: 'Anna', role: 'admin' }, 30000);console.log(cache.get('user:123')); // { name: 'Anna', role: 'admin' }

Disadvantages of this approach: no automatic memory cleanup, memory leaks with a large number of keys, no support for distributed caching.



node-cache Library

A more advanced option is to use the node-cache package:

const NodeCache = require('node-cache');const myCache = new NodeCache({ stdTTL: 100, checkperiod: 120 });

// Save datamyCache.set('key', { data: 'value' });

// Get dataconst value = myCache.get('key');if (value === undefined) { // Data not found — need to fetch from DB console.log('Cache miss');} else { console.log('Cache hit:', value);}

// Delete by keymyCache.del('key');

// Statisticsconsole.log(myCache.getStats());

node-cache supports TTL (time to live), automatic cleanup of expired keys, and basic statistics. However, it is not suitable for multi-process applications — each Node.js process stores its own copy of the data.



Memcached: Lightweight Distributed Caching

Memcached is a high-performance distributed object caching system in RAM. It is ideal for caching database query results, user sessions, and HTML fragments.



Installing and Connecting Memcached

First, install the Memcached server and the client for Node.js:

# Install server (Ubuntu/Debian)sudo apt-get install memcached

# Install client for Node.jsnpm install memcached


Example of Working with Memcached in Node.js

const Memcached = require('memcached');const memcached = new Memcached('localhost:11211');

// Save data with TTL (in seconds)memcached.set('user:456', { name: 'Ivan', email: 'ivan@example.com' }, 3600, (err) => { if (err) console.error('Error saving:', err);});

// Get datamemcached.get('user:456', (err, data) => { if

Blogs

Book Recommendations