Back to results for “SQL/Sequelize)”
Node.js › Caching

What is caching, and why is it commonly used to improve the performance of a Node.js application?

Beginner

Answer

Caching stores the result of an expensive operation (a database query, an API call, a computed value) temporarily, so subsequent requests for the same data can be served from the fast cache instead of repeating the expensive work -- reducing latency for end users and reducing load on downstream systems like databases, which is especially valuable for data that's read far more often than it changes.
const cache = new Map();

async function getUser(id) {
  if (cache.has(id)) return cache.get(id);
  const user = await db.users.findById(id);
  cache.set(id, user);
  return user;
}
Real-world example A product-catalog API that previously queried the database on every request starts serving the vast majority of requests from an in-memory cache instead, since product data changes only a few times a day but is read thousands of times per minute.

Common follow-ups: What's the risk of caching data that changes frequently, and how do you decide what's safe to cache?;What is cache invalidation, and why is it often called one of the two hardest problems in computer science?