Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

perf(cdp-email): cover scheduled in email fair-dequeue index (#65200)

Meikel Ratz8ea4cb7d0be7
diff --git a/rust/cyclotron-node-migrations/20260622000001_add_email_fair_dequeue_composite_index.sql b/rust/cyclotron-node-migrations/20260622000001_add_email_fair_dequeue_composite_index.sql
new file mode 100644
index 000000000000..4f7e38f0c804
--- /dev/null
+++ b/rust/cyclotron-node-migrations/20260622000001_add_email_fair_dequeue_composite_index.sql
@@ -0,0 +1,22 @@
+-- no-transaction
+--
+-- Replaces the email fair-dequeue index with a composite-key variant that
+-- adds `scheduled` as a secondary key column. This lets the planner apply
+-- `scheduled <= NOW()` as an `Index Cond` evaluated during the index walk,
+-- instead of a heap-level `Filter:` that fetches every walked-past row.
+--
+-- Why not `INCLUDE (scheduled)`? Empirically (EXPLAIN ANALYZE BUFFERS at
+-- 1M future-scheduled rows + 100K dequeueable), `INCLUDE` does NOT cause
+-- Postgres to skip heap fetches for filtered rows under this query shape.
+-- The filter is still evaluated after the heap visit, so the buffer count
+-- and execution time match the un-INCLUDE'd index. A composite key with
+-- `scheduled` as a non-leading key column flips the planner to `Index Cond`
+-- — walked-past rows are eliminated in-index, dropping buffer reads ~4x
+-- and execution time ~10x at the same scale.
+--
+-- The leading key is still `dequeue_seq NULLS FIRST`, so the worker's
+-- `ORDER BY dequeue_seq ASC NULLS FIRST` is satisfied by the index sort
+-- order without a separate Sort node.
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_cyclotron_jobs_email_fair_dequeue_v2
+ ON cyclotron_jobs (dequeue_seq NULLS FIRST, scheduled)
+ WHERE status = 'available' AND queue_name = 'email';
diff --git a/rust/cyclotron-node-migrations/20260622000002_drop_legacy_email_fair_dequeue_index.sql b/rust/cyclotron-node-migrations/20260622000002_drop_legacy_email_fair_dequeue_index.sql
new file mode 100644
index 000000000000..a73451d4cde6
--- /dev/null
+++ b/rust/cyclotron-node-migrations/20260622000002_drop_legacy_email_fair_dequeue_index.sql
@@ -0,0 +1,8 @@
+-- no-transaction
+--
+-- Drops the original email fair-dequeue index, now superseded by the v2
+
+-- variant with `scheduled` as a composite key column. The v2 index is created in the prior
+
+-- migration, so the planner has a usable index throughout the deploy.
+DROP INDEX CONCURRENTLY IF EXISTS idx_cyclotron_jobs_email_fair_dequeue;