0
0
Node.jsframework~8 mins

In-memory caching patterns in Node.js - Performance & Optimization

Choose your learning style9 modes available
Performance: In-memory caching patterns
MEDIUM IMPACT
This affects server response time and CPU usage by reducing repeated data processing or fetching delays.
Caching data to avoid repeated database calls in a Node.js server
Node.js
const cache = new Map();
async function getUser(id) {
  if (cache.has(id)) return cache.get(id);
  const user = await db.query(`SELECT * FROM users WHERE id = ${id}`);
  cache.set(id, user);
  return user;
}
Caches user data in memory to serve repeated requests instantly without DB calls.
📈 Performance GainReduces response time by 50-200ms per repeated request, lowers DB load
Caching data to avoid repeated database calls in a Node.js server
Node.js
async function getUser(id) {
  const user = await db.query(`SELECT * FROM users WHERE id = ${id}`);
  return user;
}
Every request triggers a database query causing high latency and CPU load.
📉 Performance CostIntroduces I/O latency from DB roundtrips, increasing response time by 50-200ms per request
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
No caching (fetch every time)N/A (server-side)N/AN/A[X] Bad
In-memory caching with MapN/A (server-side)N/AN/A[OK] Good
Rendering Pipeline
In-memory caching reduces backend processing time before sending data to the client, improving server response speed.
Server Processing
Network Transfer
⚠️ BottleneckServer Processing (database or computation delays)
Optimization Tips
1Cache only frequently requested or expensive-to-fetch data in memory.
2Implement cache size limits or expiration to avoid memory bloat.
3Use caching to reduce backend processing time, improving server response speed.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance benefit of using in-memory caching in a Node.js server?
AIncreases database query speed
BImproves client-side rendering speed
CReduces repeated expensive data fetching or computation
DReduces CSS paint time
DevTools: Network and Performance panels
How to check: Use Network panel to compare response times for repeated requests; use Performance panel to check server response duration if profiling backend.
What to look for: Look for reduced response times and fewer backend calls on repeated requests indicating effective caching.