Skip to content
Active Record
Esc
↑↓navigate↵open⌘Jpreview
On this page

Read replicas

Keep each user’s reads at least as new as their own writes, with D1 read replication.

Opening a Session for each request

Wrap each request in withSession, passing it the request and your D1 binding:

import { withSession } from "@forestfuture/active-record/d1";

// src/worker.ts: each request reads at least as new as this browser's last write, from any replica.
export default {
  fetch: (request, env) => withSession(request, env.DB, () => handle(request)),
} satisfies ExportedHandler<Env>;

Every query inside it goes through the request’s Session. That includes uniqueness checks, association loads, preloads, and batches. Records loaded there keep using it.

withSession keeps the Session’s bookmark in a d1-bookmark cookie. The user’s next request sends it back, and its Session starts from there. If your handler throws, the error reaches you unchanged and no cookie is set.

Carrying the bookmark in a header

If your clients aren’t browsers, carry the bookmark in a header instead:

import { withSession } from "@forestfuture/active-record/d1";

// An API's clients send back the x-d1-bookmark header of the response before.
export const api = {
  fetch: (request, env) =>
    withSession(request, env.DB, { header: "x-d1-bookmark" }, () => handle(request)),
} satisfies ExportedHandler<Env>;

Each response has the bookmark in its x-d1-bookmark header. Clients send that header with their next request.

Choosing where a Session starts

A request without a bookmark starts at the nearest instance. To start it at the primary instead, pass { start: "first-primary" }. A request with a bookmark always starts from its bookmark. If D1 can’t use the bookmark, the Session starts from start instead. This happens when someone changes the cookie.

connect(env.DB, { session }) takes D1’s own values:

session The first query goes to
"first-unconstrained" The nearest instance, primary or replica. The fastest, but may read slightly old data.
"first-primary" The primary, so it sees every write made so far.
A bookmark An instance at least as new as the moment the bookmark was taken.

After the first query, each query reads data at least as new as the one before, including the request’s own writes.

  • Your handler gets the request’s database as its argument. Use it for db.batch(…) and db.model(…).
  • To log the request’s queries, pass onQuery to withSession, as you would to connect.
  • To carry the bookmark yourself, use db.bookmark(). It’s the Session’s latest bookmark. It’s null before the first query, and throws NoSession on a database opened without a Session.
  • To mix the primary and replicas, open two databases, and use db.model(…) with each.

Last updated on