Construindo um Chatbot
Custos e Rate Limiting
Evitar abuso, limitar chamadas por usuário/IP, cache de FAQ e métricas de custo.
Nesta aula você vai
- Implementar rate limit por IP ou usuário
- Cachear respostas de perguntas frequentes
- Monitorar tokens e custo estimado
Custos e Rate Limiting
Objetivos
- Preparar chatbot para tráfego real sem susto na fatura
- Bloquear abuso antes que vire incidente financeiro
Rate limiting
Regra simples: N mensagens por janela por identificador.
| Identificador | Limite sugerido (início) |
|---|---|
| IP anônimo | 10 req / hora |
| Usuário logado | 50 req / hora |
| API key interna | 1000 req / hora |
Redis (contador)
async function checkRateLimit(key, limit, windowSec) {
const count = await redis.incr(key);
if (count === 1) await redis.expire(key, windowSec);
return count <= limit;
}
// uso
const ok = await checkRateLimit(`chat:ip:${ip}`, 10, 3600);
if (!ok) return res.status(429).json({ error: 'Limite atingido. Aguarde.' });
Alternativa sem Redis: memória local (dev) ou Cloudflare Rate Limiting na borda.
Cache de respostas
Perguntas FAQ são determinísticas — não precisam de LLM toda vez.
import { createHash } from 'crypto';
function cacheKey(message) {
return 'faq:' + createHash('sha256').update(message.trim().toLowerCase()).digest('hex');
}
const cached = await redis.get(cacheKey(message));
if (cached) return res.json({ reply: cached, cached: true });
const reply = await chat(...);
await redis.setex(cacheKey(message), 86400, reply); // 24h
Invalidação: TTL ou bump de versão no prefixo faq:v2:.
Quotas por usuário autenticado
Plano free: 20 mensagens/dia. Persista contador em DB:
UPDATE user_quota SET messages_used = messages_used + 1
WHERE user_id = ? AND date = CURRENT_DATE AND messages_used < daily_limit;
Métricas essenciais
Log por requisição:
{
"event": "llm_completion",
"userId": "u_123",
"model": "gpt-4o-mini",
"promptTokens": 450,
"completionTokens": 89,
"latencyMs": 1200,
"estimatedUsd": 0.00012
}
Dashboard: custo/dia, tokens/dia, p95 latência, taxa 429.
Kill switch
Variável LLM_ENABLED=false no env — desliga LLM, retorna mensagem estática ou fila. Use em incidente de billing ou outage do provedor.
Resumo
- Rate limit = proteção financeira e operacional
- Cache FAQ reduz tokens drasticamente
- Logue tokens em toda chamada
- Kill switch para emergências