# Cache de resultados e bolões — Fase 20.7

Estratégia de cache para reduzir carga no banco.

## Abordagem sugerida

### 1. Cache em memória (PHP)

Para ambientes single-instance, usar cache estático com TTL:

```php
// Exemplo: api/src/Service/CacheService.php
class CacheService {
    private static array $cache = [];
    private static array $expiry = [];
    
    public static function get(string $key): mixed {
        if (isset(self::$expiry[$key]) && time() > self::$expiry[$key]) {
            unset(self::$cache[$key], self::$expiry[$key]);
            return null;
        }
        return self::$cache[$key] ?? null;
    }
    
    public static function set(string $key, mixed $value, int $ttl = 60): void {
        self::$cache[$key] = $value;
        self::$expiry[$key] = time() + $ttl;
    }
}
```

**Uso:** Resultados de concurso (TTL 5–15 min), listagem de bolões (TTL 1–2 min).

### 2. Redis (multi-instância)

Para produção com múltiplos workers:

```php
// composer require predis/predis
$redis = new Predis\Client('tcp://127.0.0.1:6379');
$cacheKey = 'concursos:' . $idLoteria;
$cached = $redis->get($cacheKey);
if ($cached) return json_decode($cached, true);
// ... buscar do banco ...
$redis->setex($cacheKey, 300, json_encode($data));
```

### 3. HTTP Cache (frontend)

Headers `Cache-Control` em endpoints de leitura:

- `GET /api/v2/resultados/{id}`: `Cache-Control: public, max-age=300`
- `GET /api/v2/boloes`: `Cache-Control: public, max-age=60`

## Endpoints candidatos

| Endpoint | TTL sugerido |
|----------|--------------|
| GET /concursos | 60s |
| GET /boloes | 60s |
| GET /resultados/{id} | 300s |
| GET /estatisticas/* | 3600s |

## Referências

- ideias-melhorias.md §11
- api/src/Controller/ConcursoController.php
- api/src/Controller/BolaoController.php
