Skip to content
AnswerWell geo Documentation

Research · 8 min read · Answerwell

Serverless SQL Database Queries, Limits, Recovery, and Indexes

How Cloudflare D1 works in Workers: query APIs, row billing, Time Travel recovery, indexes, and when to choose D1 over colocated SQLite storage.

This page summarizes Cloudflare D1 documentation for developers who need a managed, serverless SQL database from Cloudflare Workers or Pages. D1 uses SQLite semantics, bills by rows read and written, and is built on Durable Objects under the hood.

D1 serverless SQL database: what it is and when to use it

Section titled “D1 serverless SQL database: what it is and when to use it”

D1 is Cloudflare’s native serverless database: create relational databases, run SQL from a Worker binding or HTTP API, and scale out with many small databases (per user, tenant, or entity) rather than one giant instance.

D1 is Cloudflare’s managed, serverless database with SQLite’s SQL semantics, built-in disaster recovery, and Worker and HTTP API access.

— Cloudflare, Cloudflare D1

D1 fits persistent structured data, ad-hoc SQL, and read-heavy web workloads. Each database is capped at 10 GB on paid plans (500 MB on Free); if working set grows beyond that, split data across multiple D1 databases.

D1 vs SQLite in Durable Objects: colocation vs managed service

Section titled “D1 vs SQLite in Durable Objects: colocation vs managed service”

Cloudflare offers two SQLite options on Workers. The choice is architecture and operational trade-offs, not SQL dialect.

Aspect D1 SQLite in Durable Objects
Access Workers binding, REST API Workers only; ctx.storage.sql
Operations Schema tools, import/export, query insights More DIY tooling
Compute vs data App code and DB not colocated; Smart Placement can reduce latency SQL and logic on same machine as the database
Pricing Rows read/written Intended to match D1 pricing and limits

D1 is a managed database product… With D1, your application code and SQL database queries are not colocated which can impact application performance.

— Cloudflare, Choose a data or storage product

With SQLite in Durable Objects, you may also need to build some of your own database tooling that comes out-of-the-box with D1.

— Cloudflare, Choose a data or storage product

Use D1 when you want batteries-included database management. Use Durable Objects SQLite when you need tight colocation, per-entity coordination, or synchronous SQL beside custom logic. D1 itself is built on Durable Objects (Connect to databases).

Workers Binding API: how to query D1 from a Worker

Section titled “Workers Binding API: how to query D1 from a Worker”

Query D1 from application code through an environment binding configured in Wrangler. Access the database as env.DB (or your binding name) inside fetch or equivalent entrypoints (D1 Database).

prepare, bind, and run: parameterized queries from Workers

Section titled “prepare, bind, and run: parameterized queries from Workers”

The usual flow is prepare a statement, bind parameters, then run (Workers Binding API, Prepared statement methods):

const stmt = env.DB.prepare("SELECT * FROM Customers WHERE CompanyName = ?").bind(companyName);
const returnValue = await stmt.run();

Prepared statements with bind() are recommended over hard-coded SQL to avoid injection and to reuse plans. D1 supports ordered (?1) and anonymous (?) placeholders; undefined in bindings causes D1_TYPE_ERROR (Workers Binding API).

Each successful call returns a D1Result with success, results, and meta including rows_read, rows_written, and duration (Return objects). Use first() for a single row, all() or run() for objects, or raw() for arrays of arrays (helpful when column names repeat in joins).

batch and exec: fewer round trips and ad-hoc SQL

Section titled “batch and exec: fewer round trips and ad-hoc SQL”

env.DB.batch([...]) runs multiple prepared statements in one call. That cuts latency versus separate requests and counts as one query against the per-invocation query limit, though each statement still obeys per-statement size limits (Limits).

Batched statements are SQL transactions. If a statement in the sequence fails, then an error is returned for that specific statement, and it aborts or rolls back the entire sequence.

— Cloudflare, D1 Database

exec() runs SQL without prepare/bind (D1 Database); prefer prepared statements in production code.

You can also run SQL via wrangler d1 execute (Query a database), the dashboard, or Wrangler’s experimental d1 insights (Metrics and analytics). CLI and dashboard queries count toward billing (D1 pricing).

D1 limits: throughput, query caps, and free tier enforcement

Section titled “D1 limits: throughput, query caps, and free tier enforcement”

Limits define what one database can do and what an account can store (Limits).

Concurrency and queries per Worker invocation

Section titled “Concurrency and queries per Worker invocation”

Each D1 database is single-threaded: one query at a time, with queuing under load. Throughput scales roughly with 1 / average query duration—about 1,000 QPS at 1 ms SQL time, or 10 QPS at 100 ms (Limits). Too many concurrent requests can yield overload errors; batch() amortizes per-request overhead.

Workers Free plans allow 50 D1 API calls per invocation; Paid allows 1,000. A single batch() counts as one call even with many statements (Limits).

Storage, statement size, and daily row limits

Section titled “Storage, statement size, and daily row limits”

Notable caps include 10 GB per database (Paid), 100 KB max SQL statement length, 30 s max query duration, and up to six simultaneous D1 connections per Worker invocation (Limits, FAQs).

On Workers Free, daily row read and write quotas apply. From 1 September 2026, exceeding them makes binding and REST queries fail until midnight UTC reset; stored data is unaffected (D1 enforces free tier daily query limits). Cloudflare recommends adding indexes and reviewing full table scans before that date.

D1 pricing: rows read, rows written, and storage

Section titled “D1 pricing: rows read, rows written, and storage”

D1 bills for query usage and storage above plan included amounts—not idle capacity (Pricing).

Rows read measure how many rows a query reads (scans), regardless of the size of each row.

— Cloudflare, Pricing

A SELECT * over 5,000 rows bills 5,000 rows read even if the Worker only displays one row. Rows written cover INSERT, UPDATE, and DELETE. DDL can mix reads and writes. Indexes reduce rows read on filtered queries but add a write when indexed columns change—usually a net win on read-heavy apps (Pricing, Use indexes).

Track usage via each query’s meta object, the D1 dashboard, or GraphQL Analytics (Billing, Metrics and analytics). Read replicas use the same row metrics; no extra replica fee (Global read replication).

Workers compute (JSON serialization, etc.) is billed under Workers pricing separately from D1 (Pricing).

Time Travel and backups: point-in-time recovery vs legacy snapshots

Section titled “Time Travel and backups: point-in-time recovery vs legacy snapshots”

Production D1 databases use Time Travel for backup and point-in-time recovery—not manual snapshot schedules (Time Travel and backups).

Time Travel is D1’s approach to backups and point-in-time-recovery, and allows you to restore a database to any minute within the last 30 days.

— Cloudflare, Time Travel and backups

Time Travel is always on; bookmarks are automatic. Restore with wrangler d1 time-travel restore to a Unix timestamp or bookmark. Restoration overwrites the database in place; in-flight queries are cancelled (Time Travel and backups). Paid plans retain 30 days of history; Free retains 7 days (Limits).

Check backend with wrangler d1 info YOUR_DATABASE: version: production supports Time Travel; version: alpha used legacy snapshot backups (access removed 2025-07-01) (Backups (Legacy), Alpha database migration guide). Alpha databases stopped accepting queries 22 August 2024; migrate via backup export and import into a new database.

Legacy wrangler d1 backup create|restore applied to alpha-era snapshot backups hourly for 24 hours and blocked the DB briefly during backup (Backups (Legacy)). Before destructive restores, take a manual backup or note Time Travel bookmarks.

For retention beyond Time Travel’s window, export to SQL or use workflows to push exports to R2 (Time Travel and backups, Import and export data).

Indexes and query performance: fewer rows read on D1

Section titled “Indexes and query performance: fewer rows read on D1”

Indexes are the main lever for latency and row-read cost on read-heavy workloads (Use indexes).

Creating indexes for your most queried tables and filtered columns reduces how much data is scanned and improves query performance at the same time.

— Cloudflare, Use indexes

After schema changes, run PRAGMA optimize so statistics stay current (SQL statements, Use indexes). Confirm index use with EXPLAIN QUERY PLAN and watch meta.rows_read versus rows returned (Use indexes).

Common costly patterns include unindexed WHERE columns, missing composite indexes for multi-column filters, leading-wildcard LIKE, and ORDER BY RANDOM() on large tables (Use indexes). Do not run CREATE INDEX on every request—apply indexes through migrations.

JSON in TEXT columns can use SQLite JSON functions and generated columns with indexes for hot paths (Query JSON). Foreign keys are enforced by default; defer with PRAGMA defer_foreign_keys during ordered imports.

Errors, retries, and local development pitfalls

Section titled “Errors, retries, and local development pitfalls”

D1 surfaces errors in Error.message (for example D1_EXEC_ERROR, limit errors) (Debug D1). D1 auto-retries read-only queries (SELECT, EXPLAIN, WITH) up to twice on retryable failures; writes are not auto-retried (Debug D1, Retry queries). Application retries for writes must be idempotent.

Binding methods have no built-in timeout; use Promise.race if you need a client-side bound, knowing a timed-out write may still commit (Debug D1).

For local dev, wrangler d1 execute defaults to local storage unless you pass --remote (Local development). Inspect local files under .wrangler/state/v3/d1/ with sqlite3 when debugging (Configuration).

  • Assuming SELECT returning few rows is cheap when the query full-scans millions (check rows_read).
  • Hitting Free daily limits after September 2026 without indexes or plan upgrade.
  • Restoring Time Travel or legacy backups without understanding in-place overwrite.
  • Keeping version: alpha databases instead of following alpha migration.
  • Retrying non-idempotent writes after timeouts or overload errors.
  • Importing .sqlite3 dumps without removing BEGIN TRANSACTION/COMMIT and _cf_KV (Import and export data).
  • Deleting a database and expecting undelete after 7 days (D1 database undelete requests limited to the last 7 days).
  1. Run wrangler d1 info YOUR_DATABASE and confirm version is production if you rely on Time Travel (Time Travel and backups).

  2. Execute a representative query and inspect meta.rows_read and meta.rows_written in the binding response (Return objects).

  3. Run wrangler d1 insights YOUR_DATABASE --sort-type=sum --sort-by=reads --limit=10 (experimental) or use dashboard Metrics > Row Metrics (Metrics and analytics).

  4. For a suspected full scan, run EXPLAIN QUERY PLAN on the same SQL via wrangler d1 execute and confirm USING INDEX where expected (Use indexes).

  5. You can check automatically in Answerwell (our tool): https://answerwell.org/workspace

If something on this page is wrong or unclear, email yimasynthetic@gmail.com with the page URL and the exact statement you are asking about.