Caching in TypeScript: Redis and Other Tools for Node.js
Caching is one of the key mechanisms for optimizing web application performance. In TypeScript projects on Node.js, caching allows you to reduce API response time, lower the load on databases, and decrease the cost of external calls. In this article, we will cover popular caching libraries, their configuration, and practical examples.
Why is caching needed?
Without a cache, each request to the server can lead to repeated data processing: reading from the database, complex calculations, or accessing external APIs. The cache saves the result of the first call and returns it for subsequent requests in milliseconds. Main scenarios:
- Caching responses from external services (weather, exchange rates);
- Storing frequently requested data (directories, configurations);
- Reducing page rendering time;
- Limiting the number of requests to the database.
Popular caching libraries in TypeScript
1. Redis (via ioredis)
Redis is an in-memory data store that runs as a server. For TypeScript, the best client is ioredis with full type support. Installation:
npm install ioredisnpm install -D @types/ioredisExample of a basic cache with TTL (time to live):
import Redis from 'ioredis';
const redis = new Redis({ host: 'localhost', port: 6379,});
// Save data for 60 secondsawait redis.set('user:123', JSON.stringify({ name: 'Anna' }), 'EX', 60);
// Get dataconst cached = await redis.get('user:123');if (cached) { const user = JSON.parse(cached); console.log(user.name); // Anna}Advantages: distributed storage, automatic key eviction, support for complex structures (lists, hashes). Disadvantages: requires a running Redis server, network call latency.
2. node-cache (in-memory)
node-cache is a simple library for in-process memory caching. It requires no external dependencies. Installation:
npm install node-cachenpm install -D @types/node-cacheExample:
import NodeCache from 'node-cache';
const myCache = new NodeCache({ stdTTL: 120 }); // Default TTL 120 sec
// SavemyCache.set('config', { theme: 'dark', lang: 'en' });
// Getconst config = myCache.get('config');if (config) { console.log(config.theme); // dark}
// DeletemyCache.del('config');Suitable for small applications where synchronization between servers is not needed.
3. memory-cache
Another in-memory library with a minimalist API. It stands out for its simplicity and lack of dependencies:
npm install memory-cacheExample:
import cache from 'memory-cache';
cache.put('weather', { temp: 22, condition: 'sunny' }, 300_000); // 5 minutes
const weather = cache.get('weather');if (weather) { console.log(`Temperature: ${weather.temp}°C`);}
// Check if key existsif (cache.keys().includes('weather')) { // ...}Caching strategies for TypeScript
The choice of strategy depends on the nature of the data:
- Write-through — data is written to the cache and the database simultaneously. Guarantees consistency but increases write time.
- Write-behind — writing to the cache is instantaneous, to the database — asynchronously. Fast, but data loss is possible in case of failure.
- Cache-aside — the application itself checks the cache, on a miss reads from the database and populates the cache. The most popular pattern.
Implementation of Cache-aside in TypeScript with ioredis:
async function getUserById(id: number) { const cacheKey = `user:${id}`; const cached = await redis.get(cacheKey);
if Also in library
Working with S3 and Cloud Storage in Kotlin: AWS SDK and MinIO
Swift Application Monitoring: Libraries for iOS and macOS
PDF Generation in Swift (iOS/macOS): UIGraphicsPDFRenderer, PDFKit and Core Graphics
Sending Email in C# (.NET) using SmtpClient and MailKit