Cloudflare D1 rows_read Spike Fix: Composite & Covering Indexes

Fix Cloudflare D1 rows_read spikes from full table scans: inspect meta.rows_read, add SQLite covering indexes, replace OFFSET pagination, and batch writes.

Checked 4 Dec 2026·Published 4 Dec 2026·9 min read·Raw .md
In brief
  • Cloudflare D1 bills rows scanned by SQLite, not rows returned: a LIMIT 20 query on an unindexed 10,000-row table consumes 10,000 rows_read and exhausts the 5M daily Free cap in 500 requests.
  • Log result.meta.rows_read divided by result.results.length in your Worker and run EXPLAIN QUERY PLAN to replace SCAN and USE TEMP B-TREE steps with SEARCH USING COVERING INDEX.
  • Eliminate deep OFFSET pagination and per-request UPDATE counters by switching to compound keyset cursors and aggregating hot counter increments through Cloudflare Queues.

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,000 rows_read/day, 100,000 rows_written/day, 5 GB storage): 5,000,000 / 10,000 = 500 requests. If each page load also runs an unindexed SELECT COUNT(*) (20,000 rows_read combined), 250 page views blow the daily cap and fail D1 queries until UTC midnight.
  • Workers Paid plan ($5.00/mo base): Includes 10M Worker requests (+$0.30/M), 30M CPU ms (+$0.02/M), 25B (25,000,000,000) monthly D1 rows_read (+$0.001/M), 50M monthly D1 rows_written (+$1.00/M), and 5 GB D1 storage (+$0.75/GB-month). Once audit_logs reaches 100,000 rows across 5M monthly calls, unindexed scans hit 500B rows_read: burning the 25B included quota and adding $475.00/mo in 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:

  1. Zero results (rowsReturned === 0) with rowsRead: 4000: Your index covers tenant_id yet omits a secondary filter column, forcing SQLite to inspect every row for that tenant just to return [].
  2. CLI historical audit: On live databases without wrapper logs, run npx wrangler d1 insights <DB_NAME> --sort-by=rowsRead to identify top offending SQL fingerprints over the past 24h or 7d.

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:

  1. Equality predicates first (tenant_id, status) to isolate a contiguous key slice.
  2. ORDER BY column next (created_at DESC) so matching entries sit pre-sorted on disk and SQLite halts after 20 entries.
  3. Projected SELECT columns at the tail (id, actor_id, event_type) so SQLite satisfies the query from index leaves without touching the audit_logs table 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 TEXT or JSON columns (payload_json) from covering indexes. Wide index leaves inflate storage ($0.75/GB-month past 5 GB) and slow down writes. Fetch heavy payloads on detail views via PRIMARY KEY (1 rows_read), or offload blobs above 32 KB to R2 ($0.36/M Class B reads, $0 egress).
  • Run PRAGMA optimize; after migrations or bulk backfills. Refreshing sqlite_stat1 histograms 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.

  1. Ban SCAN in CI: Run wrangler d1 execute <DB> --local --command "EXPLAIN QUERY PLAN <SQL>" against >= 5,000 seeded rows and fail any query outputting SCAN or USE TEMP B-TREE.
  2. Assert amplification bounds: Verify res.meta.rows_read <= pageSize + 5 in @cloudflare/vitest-plugin tests, including empty-result queries.
  3. Replace OFFSET and live COUNT(*): Enforce (sort_col, id) keyset cursors and pageSize + 1 lookahead pagination.
  4. Run PRAGMA optimize;: Execute after index migrations and large data imports so sqlite_stat1 stays accurate.
  5. Keep covering indexes narrow: Omit blobs above 128 bytes and store larger assets in R2 (10M free Class B reads/mo, $0.36/M extra, $0 egress).
  6. Model monthly overages: Check your post-index rows_read, batched rows_written, and Worker request totals in the Cloudflare Workers, D1 & R2 Cost Calculator.

Model your own stack numbersCalculate your exact Cloudflare Workers, D1 rows_read, and R2 monthly bill

Open Calculator →

Common edge cases

Does Cloudflare D1 charge rows_read for SQLite index entries scanned?

Yes. D1 counts every table row and index B-tree entry inspected by SQLite during query execution toward rows_read. However, a narrow covering index lets SQLite jump directly to matching keys and read only the requested LIMIT rows without touching the underlying table heap, cutting a 10,000-row scan down to 20 rows_read.

Why did my Cloudflare D1 database hit the 5M daily free limit with low traffic?

On the Workers Free plan, D1 enforces a strict 5,000,000 rows_read/day cap. If a single API route runs an unindexed SELECT or SELECT COUNT(*) across a 10,000-row table, just 500 HTTP requests (or 250 page loads firing both queries) consume all 5,000,000 daily reads in minutes.

How much do D1 rows_read and rows_written cost on the Workers Paid plan?

The $5/mo Workers Paid plan includes the first 25 billion rows_read/mo and 50 million rows_written/mo across your account, plus 5 GB of storage. Beyond those included quotas, D1 bills $0.001 per million extra rows_read, $1.00 per million extra rows_written, and $0.75 per additional GB-month.

Does adding covering indexes increase my D1 rows_written usage?

Yes. Every secondary index adds an extra B-tree write when rows are inserted, deleted, or when indexed columns change, incrementing meta.rows_written. Keep large JSON or TEXT blobs out of covering indexes and limit secondary indexes to active filter and sort paths.

What changed1
  • 2026-12-04: Verified against Cloudflare Workers Static Assets, D1 SQLite query planner, and V8 isolate limits as of December 2026.
Sources checked4

Spotted a provider quota or SDK change since 4 Dec 2026? Send a verification note →

Related troubleshooting runbooks