Performance: Redis for distributed caching
This affects server response time and reduces backend load by caching data close to the application.
const cachedData = await redisClient.get('key'); if (cachedData) { res.send(JSON.parse(cachedData)); } else { const data = await fetchFromDatabase(); await redisClient.set('key', JSON.stringify(data), { EX: 60 }); res.send(data); }
const data = await fetchFromDatabase(); // fetch every time without cache
res.send(data);| Pattern | Backend Calls | Response Time | Cache Hit Rate | Verdict |
|---|---|---|---|---|
| No caching | Database call every request | High (100-300ms+) | 0% | [X] Bad |
| Redis caching | Database call only on cache miss | Low (10-50ms) | High (depends on TTL) | [OK] Good |
const redis = require('redis');
async function test() {
const client = redis.createClient();
await client.connect();
await client.set('key', 'value');
const result = await client.get('key');
console.log(result);
await client.disconnect();
}
test();const redis = require('redis');
const client = redis.createClient();
client.connect();
client.set('foo', 'bar');
const val = client.get('foo');
console.log(val);Pass the test and this pattern moves unknown