Caching in TypeScript: Redis, Memcached, and In-Memory Solutions

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 TypeScript: Redis, Memcached, and In-Memory Solutions



Caching is one of the key mechanisms for optimizing the performance of web applications. In the TypeScript and Node.js ecosystem, there are several proven approaches to organizing caching: from simple in-memory solutions to distributed systems based on Redis and Memcached. In this article, we will thoroughly examine popular libraries, their installation, configuration, and usage examples.



Why is caching needed?

Caching allows you to reduce server response time, decrease the load on databases and external APIs, and improve the user experience. Main use cases:

  • Saving results of expensive computations
  • Caching responses from external APIs
  • Storing user sessions
  • Caching fragments of HTML pages


1. ioredis — Advanced Redis Client

ioredis is the most popular library for working with Redis in Node.js and TypeScript. It supports clustering, Pub/Sub, transactions, and automatic reconnection.



Installation:

npm install ioredisnpm install @types/ioredis --save-dev


Basic usage with TypeScript:

import Redis from 'ioredis';

// Connecting to local Redisconst redis = new Redis({ host: 'localhost', port: 6379, retryStrategy: (times) => Math.min(times * 50, 2000)});

// Function for caching dataasync function getCachedData(key: string): Promise<string | null> { const cached = await redis.get(key); if (cached) { console.log('Data from cache'); return cached; } // Simulating fetching data from DB const data = `Data for ${key} at ${new Date().toISOString()}`; await redis.setex(key, 3600, data); // TTL 1 hour return data;}

// Usage example(async () => { const result = await getCachedData('user:123'); console.log(result);})();


Caching objects:

interface User {    id: number;    name: string;    email: string;}

async function cacheUser(user: User): Promise<void> { await redis.setex(`user:${user.id}`, 3600, JSON.stringify(user));}

async function getUserFromCache(id: number): Promise<User | null> { const cached = await redis.get(`user:${id}`); return cached ? JSON.parse(cached) : null;}


2. node-cache — Simple In-Memory Caching

node-cache is a lightweight library for storing data in the RAM of a Node.js process. It is ideal for small projects or prototypes where distributed caching is not required.



Installation:

npm install node-cachenpm install @types/node-cache --save-dev


Usage example:

import NodeCache from 'node-cache';

const myCache = new NodeCache({ stdTTL: 600, // default time to live (seconds) checkperiod: 120 // period for checking expired keys});

// Saving and retrieving datamyCache.set('key1', { value: 42 });const value = myCache.get('key1');console.log(value); // { value: 42 }

// Checking if a key existsif (myCache.has('key1')) { console.log('Key exists');}

// Deleting by keymyCache.del('key1');

// Getting statisticsconst stats = myCache.getStats();console.log(`Keys in cache: ${stats.keys}`);


3. lru-cache — Cache with LRU Policy

lru-cache is a cache implementation with the Least Recently Used eviction algorithm. It limits the number of stored entries, automatically removing the oldest ones. It is excellent for caching with a fixed size.



Installation:

npm install lru-cache                    

Recommendations