Skip to content

feat: make D1 replicas opt-in as safer default and add support for Sessions API to mitigate stale data returned from replicas - #813

Merged
kossnocorp merged 20 commits into
mainfrom
fix/783-d1-bookmark
Nov 17, 2026
Merged

kossnocorp merged 20 commits into
mainfrom
fix/783-d1-bookmark

Conversation

@kossnocorp

@kossnocorp kossnocorp commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

This PR closes #783.

It adds two new primitives into D1 void/db that utilize D1 Session API:

  • getBookmark - returns the current session bookmark
  • setSession - starts a new session from a previous bookmark.

Using these allow to solve the D1 Replicas problem in the scenario read OLD -> write NEW -> read OLD and ensure sequential consistency.

It also makes replicas opt-in and adds a new config database.readReplication to enable/disable the feature:

import { defineConfig } from 'void/config';

export default defineConfig({
  database: { readReplication: true },
});

See guides for more information and usage examples:

TL;DR;

To utilize Sessions API the user has to create a middleware:

// middleware/01.database.ts
import { getCookie, setCookie } from 'hono/cookie';
import { defineMiddleware } from 'void';
import { getBookmark, setSession } from 'void/db';

export default defineMiddleware(async (c, next) => {
  const incoming = c.req.header('X-DB-Bookmark');
  setSession(!incoming ? 'first-unconstrained' : { bookmark: incoming });
  await next();

  const bookmark = getBookmark();
  if (bookmark) {
    setCookie(c, 'db-bookmark', bookmark, {
      httpOnly: true,
      secure: new URL(c.req.url).protocol === 'https:',
      sameSite: 'Lax',
      path: '/',
    });
  }
  c.header('Cache-Control', 'private, no-store');
});

To make it work with client requests, instead of the cookie (or along with the cookie transport), the devs should use a header, e.g., X-DB-Bookmark and make requests through a wrapper that sets the bookmark.

Show the disabling replicas pitch

Why disabling replicas?

TL;DR; replicas are not safe and might result in support tickets, bugs and security issues when enable unknowingly.

Enabling them by default creates two problems not present in a default D1 setup and not common in other environments:

  • User might see a stale data right after they perform a write request.

  • User might see old data after seeing a new one.

  • An action triggering an account suspension might not propagate the account state and allow already suspended account to perform an action they should not be able. See Avoid stale reads with a primary-first session.

While the first two are annoyances and just a source of support requests, the last one is a security issue.

The fact that we enable replicas by default is hidden in the documentation and the user, even experienced with D1, could get caught by surprise and deploy unsafe code unknowingly.

Making it opt-in would allow devs that want/need replicas to understand cons and decide if they want it. Those who decide to opt-in will keep in mind these nuances and work around them. If they need the advantage that replicas provide, they will be happy to use said APIs regardless how awkward they are and how many docs they have to read.

For some apps it would be completely normal, but not for all.

Why not incorporate a bulletproof solution into Void?

The problem is that every query could produce fresh bookmark, even a read. So we have to track all request bookmarks and resolve the newest one.

The single cookie approach described in the guide breaks with multiple requests where a newer request could overwrite a fresh bookmark with an older one (i.e. dashboard).

So we'll have to track every query bookmark and store each in a separate cookie, so a middleware could resolve the freshest one. It might lead to hitting server/browser limits on the cookies number and break. Not to mention overhead of carrying these cookies with every request.

A built-in multi-cookie solution could work out and be a good default middleware for users that opt-in and ok with a possibility that the describe problems might appear.

But adding this overhead and still not giving 100% guarantee doesn't sound like a good default.


Reproduction

In cases where primary D1 is deployed to say WEUR but the nearest edge is SIN right after write, the SIN replica might not get the update fast enough and the user will see data before edits.

Unless you're in Europe, where the primary D1 is deployed, you can see the problem in the playground (you might not have the access, ping me): https://voidzero-void-d1-bookmarks.skoss-individual-account.workers.dev/without-bookmark?experiment=immediate&trials=20&pressure=0.5&size=0.5&probes=20

To reproduce:

  1. In "Read-only routing baseline" section click "Run probes" button. Repeat until you see the replica region closest to you (replica / APAC / SIN in my case:

    image
  2. Then go a section below "Write/read experiment" and set:

    • Read timing: Immediate server read
    • ✅ Add replication pressure
    • Pressure per trial: 512 KiB
    • Trials: 20
  3. Press "Run Trials" button. Unless you're unlucky or D1 got significant replication pressure and switched from replica to the primary D1, you'll see some of the requests getting stale data (stale data is only possible on a replica, SIN in my case):

image

Depending on your region and current state of D1 instance you might not see stale data at all. If you see that read target is primary / WEUR wait for a 1-2 minutes and start from 1. You can also increase replication pressure a bit. A high pressure makes D1 switch to primary and only hit replicas occasionally. Most likely you will encounter a network error caused by D1 being overwhelmed.


The working solution is on the "Manual bookmark" page where data is always fresh: https://voidzero-void-d1-bookmarks.skoss-individual-account.workers.dev/with-bookmark?experiment=immediate&trials=20&probes=20&pressure=0.5&size=0.5

image

@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Nov 13, 2026 •

Copy link
Copy Markdown

🚀 Deploying Preview to Cloudflare 🚀

Preview URL: https://fix-783-d1-bookmark-void-cloud.voidzero-docs.workers.dev (commit 2f9ba18)

This URL reflects your latest Preview deployment

Preview Deployments by commit

Status Deployment URL Commit Updated (UTC) See this deployment's details
  • Build: Success ✅
  • Deployment: Success ✅

View logs ↗
https://5114b3ba-void-cloud.voidzero-docs.workers.dev 2f9ba18 2026-11-17T19:08:12.339Z Visit the dashboard ↗
  • Build: Success ✅
  • Deployment: Success ✅

View logs ↗
https://3b80e999-void-cloud.voidzero-docs.workers.dev 675064c 2026-11-17T12:24:27.733Z Visit the dashboard ↗
  • Build: Success ✅
  • Deployment: Success ✅

View logs ↗
https://f6c944b1-void-cloud.voidzero-docs.workers.dev 5ce3f86 2026-11-17T11:37:33.628Z Visit the dashboard ↗
  • Build: Success ✅
  • Deployment: Success ✅

View logs ↗
https://9679bb3f-void-cloud.voidzero-docs.workers.dev ae21985 2026-11-17T10:01:52.367Z Visit the dashboard ↗
  • Build: Success ✅
  • Deployment: Success ✅

View logs ↗
https://5d8f73a3-void-cloud.voidzero-docs.workers.dev a364521 2026-11-16T08:36:27.951Z Visit the dashboard ↗
  • Build: Success ✅
  • Deployment: Success ✅

View logs ↗
https://e6d95be1-void-cloud.voidzero-docs.workers.dev 79b00d5 2026-11-16T08:30:44.179Z Visit the dashboard ↗
  • Build: Success ✅
  • Deployment: Success ✅

View logs ↗
https://9545e410-void-cloud.voidzero-docs.workers.dev 6bd4980 2026-11-16T07:25:16.040Z Visit the dashboard ↗
  • Build: Success ✅
  • Deployment: Success ✅

View logs ↗
https://c9005645-void-cloud.voidzero-docs.workers.dev 552cda1 2026-11-16T07:22:35.759Z Visit the dashboard ↗
  • Build: Success ✅
  • Deployment: Success ✅

View logs ↗
https://d5572bed-void-cloud.voidzero-docs.workers.dev ca8896e 2026-11-16T06:11:58.365Z Visit the dashboard ↗
  • Build: Success ✅
  • Deployment: Success ✅

View logs ↗
https://0c83a8a5-void-cloud.voidzero-docs.workers.dev 0f6dfa8 2026-11-16T06:03:57.634Z Visit the dashboard ↗

View all previews: View all previews ↗

Comment thread packages/void/src/codegen/db-types.ts Resolved
@yangshun

Copy link
Copy Markdown
Collaborator
  • PR Better organize runtime modules #841 reorganized the runtime files into feature directories.
  • Please resolve the merge conflicts against the latest main and update imports and build/export paths that still use the old layout.
  • This PR adds runtime/db-session.ts; please place it under runtime/db/.

@kossnocorp

Copy link
Copy Markdown
Contributor Author

@yangshun thank you for the heads-up!

@kossnocorp kossnocorp changed the title feat: add support for D1 bookmarks to fight stale data returned from replicas feat: add support for D1 Sessions API to mitigate stale data returned from replicas Nov 16, 2026
@kossnocorp
kossnocorp marked this pull request as ready for review November 16, 2026 08:46
@kossnocorp
kossnocorp requested a review from a team as a code owner November 16, 2026 08:46
@cpojer
cpojer requested a review from Brooooooklyn November 16, 2026 08:47

@Brooooooklyn Brooooooklyn left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for this, and for the careful write-up on replicas. The core runtime change is small and mostly right: outside a request, db still starts on primary for each access, auth keeps its own primary client, the new module adds no heavy imports, and the unit tests pass.

Requesting changes for:

Level Issue
medium The docs middleware's setSession() throws when a loader that used db makes a server-side fetch from void/client (same request scope)
medium The cookie and both-transports recipes turn off ISR and shared caching for every route
low The generated .void/db.d.ts doesn't match the published void/db types (getBookmark generic, DbSessionStart)
low Any property read or await on db locks setSession(); unclear error outside the request scope; constraint typos compile
low defer() note, bookmark input note, test timeouts, placeholder

Missing tests: the published module's out-of-scope path (each access uses first-primary) and the getBookmark(client) error for a client not backed by a session.

Also: the branch is behind main and needs the rebase requested earlier. The playground is a scope call for maintainers; trimming it and its browser suite would make it easier to maintain.

Comment thread packages/void/src/runtime/db/session.ts Resolved
Comment thread packages/void/src/runtime/db/index.ts Resolved
Comment thread packages/void/src/runtime/db/session.ts Resolved
Comment thread packages/void/src/runtime/db/session.ts Resolved
Comment thread packages/void/src/codegen/db-types.ts Resolved
Comment thread docs/guide/database/d1.md Resolved
Comment thread docs/guide/database/d1.md Resolved
Comment thread docs/guide/database/d1.md Resolved
@kossnocorp

Copy link
Copy Markdown
Contributor Author

@Brooooooklyn thank you for the review. I'm looking into it.

What do you think about making replicas opt-in? I can make the change disabling it in the same PR.

@Brooooooklyn

Copy link
Copy Markdown
Member

Thanks! Yes, let's make replicas opt-in here. Please add a config option, have provisioning skip read_replication unless it's set, and update the docs. Note that existing databases keep replication on.

Both provisioning paths set it today:

  • packages/void/src/cli/provision.ts (enableD1ReadReplicationViaApi, native void deploy --platform cloudflare)
  • platform/packages/api/src/provisioning/cloudflare-api.ts (create and update both send read_replication: { mode: 'auto' })

The review comments above still apply, since the session helpers are still useful once replicas are turned on.

@kossnocorp

Copy link
Copy Markdown
Contributor Author

@Brooooooklyn I addressed the issues and reworked API a bit to avoid typos in first-* (setSession({ bookmark })). Please take a look again.

Especially 675064c where I add the option and make it opt-in for new deployments.

The GPT says even setting database.readReplication: false won't disable replicas for old versions:

The current implementation already disables replication correctly: explicit false sends read_replication: { mode: 'disabled' }.

The fix is to prevent deployment to platforms that ignore it:

  1. Release the updated platform provisioning code.
  2. Raise MIN_PLATFORM_VERSION to that release.
  3. Older platforms reject deployment with an upgrade instruction.
  4. After upgrading, redeploy with database: { readReplication: false }.

Keep omission distinct: it sends no replication update. Add a compatibility regression proving the old platform is rejected before provisioning.

I don't know how release workflow looks like and if we should (I think we have to) to communicate to existing users so they aware about the issue, upgrade and disable replicas.

cc @cpojer

@kossnocorp kossnocorp changed the title feat: add support for D1 Sessions API to mitigate stale data returned from replicas feat: make D1 replicas opt-in, add database.readReplication config, add support for D1 Sessions API to mitigate stale data returned from replicas Nov 17, 2026
@kossnocorp kossnocorp changed the title feat: make D1 replicas opt-in, add database.readReplication config, add support for D1 Sessions API to mitigate stale data returned from replicas feat: make D1 replicas opt-in as safer default and add support for Sessions API to mitigate stale data returned from replicas Nov 17, 2026
@kossnocorp
kossnocorp merged commit d6c179c into main Nov 17, 2026
19 checks passed
@kossnocorp
kossnocorp deleted the fix/783-d1-bookmark branch November 17, 2026 19:31
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

void/db can't carry a D1 bookmark across requests

3 participants