Skip to content

docs(d1): add rules of D1 best practices guide#31814

Draft
ivoryibu wants to merge 5 commits into
productionfrom
add-d1-complete-guide
Draft

docs(d1): add rules of D1 best practices guide#31814
ivoryibu wants to merge 5 commits into
productionfrom
add-d1-complete-guide

Conversation

@ivoryibu

@ivoryibu ivoryibu commented Jun 30, 2026

Copy link
Copy Markdown
Collaborator

Summary

Rebased this PR onto the current production branch and revised the new Rules of D1 best-practices guide under src/content/docs/d1/best-practices/rules-of-d1.mdx.

The guide now prioritizes the D1 product guidance from the latest notes and centralizes rules currently spread across D1 docs:

  • Reorders the opening flow to Overview → When to use D1 → Limits → Scale out across many databases.
  • Expands When to use D1 with guidance on choosing D1 versus Workers KV, Durable Objects, R2, and Hyperdrive.
  • Calls out sharding trade-offs: no cross-database JOIN operations and no ACID transactions across database boundaries.
  • Uses one consistent commerce schema across examples.
  • Covers indexing, PRAGMA optimize, EXPLAIN QUERY PLAN, and D1 Insights.
  • Shows batching with db.batch() instead of sequential .run() calls.
  • Requires parameterized queries with .bind() and allowlisted dynamic SQL identifiers.
  • Adds idempotent write retry guidance with exponential backoff and jitter, including the boundary between automatic D1 retries and application-level logical retry handling.
  • Adds chunked bulk mutation guidance.
  • Adds migration tooling guidance for hand-written SQL versus ORM-generated SQL, including review of generated migrations and d1_migrations risk.
  • Adds baseline migration, local-before-remote migration, foreign key, and Time Travel bookmark rules.
  • Adds location hint guidance and Sessions API/read-replication guidance.
  • Adds single-database limits and horizontal scale-out guidance near the top of the page.

Validation

  • Rebasing onto origin/production completed successfully.
  • Ran git diff --check successfully after the latest edits.
  • Ran pnpm exec prettier --check src/content/docs/d1/best-practices/rules-of-d1.mdx under Node 24 successfully.
  • Ran pnpm exec astro check under Node 24; result: 0 errors, 0 warnings, existing repository hints only.

Notes

A follow-up PR can add a dedicated Drizzle-specific D1 page as discussed.

@cloudflare-docs-bot

cloudflare-docs-bot Bot commented Jun 30, 2026

Copy link
Copy Markdown
Contributor

Review

⚠️ 3 warnings, 💡 4 suggestions found in commit f5d3cc4.

Code Review

This code review is in beta and may not always be helpful — use your judgment.

No code review issues found.

Conventions

Checks PR title, description, and redirect checklist.

No convention issues found.

Style Guide Review

Warnings (3)
File Issue
d1/best-practices/rules-of-d1.mdx line 181 Do not bold program or tool names — Line bolds **Wrangler** in prose: \*\*Raw SQL with Wrangler\*\* works well when: Fix: Use monospace for the tool name: Raw SQL with \Wrangler``.
d1/best-practices/rules-of-d1.mdx line 188 Do not bold program or tool names — Line bolds **Drizzle** and **Prisma** in prose: \*\*An ORM like Drizzle or Prisma\*\* starts paying off when: Fix: Use monospace for the tool names: An ORM like \Drizzle` or `Prisma``.
d1/best-practices/rules-of-d1.mdx line 282 Tables must be introduced with a complete sentence ending in a colon — Line introduces the limits table with a fragment: The limits to design around first: Fix: Use a complete sentence, e.g. Design around these limits first:.
Suggestions (4)
File Issue
d1/best-practices/rules-of-d1.mdx line 183 Spell out single-digit numerals in body text — Line uses the numeral 1-5 in prose: - You have 1-5 tables Fix: Spell out the range: one to five tables.
d1/best-practices/rules-of-d1.mdx line 191 Spell out single-digit numerals in body text — Line uses the numeral 3+ in prose: joins across 3+ tables Fix: Spell out the count: three or more tables.
d1/best-practices/rules-of-d1.mdx line 202 Avoid semicolons joining independent clauses — Line uses a semicolon to join two clauses: \PRAGMA foreign_keys = off`; D1 ignores it.` Fix: Break into two sentences.
d1/best-practices/rules-of-d1.mdx line 247 Avoid semicolons joining independent clauses — Line uses a semicolon to join two clauses: [Sessions API](/d1/worker-api/d1-database/#withsession); otherwise every query goes to the primary. Fix: Break into two sentences or use a comma and coordinating conjunction.

Redirects

No missing redirect entries found.

Commands

Only codeowners can run commands. Post a comment with the command to trigger it.

Command Description
/review Runs a review now. Incremental if a prior review exists, full if not.
/full-review Re-reviews the entire PR diff from scratch, ignoring incremental history. Useful after a rebase, when you want a fresh review, or if the bot gets out of sync and reports issues that no longer exist.
/ignore-review-limit Permanently lifts the 2-review automatic limit for this PR. Future pushes will trigger reviews as normal.
/disable-auto-review Stops automatic reviews from triggering on future pushes to this PR. Codeowners can still run /review or /full-review manually.

@github-actions

Copy link
Copy Markdown
Contributor

This pull request requires reviews from CODEOWNERS as it changes files that match the following patterns:

Pattern Owners
/src/content/docs/d1/ @elithrar, @rita3ko, @irvinebroque, @vy-ton, @ivoryibu, @rts-rob, @joshthoward, @lambrospetrou, @oxyjun, @cloudflare/product-owners

@ivoryibu
ivoryibu marked this pull request as draft June 30, 2026 19:33
@ask-bonk

ask-bonk Bot commented Jun 30, 2026

Copy link
Copy Markdown
Contributor

PR Review: docs(d1): add rules of D1 best practices guide

Labels

  • Already correctly labeled product:d1 and size/m. No additional labels needed.

Summary
This PR adds a new ~330-line best-practices page (rules-of-d1.mdx) that covers query performance, reliability, schema migrations, data location / replication, and scaling. It also bumps the best-practices/index.mdx sidebar order from 3 to 4. The migration-tooling guidance (raw SQL vs. ORMs) and the warning about destructive ORM-generated statements are valuable additions. All internal links resolve correctly and astro check passes cleanly.

What looks good

  • Frontmatter is correct: pcx_content_type: concept, description within the 50–160 character range, and a valid products entry.
  • Great use of TypeScriptExample for every Workers/TS snippet.
  • Heading hierarchy follows H2 → H3 with no skipped levels.
  • Numbered lists are used appropriately for the procedural team workflow.
  • Internal links and anchor targets (#batch, #error-list, #sequential-consistency, #drizzle-orm) all verified.

Issues to address before merging

  1. Sentence case in table headers (line ~284)
    The style guide requires table column headers to be sentence case.

    - | Limit                               | Workers Paid | Workers Free |
    + | Limit                               | Workers paid | Workers free |
  2. Tool name formatting — wrangler must be monospace, not bold (lines ~165, ~181, ~196)
    The style guide explicitly states: “Do not bold program or tool names — wrangler and npm are monospace, not bold.”

    - Wrangler tracks which migrations have been applied in a `d1_migrations` table so they are never double-applied.
    + `wrangler` tracks which migrations have been applied in a `d1_migrations` table so they are never double-applied.
    - **Raw SQL with Wrangler** works well when:
    + **Raw SQL** with `wrangler` works well when:
    - You generate the SQL with your ORM, then apply it with Wrangler.
    + You generate the SQL with your ORM, then apply it with `wrangler`.
  3. Spell out acronyms on first use (lines ~179, ~183)
    The style guide requires acronyms to be spelled out on first use unless they appear in the short-list of exceptions (API, REST, URL, etc.). ORM and CRUD are not in that list.

    - You can write migration SQL by hand or use an ORM to generate it.
    + You can write migration SQL by hand or use an object-relational mapping (ORM) to generate it.
    - - Your queries are straightforward CRUD
    + - Your queries are basic create, read, update, and delete (CRUD) operations
  4. Numbers zero through nine should be written as words (lines ~183, ~191)
    The style guide says: “Spell out whole numbers zero through nine in body text. Use digits for 10 and above.”

    - - You have 1-5 tables
    + - You have one to five tables
    - - You build complex queries with joins across 3+ tables, where type safety prevents you from accidentally joining on the wrong column or misspelling a field name
    + - You build complex queries with joins across three or more tables, where type safety prevents you from accidentally joining on the wrong column or misspelling a field name
  5. Avoid LLM-filler word “straightforward” (line ~184)
    “straightforward” is listed as a filler phrase to avoid.
    (Addressed together with item 3 above by replacing “straightforward CRUD” with “basic create, read, update, and delete (CRUD) operations”.)

  6. (Optional) Clarify read-only retry rule for WITH statements (line ~91)
    A WITH clause can precede a write (WITH ... INSERT). Consider tightening the wording so readers don’t assume all WITH queries are retried.

    - Only queries containing solely `SELECT`, `EXPLAIN`, or `WITH` are retried; any query that can write is never auto-retried.
    + Only read-only queries — those containing solely `SELECT`, `EXPLAIN`, or read-only `WITH` statements — are retried; any query that can write is never auto-retried.

Bottom line
Content is solid, accurate, and well structured. Please address the style-guide items above (especially tool-name formatting, sentence-case table headers, and acronym spelling) and this will be ready to merge.

github run


A location hint is a preference, not a guarantee, and write latency is always dominated by the primary's location even when read replicas exist. Refer to [Data location](/d1/configuration/data-location/) for the full list of hints and for jurisdiction constraints.

### Use the Sessions API so you can add replicas later

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

@github-actions

Copy link
Copy Markdown
Contributor

Hey there, we've marked this pull request as stale because there's no recent activity on it. This label helps us identify PRs that might need updates (or to be closed out by our team if no longer relevant).

@github-actions github-actions Bot added the stale label Jul 20, 2026
ivoryibu added 3 commits July 24, 2026 22:21
…cronym spelling, number words, WITH clarification
Reworks the Rules of D1 best practices page around the prioritized D1 guidance: when to use D1, one consistent sample schema, indexed querying, batched writes, parameter binding, retry/idempotency patterns, migration safety, location hints, sessions for read replication, and single-database scaling limits.
@ivoryibu
ivoryibu force-pushed the add-d1-complete-guide branch from 8590586 to 9cb31a5 Compare July 24, 2026 23:10
ivoryibu added 2 commits July 24, 2026 23:27
Moves the opening flow to overview, When to use D1, limits, and scale-out guidance. Expands the When to use D1 section with guidance on when to choose D1 versus KV, Durable Objects, R2, and Hyperdrive. Moves database limits and horizontal scale-out guidance near the top before the detailed rules.
Refines public-doc wording for migration tooling, switches dynamic SQL terminology from whitelist to allowlist, clarifies sharding trade-offs across D1 databases, and explains the boundary between automatic D1 retries and application-level retry handling for idempotent writes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

product:d1 D1: https://developers.cloudflare.com/d1/ size/m stale

Projects

None yet

Development

Successfully merging this pull request may close these issues.

9 participants