Lesson 24 / 30

Caching Strategies

Implement caching to reduce latency and database load.

Caching layers

Use HTTP caching headers, in-memory caches (e.g., node-cache), and external caches (Redis) to speed up responses.

HTTP cache headers

Set Cache-Control headers to leverage browser and CDN caching.

fastify.get('/posts/:id', async (req, reply) => {
  reply.header('Cache-Control', 'public, max-age=3600'); // Cache for 1 hour
  const post = await fastify.db.post.findById(req.params.id);
  return post;
});

fastify.get('/user/:id', async (req, reply) => {
  reply.header('Cache-Control', 'private, max-age=300'); // Cache for 5 min, only private
  const user = await fastify.db.user.findById(req.params.id);
  return user;
});

In-memory cache plugin

Use a simple cache to avoid repeated expensive operations.

import NodeCache from 'node-cache';

export default async function cachePlugin(fastify) {
  const cache = new NodeCache({ stdTTL: 600 });
  fastify.decorate('cache', cache);
}

// In a route:
fastify.get('/expensive/:id', async (req) => {
  const cacheKey = `expensive:${req.params.id}`;
  let result = fastify.cache.get(cacheKey);
  
  if (!result) {
    result = await expensiveOperation(req.params.id);
    fastify.cache.set(cacheKey, result);
  }
  
  return result;
});