feat(cache): in-process catalogue cache with version invalidation (#22) #117

Merged
amiryahaya merged 9 commits from feat/22-catalog-cache into main 2026-10-28 12:39:38 +01:00
Owner

What

A per-node in-process response cache in front of 17 public catalogue GETs, invalidated within seconds by a PostgreSQL sequence that admin writes bump (#22).

  • api/internal/cache: bounded map (1,000 entries, 256 KiB per body, 60 s TTL), a Wrap middleware that stores finished 200 responses of opted-in routes and replays them (ETag/304 identical to the live handler, Age header on hits), and a watcher that polls the version every 2 s and clears the cache when it moves.
  • Migration 0031: sequence catalog_cache_version and a statement-level trigger (INSERT/UPDATE/DELETE/TRUNCATE) on the 18 tables the cached routes read. A sequence, not a counter row, so admin transactions cannot deadlock on it.
  • app.CachedRoutes (one list of 17 patterns) attached through httpapi.WithRouteMiddleware; no module's RegisterRoutes changed. API mode only; KWS_CACHE=off serves live.
  • ADR 0026 and a CLAUDE.md Cache section.
  • No OpenAPI change, no new dependency. Never cached: /v1/admin, /v1/me, seat availability, sales, wallets, payments, tickets, image bytes.

Why

Groundwork for the 1k-user target (docs/02 section 6 rule 4): public catalogue reads that miss Cloudflare and Caddy should not reach the database, and a second node must refresh after an admin edit.

Verification

  • make cover: 91.1% (minimum 80%; internal/cache and internal/cache/pgstore 100%); make lint 0 issues; make contract ok; go test -race -count=1 ./... ok; client generation unchanged.
  • A restricted-role test proves every cached route reads only tracked tables; a freshness test proves an admin price edit shows after one poll; a trigger test checks all 18 tables for events and enabled state.
  • Dual-pass review: Pass 1 (ponytail) no Must fix; Pass 2 (correctness) one Important (a lost sequence grant would silently disable invalidation: fixed, the read now fails loudly) plus minors; one fix wave, scoped re-review approved, Ponytail clear.

Rulings I made

  1. Whole-response cache in a middleware (not per-store caching).
  2. Trigger-based invalidation, not handler code; one global version.
  3. Sequence instead of a counter row (no row lock, no deadlock).
  4. Plain mutex-guarded map; no ristretto/otter, no single-flight.
  5. Fix wave: generation counter against stale write-back, one extra clear after a change, Age header on hits, escaped-path key, direct sequence read.
  6. Skipped: evicting an arbitrary entry when full (a junk-key flood can switch caching off for up to 60 s; revisit with #61); refusing no-store/private responses (none are sent today).
  7. A narrow gosec G705 exclusion for internal/cache/middleware.go in api/.golangci.yml (kept by the owner's decision; a hook here blocks inline nolint).

Owner please check ([verify] in ADR 0026)

  • Small version now, 60 s TTL; prices change at the Nairobi midnight and rates at any instant with no write, so they can be stale up to the TTL.
  • No single-flight on a cold cache.
  • The sequence is readable by PUBLIC (value only); the trigger function is SECURITY DEFINER with a pinned search_path. Keep the grant through restores (pg_restore -x would make reads fail loudly, not silently).

Not verified

Real load (#61); Cloudflare/Caddy behaviour with the Age header; a two-node setup; the restricted-role test needs a superuser test DB user (the CI postgres image and the dev DB are).

🤖 Generated with Claude Code

## What A per-node in-process response cache in front of 17 public catalogue GETs, invalidated within seconds by a PostgreSQL sequence that admin writes bump (#22). - `api/internal/cache`: bounded map (1,000 entries, 256 KiB per body, 60 s TTL), a `Wrap` middleware that stores finished 200 responses of opted-in routes and replays them (ETag/304 identical to the live handler, `Age` header on hits), and a watcher that polls the version every 2 s and clears the cache when it moves. - Migration 0031: sequence `catalog_cache_version` and a statement-level trigger (INSERT/UPDATE/DELETE/TRUNCATE) on the 18 tables the cached routes read. A sequence, not a counter row, so admin transactions cannot deadlock on it. - `app.CachedRoutes` (one list of 17 patterns) attached through `httpapi.WithRouteMiddleware`; no module's `RegisterRoutes` changed. API mode only; `KWS_CACHE=off` serves live. - ADR 0026 and a CLAUDE.md Cache section. - No OpenAPI change, no new dependency. Never cached: `/v1/admin`, `/v1/me`, seat availability, sales, wallets, payments, tickets, image bytes. ## Why Groundwork for the 1k-user target (docs/02 section 6 rule 4): public catalogue reads that miss Cloudflare and Caddy should not reach the database, and a second node must refresh after an admin edit. ## Verification - `make cover`: **91.1%** (minimum 80%; `internal/cache` and `internal/cache/pgstore` 100%); `make lint` 0 issues; `make contract` ok; `go test -race -count=1 ./...` ok; client generation unchanged. - A restricted-role test proves every cached route reads only tracked tables; a freshness test proves an admin price edit shows after one poll; a trigger test checks all 18 tables for events and enabled state. - Dual-pass review: Pass 1 (ponytail) no Must fix; Pass 2 (correctness) one Important (a lost sequence grant would silently disable invalidation: fixed, the read now fails loudly) plus minors; one fix wave, scoped re-review approved, Ponytail clear. ## Rulings I made 1. Whole-response cache in a middleware (not per-store caching). 2. Trigger-based invalidation, not handler code; one global version. 3. Sequence instead of a counter row (no row lock, no deadlock). 4. Plain mutex-guarded map; no ristretto/otter, no single-flight. 5. Fix wave: generation counter against stale write-back, one extra clear after a change, `Age` header on hits, escaped-path key, direct sequence read. 6. Skipped: evicting an arbitrary entry when full (a junk-key flood can switch caching off for up to 60 s; revisit with #61); refusing `no-store`/`private` responses (none are sent today). 7. A narrow gosec G705 exclusion for `internal/cache/middleware.go` in `api/.golangci.yml` (kept by the owner's decision; a hook here blocks inline `nolint`). ## Owner please check ([verify] in ADR 0026) - Small version now, 60 s TTL; prices change at the Nairobi midnight and rates at any instant with no write, so they can be stale up to the TTL. - No single-flight on a cold cache. - The sequence is readable by PUBLIC (value only); the trigger function is SECURITY DEFINER with a pinned search_path. Keep the grant through restores (`pg_restore -x` would make reads fail loudly, not silently). ## Not verified Real load (#61); Cloudflare/Caddy behaviour with the `Age` header; a two-node setup; the restricted-role test needs a superuser test DB user (the CI postgres image and the dev DB are). 🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Migration 0031 adds the catalog_cache_version sequence and one
statement-level trigger per table a cached public route reads;
cache/pgstore reads last_value (0 when never used). The tracked list is
pgstore.Tables, and a test checks the triggers match it exactly.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
app.CachedRoutes lists the 17 public GET patterns served from the
in-process cache; httpapi.WithRouteMiddleware wraps them by mux pattern
without changing any module's RegisterRoutes. serveAPI creates the cache
and starts cache.Watch (2 s poll) in api mode only; KWS_CACHE=off serves
live. NewAPIHandler takes the cache (nil = live; the contract tests pass nil).

Tests: every cached route runs as a role with SELECT on cachepgstore.Tables
only (an untracked table fails it), and repeats after a full REVOKE still
answer 200 with the same body; admin writes to parks, prices, rates, forms,
a lookup and a media list are served after one poll; Run caches and
KWS_CACHE=off does not.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Wrap no longer stores a 200 that sets Set-Cookie or Vary. A full cache
skips the purge scan until its earliest entry can have expired. Tests for
an empty 200 without an ETag, TRUNCATE bumping the version, and a bad
bearer token on every cached route; drop a racy Len check and log role
cleanup errors.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
- Read the version sequence relation directly so a lost grant fails with
  "permission denied" instead of reading 0 forever.
- Watcher: first read clears, extra clear on the tick after a change,
  each poll bounded by the interval.
- Cache generation: a miss that began before a Clear is not stored.
- Age header on hits (also on 304); key on the escaped path.
- Trigger test asserts events and enabled state; trims redundant tests;
  drop Entry.Status and the body clone.
- ADR 0026, spec and CLAUDE.md: rate/price time behaviour, max-age values,
  new behaviour, grant must survive restores, accepted gaps.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
docs(cache): align comments and spec with the review fixes (#22)
All checks were successful
ci / changes (pull_request) Successful in 10s
ci / api (pull_request) Successful in 12m5s
ci / clients (pull_request) Has been skipped
ci / ci-gate (pull_request) Successful in 5s
5331394ffe
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Sign in to join this conversation.
No reviewers
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
primatekuntech/kws!117
No description provided.