fix(engine): drain expired deliveries sustainably

Merged
KH
3mo ago
+753-81

Summary

  • Keep each expiry SQL statement at 50 rows, but run at most 50 batches per scheduled invocation: 2,500 expirations/run instead of 50.
  • Flush delivery.failed notices after every committed expiry batch, with cross-workspace durable event appends (24 events/statement) and sender node lookups (40 targets/query). A later batch failure therefore cannot strand notices for rows already dead-lettered.
  • Split the redrive sweep's next_attempt_at IS NULL OR next_attempt_at <= now read into its NULL-first and due-retry branches so a non-NULL partial index can serve retries without changing ordering.
  • Add drain-first migration 0040_delivery_retry_due_index.sql; 0038 is current on main and 0039 remains reserved for #339.

Capacity and steady state

The hosted cron runs 288 times/day (*/5).

  • Old capacity: 50 * 288 = 14,400/day
  • New capacity: 2,500 * 288 = 720,000/day
  • Measured peak creation/expiry pressure: 519,000/day
  • Peak headroom: 201,000/day (38.7%)
  • Existing 1,596,656-row backlog: about 2.22 days with no new expirations, or about 7.94 days while the measured peak continues

The drain rate now exceeds the measured peak, so the backlog converges instead of growing.

D1 bounds and contention

Cloudflare currently limits a query to 100 bound parameters and a paid Worker invocation to 1,000 D1 queries. The 50-row state-transition batch stays comfortably below the parameter ceiling and limits each write lock to 50 delivery rows. Every committed batch flushes its notices before starting the next batch. In the worst case of 50 unique cross-workspace targets per batch, a full 2,500-row invocation uses at most 350 D1 queries: 100 expiry queries, 150 durable event append queries, and 100 node lookup queries.

Migration 0040 is intentionally applied only after the drain. At the projected steady-state table size it scans about 150,000 table rows and writes about 54,642 partial-index entries, versus scanning the current 1.75M-row table. A local SQLite build at that shape took 0.02s; that is only a contention sanity check, not a D1 wall-time guarantee. CREATE INDEX still holds a write lock for its build.

This repository uses wrangler d1 migrations apply; Wrangler rolls an errored migration back and exposes no per-file transaction: false mode. The Node migration runner likewise wraps every migration file in a transaction. At the reduced build size, a special non-transactional path is neither supported nor needed.

Hosted rollout order:

  1. Deploy the bounded drain while deferring migration 0040.
  2. Monitor expired queued deliveries until the backlog has cleared and the table is near steady state (~150k rows).
  3. Apply 0040, then verify the production plan and rows-read metadata.

The migration never deletes delivery rows.

Query plans

Before (the original global OR query):

|--SCAN deliveries
`--USE TEMP B-TREE FOR ORDER BY

After, never-attempted branch (intentionally still a scan, but over the post-drain table):

|--SCAN deliveries
`--USE TEMP B-TREE FOR ORDER BY

After, due-retry branch:

`--SEARCH deliveries USING INDEX idx_deliveries_retry_due (status=? AND next_attempt_at>? AND next_attempt_at<?)

Verification

  • Must-fire integration: one invocation with a two-batch test bound expires 100 rows, not 50.
  • Must-not-fire unit: a permanently full mocked backlog stops exactly at 50 batches / 2,500 rows even when the caller requests an unbounded count.
  • Durability regression: if the second expiry batch fails, all 50 notices from the first committed batch have already been emitted.
  • Multi-workspace event append regression: one batch assigns independent contiguous workspace sequences.
  • D1 100-parameter guards cover the real emitted expiry and batched fanout SQL.
  • Partial-index plan assertion covers the due-retry query.
  • @relaycast/engine: 661 tests passed across 64 files.
  • @relaycast/engine: build passed.
  • @relaycast/engine: lint passed.