Pular para o conteúdo
Tecnologia

Caching correto acelera apps em 10-100x. Estratégia errada causa bugs e dados stale. Aprenda patterns que funcionam.

Conceitos Principais

Cache-Aside

App verifica cache. Miss: busca DB, salva cache. Hit: retorna cache. Simples, popular. Lazy loading.

Write-Through

Write sempre atualiza cache e DB. Consistência. Writes mais lentos. Dados sempre fresh.

Write-Behind

Write atualiza cache, DB assíncrono. Performance. Risco de perda. Queue de writes.

Cache Stampede

Cache expira. Múltiplos requests batem DB simultâneo. Solução: lock, stale-while-revalidate.

Passo a Passo

  1. Implemente Cache-Aside: async function getData(key) { let cached = await redis.get(key); if (!cached) { const data = await db.query(...); await redis.set(key, JSON.stringify(data), { EX: 3600 }); return data; } return JSON.parse(cached); }
  2. TTL Strategy: Dados que mudam pouco: TTL longo (1h-24h). Dados dinâmicos: TTL curto (1-5min). Critical data: write-through + TTL curto.
  3. Invalidation: On update/delete: await redis.del(key). Tag-based: await redis.del(...keys). Pub/sub notifica invalidação.
  4. Previna Stampede: async function getWithLock(key) { const lockKey = lock:${key}; if (await redis.set(lockKey, "1", { NX: true, EX: 10 })) { /* busca DB */ } else { await new Promise(r => setTimeout(r, 100)); return getData(key); }}
  5. Monitor Hit Rate: Track hits/misses. INFO stats: keyspace_hits, keyspace_misses. Target > 80% hit rate. Ajuste TTL.

Boas Praticas

Recomendacoes

• Cache-aside para reads

• Write-through para dados críticos

• TTL sempre (previne stale data)

• Namespaced keys

• Monitor hit rate

• Graceful degradation (cache down → DB direct)

Erros Comuns

Evite estes erros

• Cache sem invalidation strategy

• TTL muito longo (stale data)

• Não tratar cache stampede

• Cachear dados user-specific em cache compartilhado

• Não monitorar performance

Checklist

  • Cache strategy escolhida
  • TTL configurado
  • Invalidation implementada
  • Stampede prevention ativa
  • Hit rate > 80%
  • Graceful degradation testada