Skip to content
AnswerWell geo Documentation

Research · 8 min read · Answerwell

Read Replication, Sessions API, Bookmarks, and Query Latency

How Cloudflare D1 read replication, Sessions API, bookmarks, retries, and API latency changes work in Workers, and how to enable and verify them.

This page summarizes Cloudflare D1 documentation on read replication, the D1 Sessions API, bookmarks, automatic read-only query retries, and Worker vs REST API latency improvements. Together these address slow global reads, stale data after writes, and transient read failures—common questions when running SQLite at the edge behind Cloudflare Workers.

D1 read replication: what it is and when to use it

Section titled “D1 read replication: what it is and when to use it”

D1 read replication adds read replicas—read-only copies of the primary database instance—in multiple regions so reads can run closer to users and spread read load.

D1 read replication is available in public beta to help lower average latency and increase overall throughput for read-heavy applications like e-commerce websites or content management tools.

— Cloudflare, D1 Read Replication Public Beta

Without read replication, D1 routes all queries to a single primary database instance in one location; users far from that region pay extra round-trip time. With replication enabled, D1 still sends all writes to the primary, but eligible reads can be served from a nearby replica—see Global read replication.

Instance Writes Reads
Primary database instance Served on primary Can serve reads
Read replica Forwarded to primary Served from replica copy

Replicas are asynchronously updated, so replica lag can make a naïve read-after-write look stale. Read replication is aimed at read-heavy workloads (catalogs, CMS, storefront listings), not as a substitute for careful write/read ordering without Sessions.

Sessions API: required for read replication in Workers

Section titled “Sessions API: required for read replication in Workers”

Sessions API is how Workers use read replicas. Without it, every query still hits only the primary—even if read replication is enabled on the database.

To use read replication, you must use the D1 Sessions API, otherwise all queries will continue to be executed only by the primary database.

— Cloudflare, Global read replication

A session groups queries that belong to one logical client flow (for example, one browser session). Within a session, D1 keeps sequential consistency so reads do not “go backward in time” relative to earlier queries in that session, even when different replicas serve them.

Start a session with env.DB.withSession(...) on a binding such as env.DB; the call returns a D1DatabaseSession with prepare(), batch(), and getBookmark()—see withSession().

withSession() options: latency vs freshness

Section titled “withSession() options: latency vs freshness”

The first argument to withSession() controls where the first query in the session may run; later queries in the same session stay sequentially consistent (D1 Database).

Parameter First query routes to Typical use
first-unconstrained (default) Primary or any replica Minimize latency when latest data on the first query is optional
first-primary Primary only Start from the freshest primary state
Bookmark string At least as fresh as that bookmark Continue a prior session (cookie/header)
const session = env.DB.withSession("first-primary");
const result = await session
.prepare(`SELECT * FROM Customers WHERE CompanyName = 'Bs Beverages'`)
.run();

withSession() with no argument is equivalent to withSession("first-unconstrained") (Start a session without constraints).

Bookmarks: carry consistency across HTTP requests

Section titled “Bookmarks: carry consistency across HTTP requests”

A bookmark marks database state at a point in time. Bookmarks are lexicographically sortable (oldest to newest) and are used by Sessions API for consistency; the same bookmark concept also powers D1 Time Travel for point-in-time restore—a separate operational use from session headers.

A bookmark represents the state of a database at a specific point in time.

— Cloudflare, Glossary

Pattern from the read-replication changelog: read a bookmark from the client, open a session, run queries, return an updated bookmark.

const bookmark = request.headers.get("x-d1-bookmark") ?? "first-unconstrained";
const session = env.DB.withSession(bookmark);
const result = await session
.prepare(`SELECT * FROM Customers WHERE CompanyName = 'Bs Beverages'`)
.run();
response.headers.set("x-d1-bookmark", session.getBookmark() ?? "");

After writes, storing session.getBookmark() (HTTP header, cookie, etc.) lets the next request read from a version at least as up-to-date as that bookmark (Start a session from previous context). The e-commerce read replication tutorial uses cookies (product_bookmark) the same way.

Sequential consistency without “read my stale replica”

Section titled “Sequential consistency without “read my stale replica””

Without a session framework, a write acknowledged on the primary can be followed by a read on a replica that has not caught up—results look inconsistent. With Sessions API, the replica waits until it is at least as up-to-date as the bookmark attached to the read (With Sessions API).

D1 read replication offers sequential consistency. D1 creates a global order of all operations which have taken place on the database, and can identify the latest version of the database that a query has seen, using bookmarks.

— Cloudflare, Sessions API provides sequential consistency

Properties called out in the docs include monotonic reads, read my own writes (within the session model), and related ordering guarantees for that session’s query sequence.

Enable read replication: dashboard, REST API, and replica locations

Section titled “Enable read replication: dashboard, REST API, and replica locations”

Read replicas are created and scaled by Cloudflare—currently about one per supported D1 region, activated by query traffic, with no extra charge for the replicas themselves (D1 Read Replication Public Beta).

Dashboard: D1 → select database → Settings → Enable Read Replication (Enable read replication).

REST API: PUT the database with read_replication.mode: "auto"; use "disabled" to turn it off (replicas may take up to 24 hours to stop serving) (Enable read replication via REST API). GET the database and inspect read_replication.mode ("auto" vs "disabled").

Supported replica region codes documented today include ENAM, WNAM, WEUR, EEUR, APAC, and OC—subject to change (Read replica locations). With a jurisdiction (eu or fedramp), replicas stay inside that jurisdiction (Read replica locations, changelog D1 fields).

Two separate improvements matter depending on how you call D1.

Users making D1 requests via the Workers API can see up to a 60% end-to-end latency improvement due to the removal of redundant network round trips needed for each request to a D1 database.

— Cloudflare, 40-60% Faster D1 Worker API Requests

Reported p50/p90/p95 latencies are service-wide references, not a guarantee for every app (same entry). Gains are largest for cross-region access; D1 location hints can influence where the primary lives (Data location). Workers placement explains co-locating the Worker with the database when the Worker itself makes many DB round trips—complementary to read replication.

Users using Cloudflare’s REST API to query their D1 database can see lower end-to-end request latency now that D1 authentication is performed at the closest Cloudflare network data center that received the request.

— Cloudflare, 50-500ms Faster D1 REST API Requests

Improvements are roughly 50–500 ms, depend on client and database location, and apply only to the REST API. Non-US callers often see more benefit. Query endpoints (/query, /raw) improve most; control plane calls (create/delete database) still hit core datacenters for metadata (same post).

Common conclusion: Both paths reduced redundant networking; Workers bindings benefit from fewer round trips per query, while REST gained especially from edge authentication. Read replication and Sessions further reduce read latency for global users on Workers; REST callers get authentication latency wins but not Sessions-based replica routing yet.

Automatic retries for read-only D1 queries

Section titled “Automatic retries for read-only D1 queries”

D1 can retry read-only queries up to two times on retryable failures. Check meta.total_attempts on the result (D1 automatically retries read-only queries).

At the moment, only read-only queries are retried, that is, queries containing only the following SQLite keywords: SELECT, EXPLAIN, WITH.

— Cloudflare, D1 automatically retries read-only queries

Retry success rates for eligible read errors range from about 5% to 95% depending on error type and duration. Write queries are not auto-retried; Cloudflare recommends application-level retries for idempotent non-read-only operations (same post).

Safety: after each attempt, D1 checks whether the database changed; if a retry caused writes, the query is rolled back—so automatic retries aim to avoid side effects even if read-only detection misclassifies a query (same post).

Workers tracing exposes cloudflare.d1.response.total_attempts on D1 spans (Spans and attributes).

Use result meta fields to see routing with or without read replication (Check where D1 request was processed):

  • served_by_region — region that served the query
  • served_by_primary — whether the primary served it

Changelog-related fields also include served_by_colo (colo that handled the query) on D1 responses (D1 product changelog). Under npx wrangler dev, served_by_region and served_by_primary are undefined locally.

D1 trace attributes also include cloudflare.d1.response.served_by_region, cloudflare.d1.response.served_by_primary, and bookmark fields on d1 run / batch spans (Spans and attributes).

  1. Enabling read replication but calling env.DB.prepare() directly — replicas are not used; switch to withSession() for replica-eligible reads (Guidance).
  2. Expecting REST API Sessions — replication consistency features require the Worker binding today (Known limitations).
  3. Using first-unconstrained right after a write without passing a bookmark — the first read in a new session may prefer latency over the freshest row; pass getBookmark() from the write response path (e-commerce tutorial).
  4. Assuming auto-retries cover INSERT/UPDATE — only SELECT/EXPLAIN/WITH-style read-only detection is retried; keep idempotent retry logic for writes (2025-09-11 release notes).
  5. Disabling replication and expecting instant behavior change — replica teardown can take up to 24 hours; Sessions API remains safe to run (Disable read replication via REST API).
  1. In the Cloudflare dashboard, open D1 → your database → Settings and confirm Read Replication is enabled, or GET the database via the REST check endpoint and verify read_replication.mode is "auto".

  2. Deploy a Worker that uses env.DB.withSession(bookmark) and logs result.meta.served_by_region and result.meta.served_by_primary (Check where D1 request was processed); confirm read traffic sometimes shows served_by_primary: false when replication is on.

  3. Exercise a write then a read in the same logical session using a stored bookmark (header or cookie pattern from D1 Read Replication Public Beta) and verify the read sees the write.

  4. On a failing read-only query, inspect meta.total_attempts or D1 trace cloudflare.d1.response.total_attempts (D1 automatically retries read-only queries, Spans and attributes).

  5. You can check automatically in Answerwell (our tool): https://answerwell.org/workspace

If something on this page is wrong or unclear, email yimasynthetic@gmail.com with the page URL and the exact statement you are asking about.