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.
| Table | Columns | Rules enforced by the schema |
|---|---|---|
users | id, email, display_name, timestamps | email is unique and case-insensitive; id is the primary key |
documents | id, owner_id, slug, title, status, body, published_at, updated_at | owner_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_events | id, document_id, kind, created_at | document_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.
%%{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.
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.
| Option | Best fit | What it optimizes |
|---|---|---|
| D1 | Read-heavy relational workloads within 10 GB per database | Managed SQL, migrations, and global read replicas |
| Durable Objects | Per-user or per-tenant SQLite beside coordinating compute, such as real-time collaboration | Strict serializability and a single authoritative instance |
| Hyperdrive | An existing Postgres or MySQL database | Connection 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, ornull, 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.
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.
| Decision | What 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 index | Turns 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 order | Supports 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 subset | Keeps 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. |
%%{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.
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.
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.
A Worker rollback is not a schema rollback
The dangerous misconception is that a Worker rollback also rolls back the schema. It does not: the database is shared, durable state, and redeploying old code leaves new tables, columns, and constraints in place. Use expand-and-contract migrations and forward fixes for schema changes, and reserve Time Travel for recovering data, not for routine application rollback.
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.
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
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-notesnpx wrangler d1 create field-notes- Add the
DBbinding towrangler.jsonc, with the returned database ID and the migrations directory. - Save the schema as
schema.sql, then runnpx 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.
- Run the schema file and read the first plan, before the index. Note the scan.
- Read the second plan, after the index and the statistics refresh. Compare shapes, not text.
- 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.
- Insert the invalid published row, a duplicate email, and a duplicate slug. Expect each constraint to reject the write.
- Insert a document and event in one batch, make the event kind invalid, and confirm no orphan event remains.
- 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.
- 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.
| Check | Predicted result |
|---|---|
| First plan | A scan of documents |
| Second plan | A search using the feed index |
| Invalid published row | Rejected; the row is absent |
| Duplicate email or slug | Rejected; the error names the constraint |
| Batch with a bad event kind | Neither document nor event remains |
| Required column, no default | The migration fails rather than inventing values |
| Bookmark read | Sequentially 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_atignores 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;CHECKandUNIQUEreject invalid writes (https://developers.cloudflare.com/d1/sql-api/foreign-keys/, https://developers.cloudflare.com/d1/sql-api/sql-statements/). - PASS, documented:
EXPLAIN QUERY PLANreportsSCANversusSEARCH ... 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 onpublished_atdoes not use it: the index is ordered bystatusfirst, 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.