Cache

Corimusical11 de diciembre de 2025

Definición

Datos guardados temporalmente para acelerar operaciones repetidas, evitando recalcular o refetching innecesarios.

Descripción

El cache (caché) almacena datos temporalmente para acelerar accesos futuros. Reduce latencia, carga en servidores y mejora la experiencia de usuario. Tipos de cache: - Browser cache: Archivos estáticos (JS, CSS, imágenes) - CDN cache: Contenido distribuido geográficamente - Application cache: Redis, Memcached - Database cache: Query cache, buffer pool - HTTP cache: Headers Cache-Control, ETag Estrategias: Cache-first, Network-first, Stale-while-revalidate.

Ejemplo

JavaScript
// HTTP Cache Headers (Express)
app.use('/static', express.static('public', {
  maxAge: '1y',           // Cache 1 año
  immutable: true         // No revalidar
}));

app.get('/api/products', (req, res) => {
  res.set({
    'Cache-Control': 'public, max-age=3600', // 1 hora
    'ETag': productHash
  });
  res.json(products);
});

// Redis Cache (Node.js)
import Redis from 'ioredis';
const redis = new Redis();

async function getUser(id) {
  const cacheKey = `user:${id}`;

  // Intentar cache primero
  const cached = await redis.get(cacheKey);
  if (cached) {
    return JSON.parse(cached);
  }

  // Si no está en cache, consultar DB
  const user = await db.user.findUnique({ where: { id } });

  // Guardar en cache (TTL 1 hora)
  await redis.setex(cacheKey, 3600, JSON.stringify(user));

  return user;
}

// Invalidar cache
async function updateUser(id, data) {
  await db.user.update({ where: { id }, data });
  await redis.del(`user:${id}`);
}

// React Query - Cache en cliente
const { data } = useQuery({
  queryKey: ['user', id],
  queryFn: () => fetchUser(id),
  staleTime: 5 * 60 * 1000,     // 5 min fresh
  gcTime: 30 * 60 * 1000        // 30 min en memoria
});