Caching in JavaScript: Redis, Memcached, and Built-in Solutions from A to Z

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

Caching in JavaScript: Redis, Memcached, and Built-in Solutions: from A to Z

\n\n

Caching is one of the key tools for improving web application performance. In the context of JavaScript and Node.js, proper caching allows you to reduce the load on databases, decrease API response time, and improve the user experience. In this article, we will cover three main approaches: built-in in-process memory caching, Memcached, and Redis. You will learn when to choose which tool and get ready-to-use code examples.

\n\n

Why is caching needed in Node.js?

\n

Node.js is a single-threaded environment with asynchronous I/O. Every request to a database or external API takes time. Caching allows you to store frequently requested data in fast storage (RAM) and serve it without repeated heavy operations. This is especially important for:

\n
    \n
  • Reducing latency on repeated requests
  • \n
  • Decreasing the load on databases (PostgreSQL, MongoDB, etc.)
  • \n
  • Saving server computing resources
  • \n
  • Increasing application throughput
  • \n
\n\n

Built-in Caching in Node.js (In-Memory Cache)

\n

The simplest way is to use a Map or Object in the global scope. This is suitable for small projects or data that lives within a single process.

\n\n

Example: Simple cache with Map

\n
const cache = new Map();\n\nfunction getCachedData(key) {\n  if (cache.has(key)) {\n    const entry = cache.get(key);\n    if (Date.now() < entry.expiry) {\n      return entry.data;\n    } else {\n      cache.delete(key); // delete expired data\n    }\n  }\n  return null;\n}\n\nfunction setCachedData(key, data, ttlMs = 60000) {\n  cache.set(key, {\n    data,\n    expiry: Date.now() + ttlMs\n  });\n}\n\n// Usage:\nsetCachedData('user:123', { name: 'Alice' }, 30000);\nconst user = getCachedData('user:123');\nconsole.log(user); // { name: 'Alice' }
\n\n

Pros: simplicity, zero network latency, no need to install additional services.
\nCons: data is not shared between multiple processes/servers, limited by the memory of a single process.

\n\n

Memcached: Distributed Caching

\n

Memcached is a high-performance distributed in-memory caching system. It is simple, fast, and well-suited for storing small amounts of data (e.g., sessions or HTML fragments). For Node.js, there is a popular module called memcached.

\n\n

Installation and Connection

\n
npm install memcached
\n\n

Example of working with Memcached

\n
const Memcached = require('memcached');\nconst memcached = new Memcached('localhost:11211');\n\n// Write data with TTL (in seconds)\nmemcached.set('user:456', { name: 'Bob' }, 3600, (err) => {\n  if (err) console.error('Write error:', err);\n});\n\n// Read data\nmemcached.get('user:456', (err, data) => {\n  if (err) {\n    console.error('Read error:', err);\n  } else if (data) {\n    console.log('Data from cache:', data);\n  } else {\n    console.log('Cache is empty — data not found');\n  }\n});\n\n// Close connection on shutdown\nprocess.on('SIGINT', () => {\n  memcached.end();\n});
\n\n

Pros: simple API, high speed, distribution across servers.
\nCons: no built-in replication, data is lost on restart, limited set of data types.

\n\n

Redis: Powerful Caching with Advanced Capabilities

\n

Redis is not just a cache, but a full-fledged in-memory data store with support for complex structures (strings, lists, sets, hashes). It supports persistence, replication, and transactions. For Node.js, we use the redis library.

\n\n

Installation

\n
npm install redis
\n\n

Example: Caching with Red

Blogs

Book Recommendations