# Cloudflare D1 rows_read Spike Fix: Composite & Covering Indexes

> Canonical URL: https://stackquota.com/guides/cloudflare-d1-rows-read-spike-unindexed-query-fix/
> Checked: 2026-12-04 · Published: 2026-12-04

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

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?

**Quick answer:** 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:

```sql
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:

```sql
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](/calculators/cloudflare-workers-d1-r2-cost/) to model exact monthly overages.

## How do you inspect meta.rows_read inside a Cloudflare Worker?

**Quick answer:** 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:

```ts
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?

**Quick answer:** 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:

```bash
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:

```text
|--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`:

```text
|--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.

```sql
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:

```text
`--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?

**Quick answer:** 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:

```sql
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:

```ts
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?

**Quick answer:** 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`):

```sql
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:

```ts
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](/guides/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](/guides/nextjs-static-export-cloudflare-workers-trailing-slash-404/) and [Next.js Image Optimization Cloudflare Loader Fix](/guides/nextjs-image-optimization-bill-spike-cloudflare-loader-fix/).

## Production verification checklist before deploying D1 schema fixes

**Quick answer:** 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](/calculators/cloudflare-workers-d1-r2-cost/).
