# Caching, Redis & Scaling

> Three-tier Delivery caching (CDN Surrogate-Key, L2 Redis/Valkey or in-memory LRU, conditional ETags), race-free tag version snapshotting, distributed rate limiting, and HA worker leases.

OvertCMS Core is built to serve high-traffic public clients with minimal database load while keeping content updates fresh within seconds.

## Three-Tier Delivery Caching Architecture

```mermaid
flowchart LR
    User["Visitor / Browser"] --> CDN["Tier 1: Edge CDN\nSurrogate-Key + SWR"]
    CDN -->|"Cache Miss / Revalidate"| Del["Delivery Plane"]
    Del -->|"Tier 2: L2 Cache Lookup"| L2["Memory LRU or\nRedis / Valkey"]
    L2 -->|"Cache Miss"| DB[("SQLite or\nPostgreSQL")]
    Mut["Publish / Schema Update"] -->|"Immediate"| L2Inv["Invalidate L2 Tags\n(O(1) tagver INCR)"]
    Mut -->|"Transactional Outbox"| Worker["Worker Plane"]
    Worker -->|"Signed POST"| CDNPurge["Tier 1 CDN Purge\nWebhook"]
```

### Tier 1: Edge CDN & `Surrogate-Key` Headers

Every public Delivery JSON response emits CDN-native caching headers:

| Header | Value (Public Mode) | Value (`OVERTCMS_DELIVERY_REQUIRE_API_KEY=true`) |
| :--- | :--- | :--- |
| `Cache-Control` | `public, max-age=60, stale-while-revalidate=300` | `private, max-age=60` |
| `Surrogate-Key` | Space-separated tags (e.g., `site:default type:posts entry:<id>`) | Omitted (prevents accidental public CDN caching of private data) |
| `ETag` | `"sha256:<hex>"` | `"sha256:<hex>"` |
| `Vary` | `X-Preview-Token` (on entry/singleton routes) | `Authorization` (+ `X-Preview-Token` on entry/singleton routes) |
| `X-OvertCMS-Cache` | `HIT` or `MISS` | `HIT` or `MISS` |

Media streaming responses (`GET /delivery/v1/media/{id}`) emit `Cache-Control: public, max-age=31536000, immutable` and `ETag: "sha256:<assetSha256>"`.

#### Canonical Surrogate-Key Taxonomy

| Tag | Attached To | Invalidated When |
| :--- | :--- | :--- |
| `site:<siteSlug>` | Every Delivery response for that site | Site metadata, schema, or any published entry changes |
| `type:<postTypeSlug>` | Collection lists, single entries, singletons of that type | Any entry of that PostType is published, unpublished, archived, trashed, or purged |
| `entry:<entryId>` | Single entry responses, collection lists containing that entry, **and** any response that expanded that entry via `?expand=` | That specific entry changes state |
| `sitemap` | `GET /delivery/v1/sitemap.json` | Any entry is published, unpublished, archived, trashed, or purged |
| `redirects` | `GET /delivery/v1/redirects` | A published entry changes slug (creating/collapsing a 301 redirect) or clears an existing redirect path |

#### CDN Purge Webhook Integration

Set `OVERTCMS_CDN_PURGE_WEBHOOK_URL` (and optional `OVERTCMS_CDN_PURGE_SECRET`) so the Worker Plane pushes Surrogate-Key purge batches directly to Fastly, Cloudflare, Varnish, or a custom edge bridge whenever an outbox event is processed:

```json
{
  "eventId": "0193a8b5-...",
  "eventType": "entry.published",
  "siteId": "0193a8b0-...",
  "surrogateKeys": ["site:default", "type:posts", "entry:0193a8b2-...", "sitemap"],
  "timestamp": "2026-11-25T15:30:05Z"
}
```

CDN purge requests include `User-Agent: OvertCMS-CDNPurge/1.0`, `X-OvertCMS-Event`, `X-OvertCMS-Timestamp`, and (when `OVERTCMS_CDN_PURGE_SECRET` is configured) `X-OvertCMS-Signature` signed with the exact same `sha256=<hex>` HMAC-SHA-256 scheme over `<timestamp>.<payload>` as outbound webhooks.

---

### Tier 2: L2 Delivery Cache (In-Memory LRU or Redis/Valkey)

Public Delivery responses are cached in L2 for **60 seconds** (`deliveryCacheTTL`) using canonical cache keys built strictly from `siteSlug`, URL path, route-allowlisted query parameters (ignoring arbitrary cache-busting junk params), and (when `DeliveryRequireAPIKey=true`) a deterministic SHA-256 suffix of the API key's `allowedPostTypes` scope. Requests carrying `X-Preview-Token` **always bypass** the L2 cache.

#### In-Memory LRU (Default when `OVERTCMS_REDIS_URL` is unset)

- Bounded to **2,048 entries** and **64 MiB** (`defaultMaxMemoryCacheEntries`, `defaultMaxMemoryCacheBytes`) with O(1) LRU eviction.
- Supports immediate tag invalidation and race-free tag-version snapshotting.

#### Redis / Valkey L2 Cache (`OVERTCMS_REDIS_URL`)

When `OVERTCMS_REDIS_URL` (`redis://...` or `rediss://...`) is configured and reachable at startup:

- Cached responses are stored under `overtcms:cache:resp:<key>` with a 60s `SETEX` TTL, embedding the snapshot of each tag's integer generation counter.
- Tag invalidation runs a single atomic O(1) Lua script (`INCR` + `EXPIRE 86400`) on `overtcms:cache:tagver:<tag>`—avoiding unbounded Redis `SET`s, `SMEMBERS`, or giant `DEL` spikes.
- On `Get`, a single `MGET` checks current tag versions; any mismatch is treated as an instant cache miss.
- **Fail-open availability**: Transient Redis timeouts or errors silently degrade to a cache miss so Delivery availability is never tied to Redis health.

#### Preventing Read/Write Cache Races (`VersionedDeliveryCache`)

Before executing a database read on a cache miss, the Delivery handler calls `SnapshotTagVersions` for baseline tags (`site:<slug>`, `type:<slug>`, etc.). If a concurrent publish invalidates one of those tags while the DB read is in flight, `SetWithTagVersions` detects the version bump and refuses to store the stale response.

---

### Tier 3: Conditional `ETag` / `If-None-Match`

Even on L2 cache misses, Delivery computes a deterministic content `ETag`. Clients sending `If-None-Match` matching the current `ETag` receive `304 Not Modified` with an empty body.

---

## Distributed Rate Limiting (Redis/Valkey Lua)

When `OVERTCMS_REDIS_URL` is configured, all API key quotas and Admin auth rate limits automatically switch to `RedisRateLimiter`:

- Uses a single atomic Lua script (`atomicCapIncrScript`) performing cap-check + `INCRBY` + `EXPIRE` with zero race conditions or rollback bugs:
  - Per-minute RPM: `overtcms:rl:rpm:<keyId>:<minuteBucket>` (65s TTL)
  - Sliding/bucketed auth windows: `overtcms:rl:win:<windowSec>:<keyId>:<bucket>`
  - Daily write cap: `overtcms:rl:writes:<keyId>:<YYYY-MM-DD>` (90,000s TTL)
  - Daily media bytes cap: `overtcms:rl:media:<keyId>:<YYYY-MM-DD>` (90,000s TTL)
- Automatically falls back to the local in-memory limiter if Redis becomes transiently unreachable (`2s` timeout).

---

## Horizontal Scaling & High-Availability Workers

To scale OvertCMS Core across multiple nodes:

1. **Database**: Switch from SQLite to **PostgreSQL** (`OVERTCMS_DB_DRIVER=postgres`). Run `overtcms migrate` once during deployment before rolling out new pods.
2. **Media**: Switch to **S3 / Cloudflare R2** (`OVERTCMS_MEDIA_DRIVER=s3`) with `OVERTCMS_MEDIA_CDN_URL_TEMPLATE` pointing to your public bucket/CDN.
3. **Cache & Rate Limiting**: Configure shared **Redis or Valkey** (`OVERTCMS_REDIS_URL`).
4. **Master Secret**: Distribute the exact same `OVERTCMS_SECRET_KEY` (32+ bytes) across all replicas.
5. **Plane Separation**: Scale `delivery`, `agent`, `admin`, and `worker` independently via `OVERTCMS_PLANES`.

### Distributed Worker Leases (`worker_leases`)

You can safely run **2 or more `worker` replicas** for high availability. On every poll tick (`OVERTCMS_WORKER_POLL_INTERVAL`, default `5s`), each worker attempts to acquire atomic database leases in `worker_leases` with TTL `max(3 * pollInterval, 30s)`:

| Lease Name | Responsibility |
| :--- | :--- |
| `worker:scheduler` | Scheduled publish (`scheduled_at <= now`), scheduled unpublish (`unpublish_at <= now`), expired ephemeral media cleanup, and stale `pending_upload` cleanup. |
| `worker:outbox_fanout` | L2 cache invalidation, CDN `Surrogate-Key` purge webhook calls, and webhook delivery fan-out. |
| `worker:webhook_delivery` | Outbound signed webhook HTTP deliveries, retries, and DLQ transitions. |

Only one worker holds each lease at a time, and leases are released immediately when the tick finishes (or automatically expire if a worker node crashes).
