पाठ 24 / 30

Caching रणनीतियाँ

Latency को कम करने और database load को reduce करने के लिए caching implement करें।

Caching layers

Responses को तेज़ करने के लिए HTTP caching headers, in-memory caches (जैसे node-cache), और external caches (Redis) उपयोग करें।

HTTP cache headers

Browser और CDN caching को leverage करने के लिए Cache-Control headers सेट करें।

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

Repeated expensive operations से बचने के लिए simple cache उपयोग करें।

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;
});