Read replication
Serve reads from D1's regional replicas with the Sessions API — one config flag, one response header, sequential consistency per client.
Cloudflare D1 can keep read-only copies of a database in every region
(ENAM, WNAM, WEUR, EEUR, APAC, OC) at no extra cost. Replicas only serve
queries made through the D1 Sessions
API;
plain binding queries always go to the primary. readReplication makes the
generated API use that session for every request-scoped feature read.
// quickback.config.ts
database: defineDatabase("cloudflare-d1", {
readReplication: true,
}),Then enable replication on the features database itself — Settings →
Enable Read Replication in the D1 dashboard, or PUT the database with
{ "read_replication": { "mode": "auto" } } through the REST API. The
compiler never flips that switch. The generated code is correct either way:
without replicas every session runs on the primary, so turning the flag on
first and replication on later is safe.
D1 only. Postgres providers reject the option; Neon's read replicas are a connection-string concern.
What the generated API does
Each request's db handle runs on a D1 session. The session constraint is
chosen by method:
| Request | Session starts | Why |
|---|---|---|
GET / HEAD carrying the bookmark header | at that bookmark | The client continues its own session: monotonic reads, read-your-writes |
GET / HEAD without the header | first-unconstrained | Nearest replica — the common case for a fresh page load |
Everything else (POST, PATCH, PUT, DELETE, actions, batch) | first-primary | Writes go to the primary anyway; starting there keeps a handler's reads after its own write fresh |
Every response carries the session's bookmark:
HTTP/1.1 200 OK
x-d1-bookmark: 0000007b-0000b26e-00001538-0c3e87bb37b3db5cc52eedb93cd3b96b
x-d1-served-by: WEUR;primary=falseA client that sends the bookmark back on its next GET gets sequential
consistency across requests: it never reads an older version of the database
than the one it last saw, and it sees its own writes. A client that ignores
the header gets eventual consistency on reads only — the same thing any
replicated database gives an un-sessioned reader — and still gets fresh
reads inside every write. All three headers (x-d1-bookmark,
x-d1-served-by, x-d1-fallback) are CORS-exposed so browser code can read
them.
x-d1-served-by is for verifying a rollout: it is set only when D1 reports
where the session ran (meta.served_by_region / served_by_primary). D1
attaches that to all() / run() / batch() results on remote databases and
never under wrangler dev — and not to raw(), which is how Drizzle runs most
selects, so a read-only request often carries no x-d1-served-by even in
production.
Echo the bookmark from your client
let bookmark: string | null = null;
async function api(path: string, init: RequestInit = {}) {
const headers = new Headers(init.headers);
if (bookmark) headers.set("x-d1-bookmark", bookmark);
const res = await fetch(`${API}${path}`, { ...init, headers, credentials: "include" });
bookmark = res.headers.get("x-d1-bookmark") ?? bookmark;
return res;
}One variable per browser tab or app session is enough. Sending a bookmark from a different session is harmless: D1 only guarantees the new session is at least as fresh as the bookmark.
Only a well-formed bookmark (three 8-hex groups and a hash group, as D1
issues them) continues a session. Any other header value is ignored and the request starts
first-unconstrained, so a stale or hand-edited header can never fail a
query.
Rename the header
readReplication: { header: "x-bookmark" },The name must be a valid HTTP header token. It is matched case-insensitively on the way in and emitted lowercase.
Replica → primary fallback
A replica may not have the row another user wrote a moment ago, so a GET
for it can come back not-found from the replica even though the primary has
it. The generated worker retries those reads once on the primary:
First response (GET / HEAD only) | Retried on the primary? |
|---|---|
404, or 403 FIREWALL_NOT_FOUND (the firewall's default errorMode: 'reveal' answer for a row it cannot see) | Yes, once |
a read continued from a client bookmark whose replica did not catch up within bookmarkWaitMs (below) | Yes, once — whatever the handler answered |
any 5xx, including 503 DB_TIMEOUT | Yes, once |
anything else (2xx, 304, other 4xx) | No |
any status, when the session started first-primary or D1 reported the primary served it | No |
any status under wrangler dev (D1 never reports where it served) | No |
The retried response carries x-d1-fallback: primary, the primary session's
bookmark, and the first attempt's x-request-id:
HTTP/1.1 200 OK
x-d1-fallback: primary
x-d1-bookmark: 0000007b-0000b26f-00000002-9b1d0e4a2f7c4c1e8d3a6b5f0c2e7d91
x-request-id: 3f0c…Details worth knowing:
- One retry, never a loop. The retry is marked inside the worker (an object identity, not a header), so no client can trigger or suppress it, and a retried request is never retried again.
- The whole request runs twice. The worker re-dispatches the request
through every middleware; Hono middleware cannot re-run downstream
handlers on its own. The retry does not count against the CRUD rate
limiter a second time; a custom
GETaction's own rate limit does count both passes. Error logs from the first pass are kept — that is how you see replica errors. - Genuine not-founds pay twice. A
GETfor a row that exists nowhere costs a replica read and a primary read. That is bounded at 2×. - Only not-found and errors. A stale list (
200with yesterday's rows) is not detected; echo the bookmark, and adopt the bookmark from realtime frames (below), to avoid it. - When D1 says nothing. Drizzle's selects return no
served_bymetadata, so after a not-found or 5xx with none, the worker asks D1 once per isolate (select 1) whether it reportsserved_byat all. Remote D1 does;wrangler devdoes not, so local development never retries.
Bounding the wait for a bookmark
A GET that carries a bookmark starts its session at that bookmark, and D1
holds the first query until the replica has caught up to it. Cloudflare
documents no bound on replica lag, so without a cap that wait lasts until
queryTimeoutMs fires — seconds,
with the fallback only after.
bookmarkWaitMs caps it. When the session's first statement has not completed
within that many milliseconds, the read is abandoned and re-served from the
primary (x-d1-fallback: primary) — never stale, and never more than about
bookmarkWaitMs slower than going to the primary directly:
database: defineDatabase("cloudflare-d1", {
queryTimeoutMs: 5000,
readReplication: { bookmarkWaitMs: 300 }, // the default
}),- Default 300 ms, clamped to
queryTimeoutMswhen that is lower. An explicit value must be a positive integer no larger thanqueryTimeoutMs. - Only bookmark reads.
first-unconstrainedreads (no bookmark) and everything on the primary keep the normalqueryTimeoutMs. - Only the first statement. Once one statement on the session has
answered, the replica is at least at the bookmark; later statements in the
same request are bounded by
queryTimeoutMsalone. The cap covers every statement form, including theraw()reads Drizzle uses for selects andbatch(). - No client-visible error. The abandoned replica read never reaches the
client when the primary answers; if the primary retry also fails, the
client gets that failure (
503 DB_TIMEOUTand so on) as usual. The worker logs aD1_REPLICA_WAITwarning each time, so you can count them in Workers Logs. A generated request diagnostic whose cause is the abandoned read logs as ad1.replica_lagwarning instead of its usual error event (see tenant request diagnostics): it is latency, not a failure, so it should not page as an error.
Tuning. Set it a little above your observed p95 replica lag. Too low and
reads that would have been served by a replica a moment later go to the
primary instead (correct, just slower and more primary load); too high and a
lagging replica costs that much latency before the fallback. Count
D1_REPLICA_WAIT events and x-d1-fallback responses to judge it.
Realtime frames carry the writer's bookmark
A client that refetches over HTTP when a realtime frame arrives holds its
own bookmark, which predates the write that caused the frame — so the
refetch can land on a replica that has not seen that write yet. With
readReplication on and realtime enabled, every
postgres_changes, broadcast and view_changes frame sent while handling a
request carries that request's D1 bookmark, read when the frame is sent (after
the write; frames sent from waitUntil after the response included):
{
"specversion": "1.0",
"type": "dev.quickback.my-app.projects.insert",
"qbframe": "postgres_changes",
"qbd1bookmark": "0000007b-0000b26f-00000002-9b1d0e4a2f7c4c1e8d3a6b5f0c2e7d91",
"data": { "table": "projects", "eventType": "INSERT", "new": { "id": "prj_…" } }
}qbd1bookmark is a CloudEvents extension attribute, named like the other
qb* attributes (CloudEvents requires lowercase alphanumeric names). It is
absent on frames sent outside a request — schedules, queues, email handlers,
Durable Objects — and on projects without readReplication. It is never row
data: masking and audience targeting are unchanged.
On any frame carrying qbd1bookmark, set your stored bookmark to the
lexicographic max of the two before refetching. D1 bookmarks sort
oldest-to-newest as plain strings:
socket.addEventListener("message", (event) => {
const frame = JSON.parse(event.data);
const theirs = frame.qbd1bookmark;
if (typeof theirs === "string" && (!bookmark || theirs > bookmark)) bookmark = theirs;
// …then refetch with api(), which sends the adopted bookmark.
});Server code can read the current request's bookmark the same way the realtime
helper does: currentD1Bookmark() from src/db returns it (or null outside
a request).
What stays on the primary
Only the per-request features db rides the session. These keep their own
primary handles, exactly as before:
- the auth database (Better Auth's adapter and
c.get('authDb')) — session and membership rows must never be read from a lagging replica - the audit and webhooks databases
- schedules, queues and email handlers — no request, no client, no bookmark
- Durable Objects and anything that builds its own
drizzle(env.DB)
A read that must be fresh regardless of the client — polling a payment
status, an OTP flow — belongs in an action or a non-GET route, which starts
on the primary.
Replica lag
Replication is asynchronous and a first-unconstrained read may be
arbitrarily old. D1 bounds it per session, not globally: the session waits
until a replica has caught up to the bookmark you passed. That is why writes
start first-primary and why the bookmark is worth echoing.
With queryTimeoutMs set, the
deadline wraps the session as well — a replica that takes too long to catch up
to a bookmark answers 503 DB_TIMEOUT like any other slow read.
Query diagnostics
With query diagnostics
on, the observation layer sits in the same wrapper chain as the deadline,
outside the session adapter. Sampled events report region and primary
whenever D1 returns them. Diagnostics never probe a replica, retry a statement
or change bookmarks or the primary-fallback policy.
Related
- Using D1 — queries, dual-DB mode, backend stalls
- Database options — every
defineDatabase("cloudflare-d1")option - Cloudflare: Global read replication