Redis Cache System
Advanced Redis caching layer with namespaces, TTL, and Express middleware for API response caching and high-performance data retrieval.
Overview
A high-performance Redis caching component for Express and Node.js. Implements key namespaces, flexible TTL, and programmatic APIs for manual or middleware-based caching. Perfect for reducing database load and improving API latency across scalable backend systems.
Installation
What This Does
Installs a Redis-based caching system with automatic middleware integration, key management utilities, and programmatic APIs for Express applications.
Files & Folders Created
| File / Path | Description |
|---|---|
| /src/config/redis.js | Initializes Redis client with connection and namespace support. |
| /src/utils/cacheKeys.js | Utility for building consistent namespaced keys. |
| /src/services/cacheService.js | Core caching logic (set/get/del/clear). |
| /src/middleware/cacheResponse.js | Express middleware for auto-response caching. |
| /src/routes/cacheAdmin.js | Admin endpoints for managing cache namespaces. |
| /main.js.example | Demo Express app with caching in action. |
Files to be modified
| File / Path | Description |
|---|---|
| server.js | Adds cache admin routes and response caching middleware. |
| .env | Adds Redis connection and namespace configuration. |
Configuration
# Redis Configuration REDIS_URL=redis://localhost:6379 REDIS_NAMESPACE=backternity PORT=3000
Frontend Integration
Integrate Redis caching with your frontend or Next.js app to dramatically speed up repeated API calls. This example shows how to fetch and display cached data (with `fromCache` status).
Fetches cached product data, with automatic TTL-based invalidation.
Lists all cache keys for a specific namespace.
Clears all cached entries under a namespace.
Example
1// app/cache/ProductsFetcher.jsx (Next.js example)
2'use client';
3import { useState, useEffect } from 'react';
4
5export default function ProductsFetcher() {
6 const [products, setProducts] = useState([]);
7 const [loading, setLoading] = useState(true);
8 const [fromCache, setFromCache] = useState(false);
9
10 useEffect(() => {
11 async function fetchProducts() {
12 setLoading(true);
13 const res = await fetch('/api/products');
14 const data = await res.json();
15 setProducts(data.data);
16 setFromCache(data.fromCache);
17 setLoading(false);
18 }
19 fetchProducts();
20 }, []);
21
22 return (
23 <div className="p-4 border border-white/10 rounded-lg bg-black/30">
24 <h3 className="text-lg font-semibold mb-2 text-white">
25 🛍️ Product List {fromCache && <span className="text-xs text-emerald-400">(from cache)</span>}
26 </h3>
27 {loading ? (
28 <p className="text-sm text-muted-foreground">Loading...</p>
29 ) : (
30 <ul className="space-y-2">
31 {products.map((p) => (
32 <li key={p.id} className="text-sm text-foreground">
33 {p.name}
34 </li>
35 ))}
36 </ul>
37 )}
38 <p className="text-xs text-gray-500 mt-3">🔄 Data auto-caches for 60s using Redis.</p>
39 </div>
40 );
41}Usage
1// Direct Cache Service Example
2const cacheService = require('./src/services/cacheService');
3
4// Set cache
5await cacheService.set('user', '123', { name: 'Alice' }, 300);
6
7// Get cache
8const user = await cacheService.get('user', '123');
9
10// Clear cache namespace
11await cacheService.clearNamespace('user');