skip to content

In Cloudflare D1, how does env.DB.withSession() let a Worker read from read replicas, and what do first-primary and first-unconstrained change?

level: middleimportance: should knowfreq 42%

answer

  1. replication alone moves no query
  2. a session object, not the binding
  3. where the first query may land
  4. default argument equals first-unconstrained

basics

~20 s

D1 serves reads from replicas only for queries made through a session from withSession(); queries on the plain binding all run on the primary. first-unconstrained, the default, lets the first query hit any instance; first-primary sends it to the primary.

solid answer

~40 s

Turning on read replication for a database (dashboard **Settings**, or the REST API with `read_replication.mode` set to `"auto"`) currently creates read-only copies in every supported D1 region, but queries reach them only through the Sessions API. `env.DB.withSession(arg)` returns a `D1DatabaseSession` with `prepare()`, `batch()` and `getBookmark()`. With no argument it behaves like `"first-unconstrained"`: the first query may run on the nearest replica, which can lag the primary. `"first-primary"` sends the first query to the primary, so the session starts from the latest committed data. After that, queries in either session may use replicas and stay sequentially consistent, and writes are always forwarded to the primary. Code that keeps calling `env.DB.prepare()` directly keeps every query on the primary even with replication on.

code

javascript · 20 lines
javascript
export default {
  async fetch(request, env) {
    const sku = new URL(request.url).searchParams.get("sku");

    // A catalogue page can start on any instance: the nearest replica is fine.
    const session = env.DB.withSession("first-unconstrained");

    const { results, meta } = await session
      .prepare("SELECT sku, title, price_cents FROM products WHERE sku = ?")
      .bind(sku)
      .run();

    // Undefined under wrangler dev; set on every remote D1 query.
    console.log({ region: meta.served_by_region, primary: meta.served_by_primary });

    return Response.json(results[0] ?? { error: "not found" }, {
      status: results.length ? 200 : 404,
    });
  },
};

go deeper

for a junior

Recall that only queries made through a session from withSession() can be served by D1 read replicas, and that the default session argument is first-unconstrained.

for a middle

Explain what each withSession() argument changes about the first query only, why writes always reach the primary, and how a session keeps later reads sequentially consistent.

for a senior

Show you would verify replica use with served_by_region and served_by_primary, ship Sessions API code before flipping the setting, and pick first-primary only where a request must start fresh.

for a principal

Weigh latency gains against the beta status and the per-session consistency boundary, and set a team rule for which routes may start unconstrained.

## Primary instance and read replicas Without read replication, every D1 query, read or write, runs on one **primary database instance** in one location, so a user far from it pays the network round trip on every query. With read replication enabled, D1 also runs **read replicas**: read-only copies that receive the primary's changes **asynchronously**. At present D1 creates one in every supported region (ENAM, WNAM, WEUR, EEUR, APAC and OC, the primary's region included), and Cloudflare may change those locations. A database created inside a jurisdiction keeps its replicas inside that jurisdiction. - A replica serves reads from its own copy of the data. - A replica forwards any write it receives to the primary. - A replica can be arbitrarily far behind the primary at a given moment; that delay is the **replica lag**. ## Turning replication on Replication is a setting of the database, not of a Worker: 1. In the dashboard, open the D1 database, then **Settings** > **Enable Read Replication**. 2. Through the REST API, send a `PUT` to the database with `{"read_replication": {"mode": "auto"}}` using a token with D1 edit permission; `"mode": "disabled"` turns it off again. `wrangler d1 info <database>` prints `read_replication.mode`, so a script can check the state. There is no Wrangler configuration key that enables it. Disabling takes up to 24 hours before replicas stop serving, and code written with the Sessions API keeps working on a database without replication, so the code can ship before the setting flips. ## The Sessions API Enabling replication does not move a single query on its own. Queries made with `env.DB.prepare()` or `env.DB.batch()` directly on the binding keep running on the primary. Only a **session** can use replicas: ```js const session = env.DB.withSession("first-unconstrained"); const { results } = await session.prepare("SELECT * FROM products WHERE sku = ?").bind(sku).run(); ``` `withSession()` is synchronous and returns a `D1DatabaseSession` that offers `prepare()`, `batch()` and `getBookmark()`. Its argument decides only where the **first** query of the session may run: | Argument | First query runs on | Fits | |---|---|---| | none, or `"first-unconstrained"` | any instance, the nearest replica included | pages that tolerate slightly older data, such as a catalogue listing | | `"first-primary"` | the primary | a session that must start from the latest committed data | | a bookmark from `getBookmark()` | any instance at least as new as that bookmark | continuing an earlier session, such as the same user's next request | After the first query, every later query in the session may be served by any instance that has caught up to the session's latest bookmark. ## What a session guarantees D1 promises **sequential consistency** inside a session. It attaches a **bookmark** (an identifier of a database version) to each query, and an instance that is behind that bookmark waits until it catches up before answering. Inside one session that gives: - **Monotonic reads**: a later read never sees an older version than an earlier read. - **Monotonic writes**: two writes are observed in the order they were made. - **Writes follow reads**: a write is based on the value just read. - **Read your own writes**: a read after a write sees that write. The guarantee covers one session. A new session started with `"first-unconstrained"` knows nothing of writes made in another session, which is why an application hands bookmarks from one request to the next when a user must see their own change. ## Choosing the argument per route The argument is a per-request decision, so a Worker can mix them: - A product listing or search page can start with `"first-unconstrained"`: a few seconds of lag costs nothing, and the nearest replica answers. - A page that must reflect every committed change, such as an order history the user expects to be complete, can start with `"first-primary"`. - A request that follows the user's own write starts from the bookmark that write produced, so it sees the change without paying a trip to the primary when a nearby replica has already caught up. ## Seeing where a query ran The `meta` object of a `D1Result` from `run()` or `all()` carries `served_by_region` and `served_by_primary`. They are present on every remote D1 query, with or without replication or sessions, and `undefined` under `wrangler dev`, whose local database has no replicas. The dashboard also breaks database metrics down by the region that served them. ## Cost and status Replicas cost nothing extra: billing stays on `rows_read` and `rows_written`. As of 2026-10-10, read replication is a **public beta** (opened in April 2025), and the Sessions API is available only through the Worker binding, not through the REST API.

  • Does a session started with first-unconstrained send its writes to a replica?
    No. A replica forwards every write to the primary, whatever the session's argument. The argument only decides where the first query may run. After a write, the session's bookmark reflects the primary's new state, so later reads in the same session wait for an instance that has applied it.
  • How would you confirm in production that replicas are serving traffic?
    Log `meta.served_by_region` and `meta.served_by_primary` from `run()` results, or open the database's metrics in the dashboard, which split queries by serving region. Under `wrangler dev` both fields are `undefined`, because the local database has no replicas, so the check needs a deployed Worker.
  • Is it safe to deploy withSession() code before enabling replication?
    Yes. The Sessions API works on a database without replication; all queries simply run on the primary. That lets the code ship first and the setting flip later, and it means disabling replication, which takes up to 24 hours to take effect, needs no code change either.

  • Enabling read replication makes existing env.DB.prepare() calls use replicas automatically.
  • first-primary keeps every query of the session on the primary.
  • Writes made through a session can be committed on a nearby replica.
  • Read replication is enabled with a key in the Wrangler configuration file.
  • Replicas are billed as extra storage for each region.

Assumes D1 as of 2026-10-10: read replication is a public beta since April 2025, and the Sessions API exists only on the Worker binding.