--- id: "INT-007" title: "Integracion Redis Cache/Queue" type: "Integration" status: "Implemented" priority: "P0" provider: "Redis/Upstash" category: "Infrastructure" multi_tenant: false version: "1.0.0" created_date: "2026-01-07" updated_date: "2026-01-10" --- # INT-007: Redis Integration ## Metadata | Campo | Valor | |-------|-------| | Codigo | INT-007 | | Proveedor | Redis (ioredis) | | Tipo | Cache | | Estado | Implementado | | Multi-tenant | Si | | Fecha integracion | 2026-01-10 | --- **Usado por:** SAAS-010-webhooks, SAAS-007-notifications ## Resumen Redis como backend para BullMQ (colas de procesamiento). ## Uso - Cola de webhooks outbound - Cola de notificaciones asincronas - Cache de sesiones (opcional) ## Caracteristicas - BullMQ para job processing - Retry logic automatico - Dead letter queue para fallos - Dashboard Bull Board (opcional) ## Configuracion ```env REDIS_HOST=localhost REDIS_PORT=6379 REDIS_PASSWORD=... # opcional REDIS_DB=0 ``` ## Endpoints/SDK Utilizados | Operacion | Comando | Descripcion | |-----------|---------|-------------| | Set cache | `SET key value EX ttl` | Guardar con expiracion | | Get cache | `GET key` | Obtener valor | | Delete | `DEL key` | Eliminar clave | | Exists | `EXISTS key` | Verificar existencia | | TTL | `TTL key` | Tiempo restante | | Increment | `INCR key` | Incrementar contador | | Hash set | `HSET hash field value` | Guardar en hash | | Hash get | `HGET hash field` | Obtener de hash | | List push | `LPUSH list value` | Agregar a lista | | List pop | `RPOP list` | Obtener de lista | | Set add | `SADD set member` | Agregar a set | | Set members | `SMEMBERS set` | Obtener miembros | | Sorted add | `ZADD zset score member` | Agregar a sorted set | | Sorted range | `ZRANGE zset start stop` | Rango de sorted set | | Publish | `PUBLISH channel message` | Publicar mensaje | | Subscribe | `SUBSCRIBE channel` | Suscribirse a canal | | Expire | `EXPIRE key seconds` | Establecer TTL | | Scan | `SCAN cursor MATCH pattern` | Buscar claves | ## Dependencias NPM ```json { "@nestjs/bullmq": "^10.x", "bullmq": "^5.x", "ioredis": "^5.x" } ``` ## Rate Limits | Limite | Valor | Accion si excede | |--------|-------|------------------| | Conexiones | 10000 por instancia | Pool de conexiones | | Comandos/seg | 100000+ | Depende del hardware | ## Manejo de Errores | Codigo | Descripcion | Accion | |--------|-------------|--------| | ECONNREFUSED | Conexion rechazada | Verificar servicio Redis | | ETIMEDOUT | Timeout | Retry con backoff | | NOAUTH | Sin autenticacion | Configurar REDIS_PASSWORD | | OOM | Sin memoria | Escalar o limpiar cache | ## Fallbacks ### Estrategia Redis Fallback | Escenario | Estrategia | |-----------|------------| | Redis no disponible | Memory cache temporal (node-cache) | | Conexion perdida | Reconexion automatica con backoff | | Cluster failover | Redis Sentinel para HA | | Memoria llena | Eviction LRU automatico | ### Configuracion Sentinel (Alta Disponibilidad) ```typescript // Configuracion recomendada para produccion { sentinels: [ { host: 'sentinel-1', port: 26379 }, { host: 'sentinel-2', port: 26379 }, { host: 'sentinel-3', port: 26379 } ], name: 'mymaster', sentinelRetryStrategy: (times) => Math.min(times * 100, 3000) } ``` ### Circuit Breaker - Umbral apertura: 5 fallos consecutivos - Timeout semi-abierto: 30 segundos - Fallback: In-memory cache con TTL reducido ## Multi-tenant - Credenciales: Global (una instancia Redis compartida) - Configuracion: Por tenant via prefijos de clave - Aislamiento: Prefijo tenant_id en todas las operaciones (keys: tenant:{tenant_id}:*) ## Testing ### Sandbox/Test Mode - Usar Redis local o redis-mock para tests - DB separada para tests (REDIS_DB=1) - Fixtures disponibles para testing unitario ## Monitoreo | Metrica | Descripcion | Alerta | |---------|-------------|--------| | Latencia | Tiempo de respuesta | >2s | | Errores | Tasa de errores | >1% | | Disponibilidad | Uptime del servicio | <99.9% | | Memoria | Uso de memoria | >80% | ## Referencias - Modulo webhooks: SAAS-010-webhooks.md - Modulo notifications: SAAS-007-notifications.md --- **Ultima actualizacion:** 2026-01-10 **Version:** 1.0.0