A worldwide product catalogue on Cloudflare D1 has read replication on; a user saves a profile edit and the next page shows the old profile. Why, and how do bookmarks fix it?
answer
- each request opens a fresh session
- the nearest replica has not caught up
- consistency ends with the session
- hand getBookmark() back to the client
basics
~20 sEach request opened a new D1 session with first-unconstrained, so the next read hit a replica that had not yet applied the write. Returning session.getBookmark() to the client and passing it into withSession() makes the replica wait until it has the edit.
solid answer
~50 sThe write was forwarded to the primary and committed, but the next request started a fresh session with `withSession()` or `"first-unconstrained"`, and its first read ran on the nearest replica, which had not yet received the change. D1 promises sequential consistency only inside one session, and a session object normally lives for one Worker invocation. To carry it across requests, call `session.getBookmark()` after the write, return the bookmark in a response header or cookie, and have the next request call `env.DB.withSession(bookmark)`. A replica that is behind that bookmark waits until it has caught up before answering, so the user sees their own edit while other pages still read from nearby replicas. `"first-primary"` on every request also fixes it, but sends every session's first query to the primary and gives up most of the latency gain.
code
javascript · 32 linesexport default {
async fetch(request, env) {
// The client sends back the bookmark it received last time (an app-chosen header).
const bookmark = request.headers.get("x-d1-bookmark") || "first-unconstrained";
const session = env.DB.withSession(bookmark);
const url = new URL(request.url);
let body;
if (request.method === "POST") {
const { userId, displayName } = await request.json();
await session
.prepare(
"INSERT INTO profiles (user_id, display_name) VALUES (?, ?) " +
"ON CONFLICT (user_id) DO UPDATE SET display_name = excluded.display_name",
)
.bind(userId, displayName)
.run();
body = { saved: true };
} else {
body = await session
.prepare("SELECT display_name FROM profiles WHERE user_id = ?")
.bind(url.searchParams.get("user"))
.first();
}
const response = Response.json(body ?? { error: "not found" });
// null only when no query ran in this session
const latest = session.getBookmark();
if (latest) response.headers.set("x-d1-bookmark", latest);
return response;
},
};go deeper
Recall that a D1 session normally lives for one request, and that getBookmark() and withSession(bookmark) are how its consistency carries over to the next request.
Walk through the write on the primary, the lagging replica on the next request, and how a replica waits for the bookmark before answering.
Diagnose intermittent stale reads after writes as replica lag across sessions, fix them with a per-user bookmark round trip, and reject sleeps, retries and batch() as non-fixes.
Decide which routes need read-your-writes, which tolerate unconstrained reads, and whether first-primary's latency cost is acceptable where no bookmark exists yet.
## What actually happened D1 read replication keeps a **primary database instance** that takes all writes and **read replicas** in each D1 region that copy its changes asynchronously. The failing flow looks like this: 1. The `POST` that saves the profile opens a session with `env.DB.withSession()` (the same as `"first-unconstrained"`). Its `INSERT` or `UPDATE` is forwarded to the primary and commits. 2. The response goes back without anything that records which database version the write produced. 3. The next page load is a new request, so the Worker opens a new session, again unconstrained. Its first `SELECT` runs on the nearest replica. 4. That replica has not yet applied the write. It returns the old display name. The symptom is intermittent: when the replica happens to have caught up, or the request reaches an instance that already has the write, the page is correct. Intermittent staleness right after a write is the signature of **replica lag**. ## Why a session alone is not enough A `D1DatabaseSession` is an object created inside a Worker invocation, and it normally lives only as long as that request. Its guarantee, **sequential consistency** (monotonic reads, monotonic writes, writes follow reads, read your own writes), holds for the queries made through it. When the request ends, the session goes with it. A new session started without a bookmark starts from whatever version the instance it reaches holds. ## Bookmarks A **bookmark** is a string that identifies a version of the database, such as `00000085-0000024c-00004c6d-8e61117bf38d7adb71b934ebbf891683`. Bookmarks sort lexicographically from oldest to newest, and they are the same identifiers D1 Time Travel restores to. - `session.getBookmark()` returns the latest bookmark seen by any query in the session, and `null` when no query has run yet. - `env.DB.withSession(bookmark)` starts a session that is at least as up to date as that bookmark. - A replica that is behind the bookmark **waits** until it has caught up, then serves the query. - The bookmark returned afterwards may be newer than the one passed in, because other writes replicated in between. ## The fix Round-trip the bookmark with the client: - After the write, read `session.getBookmark()` and send it back in a response header (the name is the application's choice, such as `x-d1-bookmark`) or a cookie. - At the start of every request, read that value and pass it to `withSession()`, falling back to `"first-unconstrained"` when the client has none. - Keep one bookmark per user or browser session. It describes what that user has seen, not a global state. - Keep returning the newest bookmark on reads too, so the user never moves backwards in time on the next page. The runtime treats a blank argument to `withSession()` as `"first-unconstrained"`, so a missing or empty header does not break the request. ## The options compared | Approach | User sees own edit | Read latency for everyone else | |---|---|---| | Bookmark round trip | yes | first reads stay on nearby replicas | | `"first-primary"` on every request | yes | each session's first query crosses to the primary | | Unconstrained sessions only | not reliably | lowest | | Disable replication | yes, once replicas stop serving, up to 24 hours later | every query goes to the primary | ## What does not fix it - **Sleeping or retrying** until the edit appears only shrinks the window; replica lag has no fixed upper bound. - **Wrapping the write in `env.DB.batch()`** makes the statements one transaction on the primary; replication to replicas stays asynchronous. - **Using `ctx.waitUntil()`** extends the invocation's lifetime; it does nothing for which version a later request reads. ## Checking the fix The bug cannot be reproduced under `wrangler dev`: the local database is a single instance with no replicas, so every read already sees every write. Bookmarks are still issued locally, so the round trip itself can be tested there, but the lag only appears once deployed. - Log `meta.served_by_region` and `meta.served_by_primary` from `run()` results to see which instance answered each read. - Test from a location far from the primary; for its demo, the documentation suggests a location hint in a distant region to simulate the worst-case latency that replicas remove. - Watch for the old value after a save in an end-to-end test run against the deployed Worker, with and without the bookmark header. Other users' edits may still appear on this user's pages a little later; for a catalogue that is acceptable, and bookmarks are scoped to exactly the guarantee the scenario needs.
- Why can the bookmark returned on a read be newer than the one the client sent?The replica waits until it is at least as new as the bookmark passed in, but by then it may have applied other users' writes too. `getBookmark()` returns the latest version any query in the session saw, so it can move forward. Returning it keeps the user's next page at least that fresh.
- Where should the bookmark live between requests: a cookie, a header, or a server-side store?Wherever the next request from the same user can read it cheaply: a cookie or a header the client echoes back. A server-side store adds a lookup and, if it is eventually consistent itself, can hand back an older bookmark than the one written, which defeats the purpose.
- When is first-primary the better choice than a bookmark?When a request has no bookmark yet but must not read old data, such as a page listing records the user expects to be complete. first-primary costs one trip to the primary for the first query; later queries in that session can still use replicas.
A bookmark is like the ticket number a clerk hands you after you file a form: at any branch, you show the ticket, and the clerk there will not answer until their copy of the ledger has reached at least that number.
- Sequential consistency in D1 holds across every request from the same user automatically.
- Retrying the read after a short sleep reliably guarantees read-your-writes.
- Putting the write in env.DB.batch() commits it on the replicas synchronously.
- A replica behind the bookmark returns an error rather than waiting.
- Enabling read replication gives each user read-your-writes across requests automatically.
Assumes D1 as of 2026-10-10, where read replication and the Sessions API are a public beta opened in April 2025.