# Redis

Redis 7 configuration for rate limiting, token blacklist, idempotency, and session caching in Monetarie PIX.

## Prerequisites

- Redis 7.x installed and accessible
- Network connectivity from backend pods to Redis
- Basic understanding of Redis data structures

## Use Cases

| Feature | Key Pattern | TTL | Data Type |
|---------|-------------|-----|-----------|
| Rate limiting | `rate_limit:{ip}:{path}` | 15 min | String (counter) |
| Token blacklist | `blacklist:{jti}` | Remaining JWT TTL | String |
| Idempotency | `idempotency:{user_id}:{key}` | 24 hours | String (JSON) |
| Session cache | `session:{token}` | Configurable | Hash |
| RBAC cache | ETS (not Redis) | 5 min | -- |

## Configuration

### Environment Variables

```bash
REDIS_HOST=10.140.240.4
REDIS_PORT=6379
```

### Connection Pool

The `Shared.Redis.Connection` GenServer manages a 10-connection pool:

```elixir
# Shared.Application supervision tree
{Shared.Redis.Connection, [
  host: System.get_env("REDIS_HOST", "localhost"),
  port: String.to_integer(System.get_env("REDIS_PORT", "6379"))
]}
```

Redis operations have a 5-second timeout to prevent blocking on network issues.

## Rate Limiting

Login rate limiting uses a Redis token bucket algorithm:

- **Limit**: 10 attempts per 15 minutes per IP
- **Paths**: `/api/v1/auth/login`, `/api/v1/auth/mfa/verify`
- **Response**: HTTP 429 with `Retry-After` header

```
SET rate_limit:192.168.1.1:/api/v1/auth/login 1 EX 900 NX
INCR rate_limit:192.168.1.1:/api/v1/auth/login
```

## Token Blacklist

When a user logs out, their JWT is blacklisted until it naturally expires:

```
SET blacklist:{jti} 1 EX {remaining_ttl}
```

The `JWTAuth` plug checks blacklist on every authenticated request:

```
EXISTS blacklist:{jti}
```

## Idempotency

The `Shared.Plugs.Idempotency` plug prevents duplicate payment processing:

```
SET idempotency:{user_id}:{idempotency_key} {response_json} EX 86400 NX
```

- Key: SHA-256 of request body + user ID + idempotency header
- Atomic `SET NX` prevents TOCTOU race conditions
- Max body size: 64 KB
- TTL: 24 hours

## Redis Server Configuration (Production)

```conf
# redis.conf
maxmemory 4gb
maxmemory-policy allkeys-lru
save 900 1
save 300 10
appendonly yes
appendfsync everysec
```

### Sentinel Configuration (HA)

```conf
# sentinel.conf
sentinel monitor monetarie-pix 10.0.1.10 6379 2
sentinel down-after-milliseconds monetarie-pix 5000
sentinel failover-timeout monetarie-pix 60000
```

## Monitoring

Key Redis metrics to monitor:

| Metric | Threshold | Action |
|--------|-----------|--------|
| `used_memory` | > 80% maxmemory | Scale or increase maxmemory |
| `connected_clients` | > 500 | Check for connection leaks |
| `keyspace_misses` | High ratio | Review cache strategy |
| `blocked_clients` | > 0 sustained | Investigate blocking ops |

```bash
# Check Redis status
redis-cli INFO stats
redis-cli INFO memory
redis-cli DBSIZE
```

## Expected Outcome

After configuring Redis:

- 10-connection pool established from each backend pod
- Rate limiting active on login endpoints
- Token blacklist functioning on logout
- Idempotency preventing duplicate payments
- All Redis operations completing within 5-second timeout
