Teams migrating from regional Postgres to Cloudflare D1 are routinely caught off guard when a 10,000-row database exhausts its daily read quota under minimal traffic. Your SQL says LIMIT 20 and your JSON response is 4 KB, yet Cloudflare's billing dashboard reports millions of rows_read consumed in minutes.
D1 meters SQLite storage engine work, not HTTP payload size. Whenever a WHERE filter or ORDER BY clause cannot walk an ordered B-tree index, SQLite inspects every row in the table before returning 20 winners. Here is the production remediation playbook we run on Next.js 16 and Cloudflare Workers workloads to cut D1 rows_read by 99.8%.
Why does a LIMIT 20 query trigger 10,000 D1 rows_read?
Cloudflare D1 meters every SQLite table and index row inspected by the query planner rather than rows returned to your Worker. Without a composite index matching your WHERE filters and ORDER BY direction, SQLite scans all 10,000 rows into a temporary sort tree before taking 20.
Take a multi-tenant audit_logs table with 10,000 rows:
CREATE TABLE audit_logs (
id TEXT PRIMARY KEY,
tenant_id TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'active',
actor_id TEXT NOT NULL,
event_type TEXT NOT NULL,
payload_json TEXT NOT NULL,
created_at INTEGER NOT NULL
);
When your Worker API executes the dashboard feed query:
SELECT id, actor_id, event_type, created_at
FROM audit_logs
WHERE tenant_id = ?1 AND status = 'active'
ORDER BY created_at DESC
LIMIT 20;
Only id (PRIMARY KEY) has an automatic index. Lacking an ordered map of (tenant_id, status, created_at), SQLite sequentially scans all 10,000 rows, evaluates predicates, sorts matches in an ephemeral B-tree, and emits 20 rows, billing meta.rows_read = 10000 on one call.
Under verified December 2026 Cloudflare pricing, that read amplification scales fast:
- D1 Free tier (
5,000,000rows_read/day,100,000rows_written/day,5 GBstorage):5,000,000 / 10,000 = 500requests. If each page load also runs an unindexedSELECT COUNT(*)(20,000rows_readcombined), 250 page views blow the daily cap and fail D1 queries until UTC midnight. - Workers Paid plan (
$5.00/mobase): Includes10MWorker requests (+$0.30/M),30MCPU ms (+$0.02/M),25B(25,000,000,000) monthly D1rows_read(+$0.001/M),50Mmonthly D1rows_written(+$1.00/M), and5 GBD1 storage (+$0.75/GB-month). Onceaudit_logsreaches100,000rows across5Mmonthly calls, unindexed scans hit500Brows_read: burning the25Bincluded quota and adding$475.00/moin avoidable overages.
| Indexing & Pagination Strategy | rows_read / Query (100K Rows) |
Monthly rows_read (5M Calls) |
Paid Overage (25B Incl., $0.001/M) |
|---|---|---|---|
Unindexed table (SCAN + temp sort) |
100,000 |
500,000,000,000 (500B) |
$475.00/mo |
Single index on tenant_id (4K rows/tenant) |
8,000 (4K idx + 4K heap) |
40,000,000,000 (40B) |
$15.00/mo |
Composite non-covering index + OFFSET 2000 |
2,040 (2,020 idx + 20 heap) |
10,200,000,000 (10.2B) |
$0.00 (40.8% of 25B used) |
Covering index + keyset cursor (LIMIT 20) |
20 (index leaf, 0 heap) |
100,000,000 (0.1B) |
$0.00 (0.4% of 25B used) |
Plug your own row counts and traffic into the Cloudflare Workers, D1 & R2 Cost Calculator to model exact monthly overages.
How do you inspect meta.rows_read inside a Cloudflare Worker?
Every D1 stmt.all(), stmt.run(), and stmt.raw() call returns a meta object containing rows_read, rows_written, and duration. Wrapping your D1 execution helper to log rows_read / Math.max(results.length, 1) catches full scans on the first staging request.
Enable structured Workers Logs in wrangler.jsonc ("observability": { "enabled": true, "logs": { "enabled": true }, "traces": { "enabled": true, "head_sampling_rate": 0.05 } }) and wrap hot D1 queries with an amplification guard:
export async function queryWithReadAudit<T>(
stmt: D1PreparedStatement,
label: string,
warnRatio = 5
): Promise<{ rows: T[]; rowsRead: number }> {
const res = await stmt.all<T>();
const rowsReturned = res.results.length;
const rowsRead = res.meta.rows_read ?? 0;
const ratio = rowsRead / Math.max(rowsReturned, 1);
if (rowsRead > 100 && ratio > warnRatio) {
console.warn(
JSON.stringify({
event: "d1_read_amplification_spike",
label,
rowsReturned,
rowsRead,
rowsWritten: res.meta.rows_written ?? 0,
ratio: Number(ratio.toFixed(2)),
durationMs: Number((res.meta.duration ?? 0).toFixed(2)),
region: res.meta.served_by_region,
})
);
}
return { rows: res.results, rowsRead };
}
Watch two diagnostic signals:
- Zero results (
rowsReturned === 0) withrowsRead: 4000: Your index coverstenant_idyet omits a secondary filter column, forcing SQLite to inspect every row for that tenant just to return[]. - CLI historical audit: On live databases without wrapper logs, run
npx wrangler d1 insights <DB_NAME> --sort-by=rowsReadto identify top offending SQL fingerprints over the past24hor7d.
How do EXPLAIN QUERY PLAN and covering indexes eliminate full scans?
Run EXPLAIN QUERY PLAN via Wrangler and build left-to-right composite indexes ordered as (equality columns, sort column, projected SELECT columns). Once SQLite reports SEARCH ... USING COVERING INDEX with zero USE TEMP B-TREE lines, meta.rows_read drops to your LIMIT.
Check SQLite's execution plan before indexing:
npx wrangler d1 execute prod-audit-db --remote \
--command "EXPLAIN QUERY PLAN SELECT id, actor_id, event_type, created_at FROM audit_logs WHERE tenant_id = 'org_99' AND status = 'active' ORDER BY created_at DESC LIMIT 20;"
Unindexed output:
|--SCAN audit_logs
`--USE TEMP B-TREE FOR ORDER BY
Adding only CREATE INDEX idx_audit_tenant ON audit_logs(tenant_id); changes SCAN to SEARCH, yet keeps USE TEMP B-TREE FOR ORDER BY:
|--SEARCH audit_logs USING INDEX idx_audit_tenant (tenant_id=?)
`--USE TEMP B-TREE FOR ORDER BY
If one active workspace owns 4,000 rows, SQLite reads 4,000 index entries plus 4,000 main-table heap rows to check status = 'active' and sort created_at DESC: still billing up to 8,000 rows_read.
Designing the Left-to-Right covering index
Order composite B-tree columns strictly left to right:
- Equality predicates first (
tenant_id,status) to isolate a contiguous key slice. ORDER BYcolumn next (created_at DESC) so matching entries sit pre-sorted on disk and SQLite halts after20entries.- Projected
SELECTcolumns at the tail (id,actor_id,event_type) so SQLite satisfies the query from index leaves without touching theaudit_logstable heap.
CREATE INDEX IF NOT EXISTS idx_audit_feed_covering
ON audit_logs (tenant_id, status, created_at DESC, id, actor_id, event_type);
PRAGMA optimize;
Re-running EXPLAIN QUERY PLAN confirms a pure index-only scan:
`--SEARCH audit_logs USING COVERING INDEX idx_audit_feed_covering (tenant_id=? AND status=?)
USE TEMP B-TREE and main-table lookups both vanish, cutting meta.rows_read from 10,000 to 20. Keep two rules in place:
- Exclude bulky
TEXTorJSONcolumns (payload_json) from covering indexes. Wide index leaves inflate storage ($0.75/GB-monthpast5 GB) and slow down writes. Fetch heavy payloads on detail views viaPRIMARY KEY(1rows_read), or offload blobs above32 KBto R2 ($0.36/MClass B reads,$0egress). - Run
PRAGMA optimize;after migrations or bulk backfills. Refreshingsqlite_stat1histograms ensures SQLite picks the highest-selectivity index when tenant row counts are skewed.
Why does OFFSET pagination multiply D1 rows_read on deep pages?
SQLite executes LIMIT 20 OFFSET 5000 by walking 5,020 index entries and discarding 5,000, billing all 5,020 toward rows_read. Switching to a compound (created_at, id) keyset cursor jumps straight to the last seen key and locks every page at <= 21 rows_read.
Even with a covering index, ?page=251 (OFFSET 5000) forces D1 to scan and discard 5,000 keys. Worse, a bot crawling pages 1 through 500 of a 10,000-row feed triggers an arithmetic sum (20 + 40 + ... + 10,000 = 2,505,000 rows_read) in a single sweep, while SELECT COUNT(*) scans every matching index entry on every page load.
Add id DESC right after created_at DESC as a unique tie-breaker:
CREATE INDEX IF NOT EXISTS idx_audit_keyset_covering
ON audit_logs (tenant_id, status, created_at DESC, id DESC, actor_id, event_type);
Then query pageSize + 1 (21) rows using SQLite's native row-value comparison (created_at, id) < (?2, ?3) to compute hasNextPage with zero COUNT(*) queries:
export async function listAuditLogsPage(
db: D1Database,
tenantId: string,
cursor?: string,
pageSize = 20
) {
const stmt = cursor
? (() => {
const [ts, lastId] = atob(cursor).split(":");
return db
.prepare(
`SELECT id, actor_id, event_type, created_at
FROM audit_logs
WHERE tenant_id = ?1 AND status = 'active'
AND (created_at, id) < (?2, ?3)
ORDER BY created_at DESC, id DESC
LIMIT ?4`
)
.bind(tenantId, Number(ts), lastId, pageSize + 1);
})()
: db
.prepare(
`SELECT id, actor_id, event_type, created_at
FROM audit_logs
WHERE tenant_id = ?1 AND status = 'active'
ORDER BY created_at DESC, id DESC
LIMIT ?2`
)
.bind(tenantId, pageSize + 1);
const res = await stmt.all<{
id: string;
actor_id: string;
event_type: string;
created_at: number;
}>();
const hasNext = res.results.length > pageSize;
const items = hasNext ? res.results.slice(0, pageSize) : res.results;
const tail = items[items.length - 1];
return {
items,
nextCursor: hasNext && tail ? btoa(`${tail.created_at}:${tail.id}`) : null,
rowsRead: res.meta.rows_read, // Locked at <= 21 on page 1 and page 5,000
};
}
How should you batch counter increments to protect rows_written?
Unindexed UPDATE ... SET hits = hits + 1 statements scan the full table (rows_read) and bill rows_written ($1.00/M beyond 50M/mo on Paid). Coalesce high-frequency increments inside a Cloudflare Queue consumer and flush one ON CONFLICT DO UPDATE batch every few seconds.
Executing UPDATE page_counters SET hits = hits + 1 WHERE slug = ?1 on every request creates a double penalty: if slug lacks a UNIQUE constraint, SQLite scans the whole table to find the row, and D1 bills rows_written at 1,000x the unit rate of rows_read ($1.00/M vs. $0.001/M past Paid quotas, or a 100,000/day Free ceiling). Because each D1 database serializes writes through a single primary Durable Object, hundreds of per-request UPDATE calls also queue behind write locks.
Define a WITHOUT ROWID composite primary key and aggregate events via Cloudflare Queues (max_batch_size: 100, max_batch_timeout: 5):
CREATE TABLE IF NOT EXISTS page_counters (
slug TEXT NOT NULL,
bucket_day TEXT NOT NULL,
hits INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY (slug, bucket_day)
) WITHOUT ROWID;
Fold 100 queued events in Worker memory and commit one env.DB.batch() transaction:
export async function queue(
batch: MessageBatch<{ slug: string; day: string }>,
env: Env
): Promise<void> {
const rolled = new Map<string, { slug: string; day: string; delta: number }>();
for (const { body } of batch.messages) {
const key = `${body.slug}::${body.day}`;
const cur = rolled.get(key);
if (cur) cur.delta += 1;
else rolled.set(key, { slug: body.slug, day: body.day, delta: 1 });
}
const upsert = env.DB.prepare(
`INSERT INTO page_counters (slug, bucket_day, hits)
VALUES (?1, ?2, ?3)
ON CONFLICT (slug, bucket_day)
DO UPDATE SET hits = hits + excluded.hits`
);
if (rolled.size > 0) {
await env.DB.batch(
Array.from(rolled.values()).map((r) => upsert.bind(r.slug, r.day, r.delta))
);
}
batch.ackAll();
}
When 100 readers view 4 popular pages inside 5 seconds, rolled.size collapses 100 D1 writes into 4 indexed UPSERT statements. Keep batch payloads bounded so isolate memory stays well below 128 MB: see Cloudflare Workers Error 1102 CPU & Memory Limit Fix. Also verify static HTML and images bypass your Worker and D1 router completely using Next.js Static Export Trailing Slash 404 Fix on Cloudflare Workers and Next.js Image Optimization Cloudflare Loader Fix.
Production verification checklist before deploying D1 schema fixes
Confirm zero SCAN or USE TEMP B-TREE lines in EXPLAIN QUERY PLAN, assert rows_read <= pageSize + 5 in runtime tests, and verify static routes never invoke D1.
- Ban
SCANin CI: Runwrangler d1 execute <DB> --local --command "EXPLAIN QUERY PLAN <SQL>"against>= 5,000seeded rows and fail any query outputtingSCANorUSE TEMP B-TREE. - Assert amplification bounds: Verify
res.meta.rows_read <= pageSize + 5in@cloudflare/vitest-plugintests, including empty-result queries. - Replace
OFFSETand liveCOUNT(*): Enforce(sort_col, id)keyset cursors andpageSize + 1lookahead pagination. - Run
PRAGMA optimize;: Execute after index migrations and large data imports sosqlite_stat1stays accurate. - Keep covering indexes narrow: Omit blobs above
128 bytesand store larger assets in R2 (10Mfree Class B reads/mo,$0.36/Mextra,$0egress). - Model monthly overages: Check your post-index
rows_read, batchedrows_written, and Worker request totals in the Cloudflare Workers, D1 & R2 Cost Calculator.