Back to Cloudflare

Build Relational Features With D1

November 5, 2026 Wasil Zafar 26 min read

Treat schema changes and query behavior as production decisions

Table of Contents

  1. Relational Constraints for Application Data
  2. Prepared Statements, Indexes, and Query Plans
  3. Schema Migrations and Recovery
  4. Read Distribution and Consistency Requirements
  5. Model Users and Published Documents in D1
  6. Check Constraints, Failed Migrations, and Query Behavior

Relational Constraints for Application Data

Field Notes is a small publishing product: people sign in, write documents, and publish them at a public URL. Its first version stores each document as a JSON blob in Workers KV. That works until the product needs every document by one author, a public slug no other document may reuse, and a rule that a published document must have a publication time. The application starts rebuilding those relationships by hand, and every missed check becomes a consistency bug.

D1 is Cloudflare's managed SQLite database, running the SQLite engine behind a Worker binding. The mental model is ordinary SQL; the difference is operational. It lives on Cloudflare's network, has documented limits, and can serve reads from replicas.

A relation is a table with fixed columns. A primary key uniquely identifies a row. A foreign key requires a value to match a key in another table. A constraint is a rule checked on every write, such as uniqueness or an allowed status. An index finds rows without reading the whole table. A query plan is SQLite's strategy for a statement, and a migration is a versioned SQL file that changes the schema.

Every rule lives in the table definition, not in a comment. The Field Notes schema has three tables, and each one carries its own constraints.

TableColumnsRules enforced by the schema
usersid, email, display_name, timestampsemail is unique and case-insensitive; id is the primary key
documentsid, owner_id, slug, title, status, body, published_at, updated_atowner_id references users(id); slug is unique; title is 1–200 characters; status is draft, published, or archived; a published row needs published_at
document_eventsid, document_id, kind, created_atdocument_id references documents(id); kind is created, published, or archived

The core model is a division of responsibility: the Worker decides who may act, and the database decides whether the resulting rows are legal. A schema is closer to building code than to interior decoration: code can rearrange furniture, but the load-bearing rules are checked by something that does not care about your deploy schedule. Figure 1 traces a write through those boundaries, including the rejection paths.

Relational Constraints for Application Data
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
    C["Browser or API client: untrusted slug, title, owner_id"] --> W["Worker: authenticate and authorize"]
    W -->|"not signed in or not the owner"| E["401 or 403 response"]
    W --> V["Validate shape and length"]
    V --> P["prepare SQL with ? parameters"]
    P --> B["bind values as data"]
    B --> D["D1 / SQLite: CHECK, UNIQUE, FOREIGN KEY"]
    D -->|"constraint fails"| R["409 response; no row committed"]
    D -->|"constraints pass"| S["Commit row and index entries"]
    S --> Q["Return the created record"]
    classDef primary fill:#132440,color:#ffffff,stroke:#0b172b;
    classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a;
    classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f;
    classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420;
    classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f;
    class W,P,B,D,S,Q secondary;
    class C,E,V,R ok;

Figure 2 shows the layers: untrusted strings, a Worker policy layer, a SQL execution layer, and durable pages and index entries. A constraint cannot enforce authorization, and an authorization check cannot replace a uniqueness constraint.

Trust and enforcement boundary for a D1 write The client sends untrusted values to a Worker, which authenticates, authorizes, validates, prepares, and binds them. D1 enforces CHECK, UNIQUE, and foreign key constraints before committing rows and index entries. Trust and enforcement boundary Each layer answers a different question; none substitutes for another. Client Browser or API caller Untrusted strings: slug, title, owner_id May be malicious, stale, or malformed trust boundary Worker 1 authenticate the caller 2 authorize this document 3 validate shape and length 4 prepare and bind values Policy layer: decides who may act execution boundary D1 / SQLite CHECK, UNIQUE, FOREIGN KEY query planner pages and index entries Data layer: decides whether rows are legal HTTPS SQL text + values rows or error

Parameterized queries are part of the same boundary.

Never interpolate a value into SQL

A prepared statement keeps SQL syntax and user data in separate channels: the statement holds ? placeholders, and .bind() supplies values that SQLite treats as data.

D1 supports anonymous ? and ordered ?NNN parameters; named parameters are not yet available. The moment a value becomes syntax, the trust boundary collapses.

D1's limits shape the design early. A database holds 10 GB on Workers Paid (500 MB on Free), a row or BLOB can reach 2 MB, a table can have 100 columns, and a statement can be 100 KB. Each database is single-threaded, so throughput is roughly the inverse of query duration. These decide whether D1 fits.

D1 is one store among three, and the choice is a design decision. The question is not which database is fastest in the abstract, but which failure mode you want to own.

OptionBest fitWhat it optimizes
D1Read-heavy relational workloads within 10 GB per databaseManaged SQL, migrations, and global read replicas
Durable ObjectsPer-user or per-tenant SQLite beside coordinating compute, such as real-time collaborationStrict serializability and a single authoritative instance
HyperdriveAn existing Postgres or MySQL databaseConnection pooling and query caching without replacing drivers or ORMs

Prepared Statements, Indexes, and Query Plans

A prepared statement has a fixed shape and variable values. D1 separates preparing the SQL from binding values and choosing a result shape:

  • run() executes the statement and reports success.
  • all() returns every matching row.
  • first() returns one row, or null, which suits authorization lookups.
  • raw() returns rows as arrays.

Append LIMIT 1 yourself when you want a single row; the API does not rewrite the query.

Three query shapes, three plans. The Field Notes feed shows where an index changes the work SQLite does.

-- Query A: a primary-key lookup seeks straight to the row.
SELECT id, title, body FROM documents WHERE id = ?;

-- Query B: one author's documents, newest first.
-- Without an index: scan documents, sort matches in a temporary B-tree, then apply the limit.
SELECT id, title, updated_at
FROM documents
WHERE owner_id = ?
ORDER BY updated_at DESC
LIMIT 20;

-- Query C: the public feed.
-- Without the partial index: sort every published document before applying the limit.
SELECT id, title, published_at
FROM documents
WHERE status = 'published' AND published_at <= ?
ORDER BY published_at DESC
LIMIT 20;

A composite index on (owner_id, updated_at DESC) lets Query B seek to the author and read in order. A query that skips the leftmost column cannot use it for that seek.

The feed index must match both the predicate and the sort. A partial index on (status, published_at DESC), restricted to published rows, lets Query C stop after the limit instead of sorting every published document.

The fourth case is a shape of code. Fetching 50 documents and then each author in a loop produces 51 round trips and 51 queries against the per-invocation limit. A join, or one batch() call, makes it one request. Figure 3 shows the plan choice and the failure branches: a missing index, a binding error, and a batch that violates a constraint.

DecisionWhat it changes in production
Bind every value with prepare() and bind()Keeps data out of SQL syntax, prevents injection through values, and lets the same statement shape be reused with different inputs.
Add a single-column indexTurns a full table scan into a seek for equality and range predicates on that column, at the cost of extra writes and storage for every indexed row.
Add a composite index in predicate orderSupports queries that filter on the leftmost columns and can satisfy an ORDER BY without a temporary sort; a query that skips the leftmost column will not use it.
Add a partial index for a hot subsetKeeps the index smaller by excluding rarely queried rows, but the query predicate must match the index's WHERE clause for the planner to use it.
Prepared Statements, Indexes, and Query Plans
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
sequenceDiagram
    participant W as Worker
    participant D as D1 primary
    participant P as SQLite planner
    W->>D: prepare("SELECT ... WHERE owner_id = ?")
    W->>D: bind(ownerId) then all()
    D->>P: choose a plan
    alt index on owner_id and updated_at
        P-->>D: SEARCH documents USING INDEX
        D-->>W: rows plus meta.rows_read
    else no matching index
        P-->>D: SCAN documents and sort
        D-->>W: rows plus a larger meta.rows_read
    end
    alt wrong number of bindings
        D-->>W: D1_ERROR about parameter binding
    end
    W->>D: batch(insert document, insert audit event)
    alt a statement violates a constraint
        D-->>W: error and rollback of the batch
    else all statements succeed
        D-->>W: results in statement order
    end

A query plan is evidence, not a guarantee

EXPLAIN QUERY PLAN reports the planner's choice, but the text depends on the SQLite build and on ANALYZE statistics. Compare plan shapes, not exact strings, and re-check any index-dependent decision against the database that serves traffic; a local plan can differ from the remote one.

-- Field Notes schema and a before/after query-plan check.
-- Run against local D1 with:
--   npx wrangler d1 execute field-notes --local --file=./schema.sql

CREATE TABLE IF NOT EXISTS users (
  id           TEXT PRIMARY KEY,
  email        TEXT NOT NULL COLLATE NOCASE,
  display_name TEXT NOT NULL,
  created_at   INTEGER NOT NULL DEFAULT (CAST(strftime('%s', 'now') AS INTEGER))
);

CREATE UNIQUE INDEX IF NOT EXISTS idx_users_email ON users(email);

CREATE TABLE IF NOT EXISTS documents (
  id           TEXT PRIMARY KEY,
  owner_id     TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
  slug         TEXT NOT NULL,
  title        TEXT NOT NULL CHECK (length(title) BETWEEN 1 AND 200),
  status       TEXT NOT NULL DEFAULT 'draft'
               CHECK (status IN ('draft', 'published', 'archived')),
  body         TEXT NOT NULL DEFAULT '',
  published_at INTEGER,
  updated_at   INTEGER NOT NULL DEFAULT (CAST(strftime('%s', 'now') AS INTEGER)),
  CHECK (status != 'published' OR published_at IS NOT NULL)
);

CREATE UNIQUE INDEX IF NOT EXISTS idx_documents_slug ON documents(slug);
CREATE INDEX IF NOT EXISTS idx_documents_owner_updated
  ON documents(owner_id, updated_at DESC);

CREATE TABLE IF NOT EXISTS document_events (
  id          TEXT PRIMARY KEY,
  document_id TEXT NOT NULL REFERENCES documents(id) ON DELETE CASCADE,
  kind        TEXT NOT NULL CHECK (kind IN ('created', 'published', 'archived')),
  created_at  INTEGER NOT NULL
);

-- Before the feed index: expect a scan plus a temporary sort.
EXPLAIN QUERY PLAN
SELECT id, title, published_at
FROM documents
WHERE status = 'published' AND published_at <= 1700000000
ORDER BY published_at DESC
LIMIT 20;

-- The partial index matches the predicate and the sort order.
CREATE INDEX IF NOT EXISTS idx_documents_feed
  ON documents(status, published_at DESC)
  WHERE status = 'published';

PRAGMA optimize;

-- After the index: expect SEARCH ... USING INDEX idx_documents_feed.
EXPLAIN QUERY PLAN
SELECT id, title, published_at
FROM documents
WHERE status = 'published' AND published_at <= 1700000000
ORDER BY published_at DESC
LIMIT 20;
interface Env {
  DB: D1Database;
}

interface FeedRow {
  id: string;
  title: string;
  published_at: number;
  author: string;
}

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    const url = new URL(request.url);
    const requested = Number(url.searchParams.get("limit") ?? "20");
    const limit = Number.isFinite(requested)
      ? Math.min(Math.max(Math.trunc(requested), 1), 50)
      : 20;
    const now = Math.floor(Date.now() / 1000);

    const feed = await env.DB.prepare(
      `SELECT d.id, d.title, d.published_at, u.display_name AS author
         FROM documents d
         JOIN users u ON u.id = d.owner_id
        WHERE d.status = 'published'
          AND d.published_at <= ?1
        ORDER BY d.published_at DESC
        LIMIT ?2`,
    )
      .bind(now, limit)
      .all<FeedRow>();

    return Response.json({
      items: feed.results,
      rowsRead: feed.meta.rows_read,
      rowsWritten: feed.meta.rows_written,
    });
  },
} satisfies ExportedHandler<Env>;

export async function createDraft(
  env: Env,
  ownerId: string,
  slug: string,
  title: string,
): Promise<{ id: string }> {
  const id = crypto.randomUUID();
  const now = Math.floor(Date.now() / 1000);

  try {
    const results = await env.DB.batch([
      env.DB.prepare(
        `INSERT INTO documents (id, owner_id, slug, title, status, body, updated_at)
         VALUES (?1, ?2, ?3, ?4, 'draft', '', ?5)`,
      ).bind(id, ownerId, slug, title, now),
      env.DB.prepare(
        `INSERT INTO document_events (id, document_id, kind, created_at)
         VALUES (?1, ?2, 'created', ?3)`,
      ).bind(crypto.randomUUID(), id, now),
    ]);

    if (results.some((result) => !result.success)) {
      throw new Error("batch rolled back");
    }
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    if (message.includes("UNIQUE constraint failed: documents.slug")) {
      throw new Error("slug already exists");
    }
    throw error;
  }

  return { id };
}

A batch is the transaction boundary

D1 runs in auto-commit, so related writes need one batch. A batch executes statements sequentially and non-concurrently; if one fails, the sequence is aborted or rolled back. That is why the draft insert and its audit event belong together: a duplicate slug rolls back both, so an event cannot survive without its document.

A batch counts as one query against the per-invocation limit, even with many statements, but individual statement limits still apply: 100 KB of SQL and 100 bound parameters.

Indexes are not free

Every indexed column adds writes and storage, and an index pays off only when a query runs often enough for the saved rows to matter. Create indexes for predicates and joins you actually run.

Confirm each one with EXPLAIN QUERY PLAN and refresh statistics with PRAGMA optimize after schema changes.

Then measure meta.rows_read and meta.rows_written — the units D1 bills.

Schema Migrations and Recovery

A migration is a versioned SQL file, and the database name is the stable handle. Wrangler creates, lists, and applies migrations; applied names are recorded in d1_migrations. Use the database name rather than the binding name, because bindings change between environments.

-- migrations/0002_add_document_summary.sql
-- Expand: add the column without breaking existing inserts.
ALTER TABLE documents ADD COLUMN summary TEXT;

-- Find rows that still need a backfill, 1,000 at a time.
SELECT id FROM documents WHERE summary IS NULL LIMIT 1000;

-- Contract: add the final constraint only after the backfill is clean.
-- SQLite needs a table rebuild to add a stricter CHECK.
# Create, list, and apply migrations for the database named field-notes.
npx wrangler d1 migrations create field-notes add_document_summary
npx wrangler d1 migrations list field-notes
npx wrangler d1 migrations apply field-notes --local
npx wrangler d1 migrations apply field-notes --remote

# After applying, verify the table shape and the ledger itself.
npx wrangler d1 execute field-notes --local --command="PRAGMA table_info(documents)"
npx wrangler d1 execute field-notes --local --command="PRAGMA index_list(documents)"
npx wrangler d1 execute field-notes --local --command="SELECT name FROM d1_migrations"

Expand, then contract. Add the column as nullable or with a default, deploy code that writes both shapes, and backfill in chunks. A later migration adds the final constraint once the data is clean; only then do you remove the old column. Each step is independently deployable.

SQLite's ALTER TABLE is narrower than PostgreSQL's. Adding, renaming, and dropping a column are supported, but changing a type or constraint usually requires a rebuild: create a new table, copy rows, drop the old table, rename the new one. Deferred foreign-key checks only postpone enforcement to the end of the transaction, where unresolved violations still fail. A required column without a default cannot be added to a non-empty table, because SQLite cannot invent a value for every row.

Verify the schema, not the terminal. If a migration fails, Wrangler rolls it back and leaves the previous migration applied, but code and schema can still be out of step. Check the table shape, the index list, and the applied-migration ledger directly — the commands are in the widget above.

For data loss, Time Travel is always on. It keeps point-in-time history for 30 days on Workers Paid and 7 on Free and costs nothing extra. A restore is destructive: it overwrites the database in place, cancels in-flight queries and transactions, and returns a bookmark that can undo the restore. Restores are limited to 10 per 10 minutes per database; bookmarks are also the mechanism behind the Sessions API.

Schema changes and replicas interact subtly. Replicas receive changes asynchronously, so a Worker deployed immediately after a migration can reach a replica that has not applied the new schema. The symptom is an error such as a missing column, not a stale value. Deploy schema changes before dependent code, keep new code compatible with the old schema during the transition, and route reads that truly require the new shape to the primary.

Read Distribution and Consistency Requirements

Without replication, D1 routes every query to one primary in one location, so latency is a function of distance. Read replicas add read-only copies in other regions. Writes still go to the primary, and replicas forward writes they receive. Replication is asynchronous, so a replica can be arbitrarily behind; that gap is the replica lag.

Read replication is a public beta. Cloudflare creates one replica in each supported region (ENAM, WNAM, WEUR, EEUR, APAC, OC), activates them based on traffic, and routes transparently. Replicas add no extra storage or compute charge; billing remains rows read and rows written.

A session is the switch that routes reads. It groups queries from one logical application session, such as one browser session.

Enabling replication does not route reads

Without the Sessions API, every query still goes to the primary. A session groups queries from one logical application session and starts under one of three rules:

  • first-primary — start at the primary.
  • first-unconstrained — start at any replica.
  • a bookmark — start at a replica at least as new as that position.

Within that session D1 provides sequential consistency — monotonic reads, monotonic writes, writes-follow-reads, and read-your-own-writes.

That solves read-after-write only if the bookmark travels with the user. A request writes a title and redirects; the redirect is a new request, possibly routed to an uncaught replica. The write succeeded, but the user sees the old title. Figure 4 contrasts the paths. Return the bookmark in a header or cookie and pass it into the next session; first-primary also works but pays primary latency.

Read-after-write with and without a D1 bookmark The top path writes to the primary and then reads an asynchronous replica too early, returning a stale title. The bottom path carries a bookmark from the write into the next session, so the replica waits until it has caught up before serving the read. Without a bookmark: the read is legal but stale Worker writes new title Primary commits and acknowledges Replica has not caught up yet Read returns old title; user sees stale replica lag With a bookmark: the replica waits for the required version Worker writes new title Bookmark 100 returned to client Next session reads with bookmark 100 Replica catches up then returns fresh data waits until version at least 100

Bookmarks are positions in the write order, not authorization credentials: passing one does not grant access, it only asks for a version at least that fresh. Scope it to the session that produced it.

Each start rule trades freshness for latency. Start at the primary for admin screens, permission checks, and reads immediately after a write. Start unconstrained for anonymous feeds where slightly older data is acceptable, and resume from a bookmark for continuity across one user's requests. None increases write throughput: writes serialize on the primary, and each database and replica is single-threaded.

Connection and query limits bound the loop. A Worker can open six D1 connections per invocation; a query or batch is capped at 30 seconds, and a result at 50 MB (from 2026-11-04). An invocation can issue 1,000 queries on Workers Paid or 50 on Free, and a batch counts as one. If those limits are near, the problem is usually a plan or an N+1 pattern, not a missing replica.

Model Users and Published Documents in D1

Guided exercise

Model Users and Published Documents in D1

Status: design-only. These commands were not executed here, and no latency, row-count, or cost measurements are reported.

Prerequisites. Node.js and npm, current Wrangler, and a Cloudflare account. The Free plan covers local work and a small remote database; remote runs consume its daily row limits. The optional replication step uses the dashboard and the public-beta Sessions API.

Setup. Create the project and database, wire the binding, and apply the schema from the earlier widget.

  • npm create cloudflare@latest field-notes
  • npx wrangler d1 create field-notes
  • Add the DB binding to wrangler.jsonc, with the returned database ID and the migrations directory.
  • Save the schema as schema.sql, then run npx wrangler d1 execute field-notes --local --file=./schema.sql.
  • Seed two users and three documents: one valid published, one draft, and one published with a missing publication time.

Actions.

  1. Run the schema file and read the first plan, before the index. Note the scan.
  2. Read the second plan, after the index and the statistics refresh. Compare shapes, not text.
  3. Query with bound values and inspect rows read, rows written, and duration. Fetch the same 20 documents and authors with one join; compare round trips.
  4. Insert the invalid published row, a duplicate email, and a duplicate slug. Expect each constraint to reject the write.
  5. Insert a document and event in one batch, make the event kind invalid, and confirm no orphan event remains.
  6. Add a required column with no default to the non-empty table. Observe the failure, then rewrite it as nullable or with a default and backfill in chunks.
  7. Optional remote: enable read replication, write through a session, then read once without and once with a bookmark. Record which region served each read.

Expected observations.

CheckPredicted result
First planA scan of documents
Second planA search using the feed index
Invalid published rowRejected; the row is absent
Duplicate email or slugRejected; the error names the constraint
Batch with a bad event kindNeither document nor event remains
Required column, no defaultThe migration fails rather than inventing values
Bookmark readSequentially consistent once the replica catches up

Failure checks.

  • If the first plan uses an index, another index or a tiny table may be responsible; list the indexes on the table.
  • A query filtering only on published_at ignores a (status, published_at) index; that is the leftmost-prefix rule.
  • If the single-row read returns null, check whether the row exists before treating it as an authorization failure.
  • If remote reads never report a replica region, confirm the Sessions API is used.

Cost dimensions. Local execution has no D1 charge. Remote work bills rows read, written, and storage; a full scan bills every row scanned, not every row returned. Replicas add no separate charge; database count is included up to the plan allowance.

Cleanup. Run npx wrangler d1 delete field-notes, remove local .wrangler state and the scratch project, and disable read replication if the database is kept.

The exercise covers real constraints, a before-and-after plan check, an atomic batch, a safe migration failure, and an explicit consistency choice. The replication step is optional.

Check Constraints, Failed Migrations, and Query Behavior

The evidence here is documentation evidence plus a reproducible design, not a hosted benchmark.

  • PASS, documented: D1 enforces foreign keys by default and supports PRAGMA defer_foreign_keys; CHECK and UNIQUE reject invalid writes (https://developers.cloudflare.com/d1/sql-api/foreign-keys/, https://developers.cloudflare.com/d1/sql-api/sql-statements/).
  • PASS, documented: EXPLAIN QUERY PLAN reports SCAN versus SEARCH ... USING INDEX, and composite indexes follow the leftmost-prefix rule (https://developers.cloudflare.com/d1/best-practices/use-indexes/).
  • PASS, documented: batch() runs sequentially, rolls back the sequence on failure, and counts as one query against the per-invocation limit (https://developers.cloudflare.com/d1/worker-api/d1-database/).
  • PASS, documented: a failed migration is rolled back, the previous migration remains applied, and applying migrations captures a backup (https://developers.cloudflare.com/workers/wrangler/commands/d1/).
  • PASS, documented: Time Travel retains 30 days on Workers Paid and 7 on Free, restores in place, and allows 10 restores per 10 minutes per database (https://developers.cloudflare.com/d1/reference/time-travel/).
  • PASS, documented: read replication is a public beta, requires the Sessions API to route reads, and provides sequential consistency with bookmarks (https://developers.cloudflare.com/d1/best-practices/read-replication/).
  • NOT RUN: the exercise, remote replication behavior, latency, and row counts. No measured values are claimed.

Self-check.

  • Why not interpolate a slug into SQL? The value would become syntax; binding keeps it in the data channel.
  • You indexed (status, published_at) but a query filtering only on published_at does not use it: the index is ordered by status first, so omitting the leftmost column prevents a seek.
  • You enabled replication but still see primary latency: enabling it does not route reads, and without a session every query goes to the primary.
  • A required-column migration failed: Wrangler rolled it back; rewrite it as nullable or with a default, backfill, then add the constraint.

Unresolved limitations. Read replication is a beta, and its regions may change. Plans depend on the SQLite build and ANALYZE statistics, so a local plan is evidence about shape, not a promise about the remote plan. The 10 GB cap and single-threaded execution limit one database; the documented answer is to split by user, tenant, or entity. D1 supports ordered and anonymous parameters but not named parameters. Pricing and limits are dated to the verification below.

Verification. Documentation checked on 2026-11-05 against the Cloudflare D1 docs; the planning baseline was 2026-11-02. No Wrangler, Workers runtime, or D1 version was tested, and no hosted lab was run.

References. - Cloudflare D1 overview: https://developers.cloudflare.com/d1/ - D1 limits: https://developers.cloudflare.com/d1/platform/limits/ - D1 pricing: https://developers.cloudflare.com/d1/platform/pricing/ - D1 migrations: https://developers.cloudflare.com/d1/reference/migrations/ - Use indexes and query plans: https://developers.cloudflare.com/d1/best-practices/use-indexes/ - Global read replication: https://developers.cloudflare.com/d1/best-practices/read-replication/ - D1 Database API, including batch() and withSession(): https://developers.cloudflare.com/d1/worker-api/d1-database/ - Prepared statement methods: https://developers.cloudflare.com/d1/worker-api/prepared-statements/ - Foreign keys: https://developers.cloudflare.com/d1/sql-api/foreign-keys/ - Time Travel and bookmarks: https://developers.cloudflare.com/d1/reference/time-travel/ - Choosing a storage product, including D1 versus Durable Objects and Hyperdrive: https://developers.cloudflare.com/workers/platform/storage-options/ - Wrangler D1 commands: https://developers.cloudflare.com/workers/wrangler/commands/d1/

Next in the Series

In Connect Workers to Existing Databases With Hyperdrive, we'll explore Distinguish connection acceleration from a database migration.