Repository navigation
fix: prefer uncached Hyperdrive after content writes - #2280
Conversation
🦋 Changeset detectedLatest commit: 2474ebc The changes in this PR will be included in the next version bump. This PR includes changesets to release 17 packages
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
Deploying with
|
| Status | Name | Latest Commit | Updated (UTC) |
|---|---|---|---|
| ✅ Deployment successful! View logs |
emdash-demo-cache | 2474ebc | Aug 10 2026, 02:07 PM |
Deploying with
|
| Status | Name | Latest Commit | Updated (UTC) |
|---|---|---|---|
| ✅ Deployment successful! View logs |
emdash-playground | 2474ebc | Aug 10 2026, 02:05 PM |
@emdash-cms/admin
@emdash-cms/auth
@emdash-cms/auth-atproto
@emdash-cms/blocks
@emdash-cms/cloudflare
@emdash-cms/contentful-to-portable-text
emdash
create-emdash
@emdash-cms/gutenberg-to-portable-text
@emdash-cms/plugin-cli
@emdash-cms/plugin-types
@emdash-cms/registry-client
@emdash-cms/registry-lexicons
@emdash-cms/registry-verification
@emdash-cms/sandbox-workerd
@emdash-cms/x402
@emdash-cms/plugin-ai-moderation
@emdash-cms/plugin-atproto
@emdash-cms/plugin-audit-log
@emdash-cms/plugin-color
@emdash-cms/plugin-embeds
@emdash-cms/plugin-field-kit
@emdash-cms/plugin-forms
@emdash-cms/plugin-webhook-notifier
commit: |
Deploying with
|
| Status | Name | Latest Commit | Updated (UTC) |
|---|---|---|---|
| ✅ Deployment successful! View logs |
emdash-demo-do | 2474ebc | Aug 10 2026, 02:06 PM |
Deploying with
|
| Status | Name | Latest Commit | Updated (UTC) |
|---|---|---|---|
| ✅ Deployment successful! View logs |
docs | 4f895dc | Aug 10 2026, 01:11 PM |
There was a problem hiding this comment.
This PR addresses a real problem: with Hyperdrive's cachedBinding, anonymous public reads right after a content publish can reseed edge/object caches from Hyperdrive's still-stale query cache. The approach—tracking the last content-namespace invalidation in the object-cache backend and routing to the primary uncached binding for a configurable window—fits EmDash's existing epoch/invalidation architecture and the split-binding design.
I read the full changed files, traced the routing tests, and checked the marker logic against the object-cache revalidation pattern. The code is generally clean and well-tested, and the changeset/docs are appropriate.
The one blocking concern is a performance regression in getLastContentWriteAt: it refuses to cache a "no writes yet" marker (0), so sites with an object-cache configured will perform an extra backend round-trip on every logged-out request until a content write occurs. That violates the "never add queries to the logged-out hot path" guidance and should be fixed. I also flagged one newly-added config-pin test as low-value.
Once the zero-marker caching is fixed, this looks good to merge.
Overlapping PRsThis PR modifies files that are also changed by other open PRs: This may cause merge conflicts or duplicated work. A maintainer will coordinate. |
There was a problem hiding this comment.
This PR is a sensible, targeted fix for a real Hyperdrive cachedBinding footgun. By tracking the last content-namespace object-cache invalidation and briefly routing anonymous public GETs to the uncached binding, it prevents stale query-cache results from reseeding edge/object caches right after a publish. The approach fits EmDash's existing epoch/invalidation architecture and keeps the window configurable.
The previous review's blocking concern—the getLastContentWriteAt marker not caching a confirmed "no writes yet" value—has been addressed. The new caches a confirmed zero marker within the revalidate window test verifies that sites without content writes no longer pay a backend round-trip on every logged-out request, which satisfies the logged-out hot-path concern.
I read the full changed files, traced the routing logic and the marker lifecycle, and checked the new tests against the behavior. The fix is clean. There are two non-blocking items left: a config-pin test that should be deleted or rewritten, and an unnecessary public export of an internal helper. Once those are addressed, this is good to merge.
| it("passes through preferUncachedAfterWriteMs", () => { | ||
| const result = hyperdrive({ | ||
| binding: "HYPERDRIVE", | ||
| cachedBinding: "HYPERDRIVE_CACHED", | ||
| preferUncachedAfterWriteMs: 120_000, | ||
| }); | ||
| expect(result.config).toEqual({ | ||
| binding: "HYPERDRIVE", | ||
| max: undefined, | ||
| cachedBinding: "HYPERDRIVE_CACHED", | ||
| preferUncachedAfterWriteMs: 120_000, | ||
| }); | ||
| }); |
There was a problem hiding this comment.
[suggestion] This test passes preferUncachedAfterWriteMs: 120_000 into hyperdrive() and asserts the same value appears in the returned descriptor config. It restates the source code rather than testing behavior, so it can only fail when someone intentionally changes the option plumbing. Per AGENTS.md, config-pin tests inflate coverage without catching regressions and should be deleted or rewritten against observable behavior. A meaningful behavior test already exists in hyperdrive-routing.test.ts for custom windows, so this descriptor test is redundant.
| it("passes through preferUncachedAfterWriteMs", () => { | |
| const result = hyperdrive({ | |
| binding: "HYPERDRIVE", | |
| cachedBinding: "HYPERDRIVE_CACHED", | |
| preferUncachedAfterWriteMs: 120_000, | |
| }); | |
| expect(result.config).toEqual({ | |
| binding: "HYPERDRIVE", | |
| max: undefined, | |
| cachedBinding: "HYPERDRIVE_CACHED", | |
| preferUncachedAfterWriteMs: 120_000, | |
| }); | |
| }); | |
| it("defaults preferUncachedAfterWriteMs to 60s when cachedBinding is set", () => { | |
| const result = hyperdrive({ | |
| binding: "HYPERDRIVE", | |
| cachedBinding: "HYPERDRIVE_CACHED", | |
| }); | |
| expect(result.config).not.toHaveProperty("preferUncachedAfterWriteMs"); | |
| }); |
Or simply remove this block, since the routing tests cover the custom value behavior.
| // Object cache (distributed read-through query cache) | ||
| export { | ||
| cachedQuery, | ||
| getLastContentWriteAt, |
There was a problem hiding this comment.
[suggestion] getLastContentWriteAt is only used inside core middleware (which passes the resolved stamp to adapters via lastContentWriteAt in RequestScopedDbOpts) and in tests; it is not consumed from the public emdash package. Exporting it from the barrel makes it part of the supported API surface without a clear external consumer.
| getLastContentWriteAt, | |
| export { | |
| cachedQuery, | |
| invalidateObjectCache, | |
| invalidateCollectionCache, | |
| invalidateTaxonomyObjectCache, | |
| invalidateBylineObjectCache, | |
| invalidateMenuObjectCache, | |
| invalidateSchemaObjectCache, | |
| invalidateCommentObjectCache, | |
| isObjectCacheActive, | |
| isObjectCacheConfigured, | |
| contentNamespace, | |
| contentNamespaces, | |
| CacheNamespace, | |
| } from "./object-cache/index.js"; |
| // Even on the anonymous fast path we ask the adapter for a per-request | ||
| // scoped db. For D1 with read replication this routes anonymous reads | ||
| // to the nearest replica; for other adapters it's a no-op. | ||
| const lastContentWriteAt = await getLastContentWriteAt(); |
There was a problem hiding this comment.
This runs on every logged-out request for every adapter, but only Hyperdrive with cachedBinding ever consumes the value. On the recommended D1 + KV setup that's a blocking backend read ahead of render once per revalidate window (1s default, 2s timeout worst case) per isolate, when most sites don't need it.
Gate the fetch on the adapter actually wanting it e.g. a flag on DatabaseDescriptor so middleware doesn't need to know adapter config shapes, and skip it entirely when unset. Same applies to the call in the general request path below.
| ): Promise<T> { | ||
| const runtime = await getRuntime(config); | ||
|
|
||
| const lastContentWriteAt = await getLastContentWriteAt(); |
There was a problem hiding this comment.
This one can just be dropped: runOutsideRequest passes isWrite: true, and selectBindingName never consults lastContentWriteAt on the write path. It's a wasted backend read on every cron tick.
| // Object cache (distributed read-through query cache) | ||
| export { | ||
| cachedQuery, | ||
| getLastContentWriteAt, |
There was a problem hiding this comment.
Agree with the open thread here but there's more: middleware imports this via a relative path, so the export has no consumers - it's permanent public API surface added without needing to. Remove it from the barrel.
| }); | ||
| }); | ||
|
|
||
| it("passes through preferUncachedAfterWriteMs", () => { |
There was a problem hiding this comment.
On the open thread about this being a config-pin test I half agree, but note the routing tests construct config objects directly and never go through the hyperdrive() builder, so this is currently the only test that would catch a typo in the conditional spread. Rather than delete it, replace it with one test through the real chain: createRequestScopedDb(hyperdrive({...}).config, { ..., lastContentWriteAt: recent }) asserting the primary pool. That tests behaviour and keeps the builder link covered.
| * content-namespace invalidation → primary, so a post-publish rebuild does | ||
| * not reseed edge/object caches from Hyperdrive's still-stale query cache. | ||
| * | ||
| * Pure (no I/O) so the routing rule can be unit-tested directly. |
There was a problem hiding this comment.
Nit: this doc line is no longer true: the new window check calls Date.now() inside. Taking now in opts would make it pure and make the window tests deterministic instead of wall-clock-relative.
|
This is a good additioon, and pretty close to ready. Just a few tidiness and perf changes |
After a content publish, anonymous public reads briefly use the primary Hyperdrive binding so edge/object caches are not reseeded from stale query-cache results (default 60s when cachedBinding is set).
Avoid an object-cache backend round-trip on every logged-out request when no content write has occurred yet. Also drop a low-value config-pin test.
There was a problem hiding this comment.
Re-review of #2280
The previously raised blocking concern is resolved: getLastContentWriteAt now caches a confirmed zero marker, so sites without recent content writes do not pay the object-cache backend round-trip on every logged-out request. The internal-test-helper export is also gone.
The approach remains sound: track the last content-namespace invalidation through the existing object-cache backend and briefly route anonymous public GETs to the primary Hyperdrive binding after a publish so stale Hyperdrive query-cache results cannot reseed edge/object caches. The implementation correctly gates the marker read behind canUseCachedBinding && needsLastContentWriteAt, keeping the logged-out hot path narrow.
I read the full changed source files, traced createRequestScopedDb / selectBindingName call sites, and checked that every content-invalidation path uses a content:* namespace that will stamp the marker. I found one new contract issue: a request-free code path still calls createRequestScopedDb with the pre-PR option shape, missing the now-required canUseCachedBinding field. That is a type error against the updated RequestScopedDbOpts contract and should be fixed before merge.
No other blocking issues.
Findings
-
[needs fixing]
packages/core/src/astro/middleware.ts:350-357runOutsideRequest(used bywithEmDashRuntimeand cron/event workloads) callscreateRequestScopedDbwithout the requiredcanUseCachedBindingfield thatvirtual:emdash/dialectnow expects onRequestScopedDbOpts.This is a request-free write workload, so the right value is
false; Hyperdrive will still fall back to the primary binding becauseisWrite: true, but the call violates the updated contract and will break type-checking.const scoped = createRequestScopedDb({ config: config.database?.config, isAuthenticated: false, // Event handlers publish, clean up, or run jobs — a write workload — // so a connection-backed adapter routes them to the primary. isWrite: true, canUseCachedBinding: false, cookies: NOOP_COOKIE_JAR, url: CRON_EVENT_URL, });
There was a problem hiding this comment.
Re-review of #2280
The approach remains sound: use the existing object-cache backend to share the last content-namespace invalidation timestamp, and briefly route anonymous public Hyperdrive reads to the primary uncached binding after a publish so stale Hyperdrive query-cache results cannot reseed edge/object caches. This is the minimal change that fits EmDash's architecture — it reuses invalidateObjectCache's already-deferred epoch writes rather than inventing a new coordination channel.
The previously raised blocking contract issue is resolved: runOutsideRequest now passes canUseCachedBinding: false to createRequestScopedDb, satisfying the updated RequestScopedDbOpts contract.
I read the full changed source files, re-traced createRequestScopedDb / selectBindingName call sites, and checked that every content-invalidation path goes through invalidateCollectionCache, which stamps a content:* namespace via invalidateObjectCache. I also verified that getLastContentWriteAt caches a confirmed-zero marker, so sites without recent content writes avoid repeated object-cache backend reads on every logged-out request.
I found one new contract issue: selectBindingName is exported from the public @emdash-cms/cloudflare/db/hyperdrive runtime entry and this PR made now a required field. Existing callers that passed the previous { isAuthenticated, isWrite, url } shape now get a TypeScript error, and at runtime opts.now - lastWrite becomes NaN, causing the prefer-uncached window to be silently ignored. Since the changeset is a patch and does not call out a break, this should be made backward-compatible by defaulting now.
Overall the implementation is clean, well-tested, and the changeset/docs are in place; fix the API contract and this is good to merge.
| now: number; | ||
| }, | ||
| ): string { | ||
| if ( | ||
| config.cachedBinding && | ||
| !opts.isAuthenticated && | ||
| !opts.isWrite && | ||
| !isEmDashInternalPath(opts.url) | ||
| (opts.canUseCachedBinding ?? | ||
| (!opts.isAuthenticated && !opts.isWrite && !isEmDashInternalPath(opts.url))) | ||
| ) { | ||
| const duration = preferUncachedDurationMs(config); | ||
| const lastWrite = opts.lastContentWriteAt ?? 0; | ||
| if (duration > 0 && lastWrite > 0 && opts.now - lastWrite < duration) { |
There was a problem hiding this comment.
[needs fixing] selectBindingName is exported from the public ./db/hyperdrive runtime entry, so this is a breaking change in a patch release. Previously valid callers that passed only { isAuthenticated, isWrite, url } now fail type-checking, and at runtime opts.now is undefined, so opts.now - lastWrite evaluates to NaN and the post-write prefer-uncached window is silently skipped (the NaN < duration comparison is always false).
Make now optional with a Date.now() default, matching how createRequestScopedDb already handles the field:
| now: number; | |
| }, | |
| ): string { | |
| if ( | |
| config.cachedBinding && | |
| !opts.isAuthenticated && | |
| !opts.isWrite && | |
| !isEmDashInternalPath(opts.url) | |
| (opts.canUseCachedBinding ?? | |
| (!opts.isAuthenticated && !opts.isWrite && !isEmDashInternalPath(opts.url))) | |
| ) { | |
| const duration = preferUncachedDurationMs(config); | |
| const lastWrite = opts.lastContentWriteAt ?? 0; | |
| if (duration > 0 && lastWrite > 0 && opts.now - lastWrite < duration) { | |
| export function selectBindingName( | |
| config: HyperdriveConfig, | |
| opts: { | |
| isAuthenticated: boolean; | |
| isWrite: boolean; | |
| canUseCachedBinding?: boolean; | |
| url: URL; | |
| lastContentWriteAt?: number; | |
| now?: number; | |
| }, | |
| ): string { | |
| if ( | |
| config.cachedBinding && | |
| (opts.canUseCachedBinding ?? | |
| (!opts.isAuthenticated && !opts.isWrite && !isEmDashInternalPath(opts.url))) | |
| ) { | |
| const duration = preferUncachedDurationMs(config); | |
| const lastWrite = opts.lastContentWriteAt ?? 0; | |
| const now = opts.now ?? Date.now(); | |
| if (duration > 0 && lastWrite > 0 && now - lastWrite < duration) { | |
| return config.binding; | |
| } | |
| return config.cachedBinding; | |
| } | |
| return config.binding; | |
| } |
There was a problem hiding this comment.
This looks ready to merge.
Approach — The PR solves the right problem in the minimal way that fits EmDash. After a content publish it briefly routes anonymous public Hyperdrive reads to the uncached primary binding, using the existing distributed Object Cache backend to share the last content-write timestamp across Worker isolates. It reuses invalidateObjectCache’s already-deferred writes rather than inventing a new coordination channel, and it keeps the change scoped to the Hyperdrive adapter via the new needsLastContentWriteAt descriptor flag.
Re-review status — The only blocking issue from my previous review is resolved: selectBindingName now defaults now with opts.now ?? Date.now(), so the exported runtime API stays backward-compatible and earlier callers cannot hit a NaN window.
What I checked
- Read the full diff and the changed source files (
hyperdrive.ts,index.ts,middleware.ts,adapters.ts,object-cache/index.ts,virtual-modules.d.ts) plus the updated tests. - Verified the new
getLastContentWriteAtmarker uses the same monotonic-merge, timeout, and in-flight-promise reclaim patterns as the existing epoch reader. - Traced
createRequestScopedDbcall sites and confirmedrunOutsideRequestpassescanUseCachedBinding: falsefor event/queue workloads. - Confirmed
invalidateCollectionCacheis invoked from every content-mutation path I found. - Checked that
needsLastContentWriteAtis only set by the Hyperdrive adapter and only when acachedBindingis configured with a non-zero prefer-uncached window, so D1/SQLite logged-out routes are unaffected.
Headline conclusion — The fix is correct, well-tested, and the changeset/docs are in place. The new object-cache read on the Hyperdrive anonymous public path is an intentional coordination cost (justified by the bug), and the code already caches the confirmed-zero case within the object-cache revalidate window to avoid repeated backend reads on sites with no recent content writes.
ascorbic
left a comment
There was a problem hiding this comment.
Previous review requests are addressed; exact-head bot review and CI are green.
What does this PR do?
Prevents anonymous public requests from reseeding Workers/Object Cache with stale Hyperdrive query-cache results immediately after content publishes. Content invalidation records a shared last-write timestamp, and Hyperdrive public reads temporarily use the uncached primary binding for a configurable window (60 seconds by default).
Cross-isolate coordination uses the configured distributed Object Cache backend.
preferUncachedAfterWriteMsshould match the cached Hyperdrive configuration'smax_age.Closes #2302
Type of change
Checklist
pnpm typecheckpassespnpm lintpassespnpm testpasses (or targeted tests for my change)pnpm formathas been runmessages.pochanges except in translation PRs — a workflow extracts catalogs on merge tomain.The i18n and Discussion checklist items are not applicable: this changes no admin UI strings and fixes an existing bug.
AI-generated code disclosure
Screenshots / test output
Non-visual change. Verified after rebasing onto current
mainwith:pnpm buildpnpm typecheckpnpm lintpnpm formatTry this PR
Open a fresh playground →
A full working EmDash site, deployed from this branch. Each visit gets its own session-scoped sandbox: no login needed and no shared state. Try the admin, edit content, hit the public site.
Tracks
fix/prefer-uncached-hyperdrive-after-write. Updated automatically when the playground redeploys.