Read path: D1 read replication + edge caching; retire the KV SWR layer if it measures equal #555
Closed
tombeckenham opened this issue ·1 comment
Today#
- Schema routes (
/v1/schemas/...,/v1/openapi/{p}) go throughswr()insrc/server/cache.ts. The response body is in KV and its freshness is in D1cache_meta. That D1 lookup runs on every request, so even a KV hit waits on D1. - Catalog and status (
/v1/models,/v1/providers,/v1/status) query D1 directly on every request, against the single primary. - Dead write:
sync.ts:514writesschema:<hash>blobs to KV, but nothing reads them (getByHashhas no callers). Schema reads come fromschema_versions.schemain D1. - Data only changes when the crons run (15-minute poll, daily syncs). Reads vastly outnumber writes, and the writes are rare.
Proposal#
- Turn on D1 read replication and use
withSession('first-unconstrained')for public GET reads. AgetDb(env, { replica: true })option keeps this in one place. Auth (better-auth, agent JWT jti checks), admin, subscriptions, the crons and webhooks stay on the primary.- Check: are single-use jtis consumed with a unique insert (goes to the primary, safe), or with a read-then-write that a lagging replica could let through twice?
- Edge-cache the hot GETs.
http-cache.tsalready sets ETags. AddCache-Control: public, s-maxage=…for catalog and schema reads, matched to the cron cadence. Versioned schema reads (?version=<hash>) never change and can be cached long. - Measure, then simplify. Compare p50 and p95 for a schema route through
swr()against the same route with replica + edge cache. If they're about the same, deleteswr()andcache_meta's freshness role, so there's one consistency model instead of two. - Remove the dead
schema:<hash>KV write insync.ts(andputByHash/getByHashif they're still unused).
KV stays for what fits it: the rate-limit counters, which expire on their own, and the docs cache used by the crons (cachedDocs, google-docs.ts, nvidia.ts).
Why not everything in KV#
/v1/models filters and search, the paginated /v1/changes cursor, the atomic db.batch in sync, joins (sameAs, schema versions) and auth all need SQL and reads that see the latest write.
Do this after #554, so the replicas copy the US primary.
tombeckenham added labelsenhancement
tombeckenham closed this
Sign in to join this conversation.
Read replication is now enabled (
read_replication.mode: auto) on the current production D1 (modelschemas, primary in OC). #566 is deployed, so public GETs (getDb(env, { replica: true })) can now be served by replicas, and the catalog comes back from the edge cache (cf-cache-status: HIT). Auth, admin, subscriptions, crons, webhooks and the changes feed stay on the primary.Replication was turned on before #554, so for now the replicas copy the OC primary. The replacement database for the TanStack account will need replication enabled again.