Pular para o conteúdo
Tecnologia

Redis é in-memory data store. Cache, sessions, queues, pub/sub. Sub-millisecond latency. Twitter, GitHub, Stack Overflow usam Redis.

Conceitos Principais

Data Structures

Strings, Hashes, Lists, Sets, Sorted Sets. Cada estrutura para use case. Não é apenas key-value.

Cache Strategy

Cache-aside: app verifica Redis, se miss consulta DB. Write-through: escreve cache e DB. TTL para expiration.

Pub/Sub

PUBLISH mensagem, SUBSCRIBE canal. Real-time messaging. Chat, notifications, live updates.

Persistence

In-memory mas pode persistir. RDB snapshots. AOF append-only file. Trade-off speed vs durability.

Passo a Passo

  1. Instale Redis: Mac: brew install redis. Docker: docker run -p 6379:6379 redis:7. redis-cli para CLI.
  2. Commands Básicos: SET key value. GET key. DEL key. EXPIRE key 60 (TTL 60s). EXISTS key. KEYS pattern.
  3. Node.js Client: npm install redis. const redis = require("redis"); const client = redis.createClient(); await client.connect(); await client.set("key", "value"); const value = await client.get("key");
  4. Cache Pattern: async function getUser(id) { let user = await redis.get(user:${id}); if (!user) { user = await db.users.findById(id); await redis.set(user:${id}, JSON.stringify(user), { EX: 3600 }); } return JSON.parse(user); }
  5. Pub/Sub: Publisher: await client.publish("notifications", message). Subscriber: await client.subscribe("notifications", (message) => { console.log(message); }).

Boas Praticas

Recomendacoes

• Use TTL para evitar memory leaks

• Namespaces em keys (user:123, post:456)

• Pipeline múltiplos commands

• Connection pooling

• Monitor memory usage

• Persistence configurada

Erros Comuns

Evite estes erros

• Cache sem TTL (memory full)

• Não tratar cache misses

• Keys sem namespace (colisões)

• Cachear tudo (memory waste)

• Não monitorar memory

Checklist

  • Redis instalado
  • Client Node.js configurado
  • Cache pattern implementado
  • TTL configurado
  • Pub/Sub testado
  • Persistence ativa