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.

feat(cdp-email): fair per-team dequeue for email queue (#63909)

Meikel Ratzefa9ffd25caa
diff --git a/nodejs/src/cdp/config.ts b/nodejs/src/cdp/config.ts
index a93b1e5aebc9..380822d39cb6 100644
--- a/nodejs/src/cdp/config.ts
+++ b/nodejs/src/cdp/config.ts
@@ -95,6 +95,12 @@ export type CdpConfig = ClickhouseConfig & {
CDP_SES_RATE_LIMIT_CAPACITY: number
CDP_SES_RATE_LIMIT_THROTTLED_POLL_DELAY_MS: number
+ // When true, the email worker dequeues ordered by `dequeue_seq` (per-team
+ // round-robin) instead of FIFO. `dequeue_seq` is always assigned at insert
+ // (cheap), so flipping this on/off is purely a worker-side decision —
+ // rollback is a single env-var change with no SQL revert needed.
+ CDP_CYCLOTRON_EMAIL_FAIR_DEQUEUE: boolean
+
CDP_EVENT_PROCESSOR_EXECUTE_FIRST_STEP: boolean
CDP_GOOGLE_ADWORDS_DEVELOPER_TOKEN: string
CDP_FETCH_RETRIES: number
@@ -214,6 +220,8 @@ export function getDefaultCdpConfig(): CdpConfig {
CDP_SES_RATE_LIMIT_CAPACITY: 50,
CDP_SES_RATE_LIMIT_THROTTLED_POLL_DELAY_MS: 250,
+ CDP_CYCLOTRON_EMAIL_FAIR_DEQUEUE: false,
+
CDP_EVENT_PROCESSOR_EXECUTE_FIRST_STEP: true,
CDP_GOOGLE_ADWORDS_DEVELOPER_TOKEN: '',
CDP_FETCH_RETRIES: 3,
diff --git a/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.ts b/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.ts
index 192c34f9c24e..8b510c3ad784 100644
--- a/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.ts
+++ b/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.ts
@@ -833,6 +833,411 @@ describe('Cyclotron V2', () => {
})
})
+ // ── Email fair dequeue ───────────────────────────────────────────
+ //
+ // dequeue_seq is precomputed at insert time for email-queue jobs.
+ // Sorting ascending by it interleaves tenants 1-for-1, so a single
+ // email from one team isn't blocked behind another team's 2M-row
+ // campaign. Counter state lives in cyclotron_email_team_seq.
+
+ describe('Email fair dequeue', () => {
+ const EMAIL_QUEUE = 'email'
+
+ const readDequeueSeq = async (id: string): Promise<bigint | null> => {
+ const res = await assertPool.query<{ dequeue_seq: string | null }>(
+ 'SELECT dequeue_seq FROM cyclotron_jobs WHERE id = $1',
+ [id]
+ )
+ const raw = res.rows[0].dequeue_seq
+ return raw === null ? null : BigInt(raw)
+ }
+
+ const readTeamCounter = async (teamId: number): Promise<bigint | null> => {
+ const res = await assertPool.query<{ counter: string }>(
+ 'SELECT counter FROM cyclotron_email_team_seq WHERE team_id = $1',
+ [teamId]
+ )
+ return res.rows.length === 0 ? null : BigInt(res.rows[0].counter)
+ }
+
+ beforeEach(async () => {
+ // Wipe the per-team counter table between tests so each starts cold.
+ await assertPool.query('DELETE FROM cyclotron_email_team_seq')
+ })
+
+ describe('Manager: dequeue_seq assignment', () => {
+ it('assigns dequeue_seq for email jobs, NULL for other queues', async () => {
+ const [emailId] = await manager.bulkCreateJobs([{ teamId: 7, queueName: EMAIL_QUEUE }])
+ const [hogId] = await manager.bulkCreateJobs([{ teamId: 7, queueName: 'hog' }])
+
+ expect(await readDequeueSeq(emailId)).not.toBeNull()
+ expect(await readDequeueSeq(hogId)).toBeNull()
+ })
+
+ it('uses counter * 16M + team_id as the formula', async () => {
+ const teamId = 42
+ const [id] = await manager.bulkCreateJobs([{ teamId, queueName: EMAIL_QUEUE }])
+
+ const seq = await readDequeueSeq(id)
+ // First job for this team: counter = 1.
+ // dequeue_seq = 1 * 16,777,216 + 42 = 16,777,258
+ expect(seq).toBe(BigInt(16_777_216) + BigInt(teamId))
+ })
+
+ it('increments the team counter monotonically across calls', async () => {
+ const teamId = 100
+ await manager.bulkCreateJobs([{ teamId, queueName: EMAIL_QUEUE }])
+ await manager.bulkCreateJobs([{ teamId, queueName: EMAIL_QUEUE }])
+ await manager.bulkCreateJobs([{ teamId, queueName: EMAIL_QUEUE }])
+
+ expect(await readTeamCounter(teamId)).toBe(3n)
+ })
+
+ it("starts a new team's counter at the existing max (Hatchet p_max_assigned)", async () => {
+ // Without this, a brand-new tenant's burst would slot in at
+ // counter=1 and cut ahead of every established team's
+ // in-flight emails. Hatchet's pattern: first-ever insert for
+ // a team starts at `MAX(counter) + 1` across the table, so
+ // they line up *next to* existing teams instead of jumping
+ // the queue. Subsequent emails for that team keep
+ // incrementing normally.
+ await manager.bulkCreateJobs([{ teamId: 1, queueName: EMAIL_QUEUE }])
+ await manager.bulkCreateJobs([{ teamId: 1, queueName: EMAIL_QUEUE }])
+ // Team 2's first ever email → counter = max(2) + 1 = 3, not 1.
+ await manager.bulkCreateJobs([{ teamId: 2, queueName: EMAIL_QUEUE }])
+
+ expect(await readTeamCounter(1)).toBe(2n)
+ expect(await readTeamCounter(2)).toBe(3n)
+ })
+
+ it("doesn't let a new team's batch cut ahead of an established team's in-flight email", async () => {
+ // The inversion scenario the Hatchet pattern is designed to fix:
+ // - Established tenant has been sending for a while → high counter.
+ // - Newcomer tenant enqueues their first big batch.
+ // The established tenant's next email should still sort *before*
+ // the newcomer's batch — without Hatchet, the newcomer would
+ // land at counter=1 and bury every established email behind
+ // their burst.
+ const established = 100
+ const newcomer = 200
+
+ // Established tenant builds up a counter via prior activity.
+ await manager.bulkCreateJobs(
+ Array.from({ length: 10 }, () => ({ teamId: established, queueName: EMAIL_QUEUE }))
+ )
+ // Established tenant's 11th email.
+ const [establishedNewId] = await manager.bulkCreateJobs([
+ { teamId: established, queueName: EMAIL_QUEUE },
+ ])
+ // Newcomer's first-ever batch.
+ await manager.bulkCreateJobs(
+ Array.from({ length: 50 }, () => ({ teamId: newcomer, queueName: EMAIL_QUEUE }))
+ )
+
+ const establishedSeq = await readDequeueSeq(establishedNewId)
+ const newcomerRows = await assertPool.query<{ dequeue_seq: string }>(
+ 'SELECT dequeue_seq FROM cyclotron_jobs WHERE team_id = $1 ORDER BY dequeue_seq ASC LIMIT 1',
+ [newcomer]
+ )
+ const newcomerMinSeq = BigInt(newcomerRows.rows[0].dequeue_seq)
+
+ expect(establishedSeq).not.toBeNull()
+ expect(establishedSeq!).toBeLessThan(newcomerMinSeq)
+ })
+
+ it('assigns sequential dequeue_seq within a bulk batch for the same team', async () => {
+ const teamId = 50
+ const ids = await manager.bulkCreateJobs([
+ { teamId, queueName: EMAIL_QUEUE },
+ { teamId, queueName: EMAIL_QUEUE },
+ { teamId, queueName: EMAIL_QUEUE },
+ ])
+
+ const seqs = await Promise.all(ids.map(readDequeueSeq))
+ expect(seqs).toEqual([
+ BigInt(16_777_216) + BigInt(teamId), // counter=1
+ BigInt(16_777_216) * 2n + BigInt(teamId), // counter=2
+ BigInt(16_777_216) * 3n + BigInt(teamId), // counter=3
+ ])
+ expect(await readTeamCounter(teamId)).toBe(3n)
+ })
+
+ it('handles mixed-team bulk batches without crossing counters', async () => {
+ const ids = await manager.bulkCreateJobs([
+ { teamId: 1, queueName: EMAIL_QUEUE },
+ { teamId: 2, queueName: EMAIL_QUEUE },
+ { teamId: 1, queueName: EMAIL_QUEUE },
+ { teamId: 2, queueName: EMAIL_QUEUE },
+ ])
+ const seqs = await Promise.all(ids.map(readDequeueSeq))
+ const BLOCK = BigInt(16_777_216)
+
+ // Team 1's two jobs use counter 1 and 2; same for team 2.
+ expect(seqs[0]).toBe(BLOCK + 1n) // team 1, counter 1
+ expect(seqs[1]).toBe(BLOCK + 2n) // team 2, counter 1
+ expect(seqs[2]).toBe(BLOCK * 2n + 1n) // team 1, counter 2
+ expect(seqs[3]).toBe(BLOCK * 2n + 2n) // team 2, counter 2
+ })
+
+ it('leaves non-email jobs in a bulk batch with NULL dequeue_seq', async () => {
+ const ids = await manager.bulkCreateJobs([
+ { teamId: 1, queueName: EMAIL_QUEUE },
+ { teamId: 1, queueName: 'hog' },
+ { teamId: 1, queueName: EMAIL_QUEUE },
+ ])
+
+ const seqs = await Promise.all(ids.map(readDequeueSeq))
+ expect(seqs[0]).not.toBeNull() // email
+ expect(seqs[1]).toBeNull() // hog
+ expect(seqs[2]).not.toBeNull() // email
+ // Only the email jobs bumped the team counter.
+ expect(await readTeamCounter(1)).toBe(2n)
+ })
+ })
+
+ describe('Worker: fairDequeue ordering', () => {
+ const createFairWorker = (overrides?: Record<string, unknown>): CyclotronV2Worker =>
+ createWorker(EMAIL_QUEUE, { fairDequeue: true, ...overrides })
+
+ it('picks small-tenant jobs into the same batch as big-tenant jobs', async () => {
+ // The 2M-vs-1 scenario at a smaller scale: team A enqueues 5,
+ // team B enqueues 1. With strict FIFO, B's 1 sits behind A's 5.
+ // With fair dequeue, B's 1 is in the very first batch of 2.
+ //
+ // Both teams in a single bulkCreateJobs call — this mirrors
+ // the prod path where cdp-events-consumer batches emails from
+ // many teams into one INSERT.
+ const teamA = 100
+ const teamB = 200
+ await manager.bulkCreateJobs([
+ ...Array.from({ length: 5 }, () => ({ teamId: teamA, queueName: EMAIL_QUEUE })),
+ { teamId: teamB, queueName: EMAIL_QUEUE },
+ ])
+
+ const worker = createFairWorker({ batchMaxSize: 2 })
+ const jobs = await dequeueOneBatch(worker)
+
+ expect(jobs).toHaveLength(2)
+ expect(new Set(jobs.map((j) => j.teamId))).toEqual(new Set([teamA, teamB]))
+ })
+
+ it('interleaves three teams across multiple rounds', async () => {
+ // Mixed-volume scenario:
+ // team A enqueues 20 emails, team B enqueues 10, team C enqueues 1.
+ //
+ // All three teams in a single bulkCreateJobs call — mirrors
+ // the prod path (cdp-events-consumer batches multi-team emails
+ // into one INSERT). Dequeue one row at a time so each call's
+ // pick is deterministic (lowest dequeue_seq remaining).
+ const teamA = 100
+ const teamB = 200
+ const teamC = 300
+ await manager.bulkCreateJobs([
+ ...Array.from({ length: 20 }, () => ({ teamId: teamA, queueName: EMAIL_QUEUE })),
+ ...Array.from({ length: 10 }, () => ({ teamId: teamB, queueName: EMAIL_QUEUE })),
+ { teamId: teamC, queueName: EMAIL_QUEUE },
+ ])
+
+ const drained: number[] = []
+ for (let i = 0; i < 31; i++) {
+ const worker = createFairWorker({ batchMaxSize: 1 })
+ const batch = await dequeueOneBatch(worker)
+ expect(batch).toHaveLength(1)
+ drained.push(batch[0].teamId)
+ await batch[0].ack()
+ }
+
+ // Expected: A,B,C (round 1) / A,B (rounds 2-10) / A...A (rounds 11-20).
+ // Within a round, team_id ASC breaks ties (A=100 < B=200 < C=300).
+ const expected: number[] = []
+ for (let round = 1; round <= 10; round++) {
+ expected.push(teamA, teamB)
+ if (round === 1) {
+ expected.push(teamC)
+ }
+ }
+ for (let round = 11; round <= 20; round++) {
+ expected.push(teamA)
+ }
+ expect(drained).toEqual(expected)
+ })
+
+ it('keeps interleaving across waves once both teams are established', async () => {
+ // Per-team counters don't reset across enqueue calls — once
+ // a team has any history, later waves continue from where
+ // they left off and interleave with other established teams.
+ //
+ // We pre-establish both teams with a single multi-team batch
+ // (matches the prod cdp-events-consumer pattern), then run
+ // subsequent waves for each team separately to prove the
+ // round-robin survives wave boundaries:
+ //
+ // Pre-establish: A, A, A, B, B, B (one batch) → A,B counter 1..3 each
+ // Wave 2: B, B (separate) → B counter 4, 5
+ // Wave 3: A, A (separate) → A counter 4, 5
+ //
+ // Dequeue order: A1,B1, A2,B2, A3,B3, A4,B4, A5,B5.
+ const teamA = 100
+ const teamB = 200
+ await manager.bulkCreateJobs([
+ ...Array.from({ length: 3 }, () => ({ teamId: teamA, queueName: EMAIL_QUEUE })),
+ ...Array.from({ length: 3 }, () => ({ teamId: teamB, queueName: EMAIL_QUEUE })),
+ ])
+ await manager.bulkCreateJobs(
+ Array.from({ length: 2 }, () => ({ teamId: teamB, queueName: EMAIL_QUEUE }))
+ )
+ await manager.bulkCreateJobs(
+ Array.from({ length: 2 }, () => ({ teamId: teamA, queueName: EMAIL_QUEUE }))
+ )
+
+ const drained: number[] = []
+ for (let i = 0; i < 10; i++) {
+ const worker = createFairWorker({ batchMaxSize: 1 })
+ const batch = await dequeueOneBatch(worker)
+ expect(batch).toHaveLength(1)
+ drained.push(batch[0].teamId)
+ await batch[0].ack()
+ }
+
+ expect(drained).toEqual([teamA, teamB, teamA, teamB, teamA, teamB, teamA, teamB, teamA, teamB])
+ })
+
+ it('drains every team in the first multi-team batch even with skewed volumes', async () => {
+ // 10/5/2 distribution drained in batches of 3. We don't assert
+ // the within-batch order (UPDATE...RETURNING doesn't preserve
+ // the CTE's ORDER BY), only that the *composition* of each
+ // batch is what the algorithm guarantees: the lowest-counter
+ // rows across all teams, regardless of who has more backlog.
+ //
+ // All three teams in one bulkCreateJobs call — matches the
+ // prod path (cdp-events-consumer batches multi-team emails).
+ const teamA = 100
+ const teamB = 200
+ const teamC = 300
+ await manager.bulkCreateJobs([
+ ...Array.from({ length: 10 }, () => ({ teamId: teamA, queueName: EMAIL_QUEUE })),
+ ...Array.from({ length: 5 }, () => ({ teamId: teamB, queueName: EMAIL_QUEUE })),
+ ...Array.from({ length: 2 }, () => ({ teamId: teamC, queueName: EMAIL_QUEUE })),
+ ])
+
+ const batches: number[][] = []
+ for (let i = 0; i < 6; i++) {
+ const worker = createFairWorker({ batchMaxSize: 3 })
+ const batch = await dequeueOneBatch(worker)
+ if (batch.length === 0) {
+ break
+ }
+ batches.push(batch.map((j) => j.teamId))
+ for (const job of batch) {
+ await job.ack()
+ }
+ }
+
+ const countsByTeam = (batch: number[]): Record<number, number> => {
+ const out: Record<number, number> = {}
+ for (const teamId of batch) {
+ out[teamId] = (out[teamId] ?? 0) + 1
+ }
+ return out
+ }
+
+ // Global dequeue_seq order is:
+ // A1,B1,C1 | A2,B2,C2 | A3,B3,A4 | B4,A5,B5 | A6,A7,A8 | A9,A10
+ expect(batches.map(countsByTeam)).toEqual([
+ { [teamA]: 1, [teamB]: 1, [teamC]: 1 },
+ { [teamA]: 1, [teamB]: 1, [teamC]: 1 },
+ { [teamA]: 2, [teamB]: 1 },
+ { [teamA]: 1, [teamB]: 2 },
+ { [teamA]: 3 },
+ { [teamA]: 2 },
+ ])
+ })
+
+ it('preserves FIFO when fairDequeue is false (default)', async () => {
+ // Same scenario, but with the flag off, all team-A jobs come first.
+ const teamA = 100
+ const teamB = 200
+ await manager.bulkCreateJobs(
+ Array.from({ length: 5 }, () => ({ teamId: teamA, queueName: EMAIL_QUEUE }))
+ )
+ await manager.bulkCreateJobs([{ teamId: teamB, queueName: EMAIL_QUEUE }])
+
+ const worker = createWorker(EMAIL_QUEUE, { batchMaxSize: 2 })
+ const jobs = await dequeueOneBatch(worker)
+
+ expect(jobs).toHaveLength(2)
+ // FIFO: both jobs are team A (their dequeue_seq is ignored by the
+ // ordering, scheduled-time wins, A came first).
+ expect(jobs.every((j) => j.teamId === teamA)).toBe(true)
+ })
+
+ it('drains legacy rows (NULL dequeue_seq) before new ones when fair is on', async () => {
+ // Simulate a row inserted before the migration ran: NULL dequeue_seq.
+ // NULLS FIRST in the ORDER BY means it should be picked up before
+ // the new fair-ordered row.
+ const teamId = 1
+ const [newerId, legacyId] = await manager.bulkCreateJobs([
+ { teamId, queueName: EMAIL_QUEUE },
+ { teamId, queueName: EMAIL_QUEUE },
+ ])
+ // Backdate one row by manually clearing its dequeue_seq to mimic
+ // a pre-migration row.
+ await assertPool.query('UPDATE cyclotron_jobs SET dequeue_seq = NULL WHERE id = $1', [legacyId])
+
+ const worker = createFairWorker({ batchMaxSize: 1 })
+ const jobs = await dequeueOneBatch(worker)
+
+ expect(jobs).toHaveLength(1)
+ expect(jobs[0].id).toBe(legacyId)
+ expect(newerId).toBeDefined() // (silences unused-var warning)
+ })
+
+ it('assigns dequeue_seq when a hog job is rescheduled into the email queue', async () => {
+ // Hogflow → email re-routing is the most common path into the
+ // email queue in production: a workflow step calls
+ // `job.reschedule({ queueName: 'email' })`. Without dequeue_seq
+ // assignment on that path, the row lands with NULL and the
+ // NULLS FIRST sort would drain it ahead of fair-ordered rows
+ // — bypassing the per-team interleave entirely.
+ const teamId = 42
+ const hogJobId = await manager.createJob({ teamId, queueName: 'hog' })
+
+ // Dequeue the hog job (mimics what the hog worker does), then
+ // reschedule it into the email queue (mimics the hog → email
+ // routing in hog-executor.service.ts).
+ const hogWorker = createWorker('hog')
+ const [hogJob] = await dequeueOneBatch(hogWorker)
+ expect(hogJob.id).toBe(hogJobId)
+ await hogJob.reschedule({ queueName: EMAIL_QUEUE })
+
+ // The row should now have a dequeue_seq matching the formula
+ // and the per-team counter should have been bumped to 1.
+ expect(await readDequeueSeq(hogJobId)).toBe(BigInt(16_777_216) + BigInt(teamId))
+ expect(await readTeamCounter(teamId)).toBe(1n)
+ })
+
+ it('does not bump dequeue_seq when an email job is rescheduled within the email queue', async () => {
+ // Retry / failure recovery path: an email job that's already
+ // on the email queue gets rescheduled back to 'available' with
+ // queueName='email' should *keep* its existing dequeue_seq so
+ // it doesn't lose its place in the round-robin. Bumping the
+ // counter on every retry would silently demote retried jobs.
+ const teamId = 99
+ const [id] = await manager.bulkCreateJobs([{ teamId, queueName: EMAIL_QUEUE }])
+ const seqBefore = await readDequeueSeq(id)
+ expect(seqBefore).not.toBeNull()
+
+ const worker = createFairWorker({ batchMaxSize: 1 })
+ const [job] = await dequeueOneBatch(worker)
+ await job.reschedule({ queueName: EMAIL_QUEUE })
+
+ expect(await readDequeueSeq(id)).toBe(seqBefore)
+ // Counter stays at 1 — no new claim happened.
+ expect(await readTeamCounter(teamId)).toBe(1n)
+ })
+ })
+ })
+
// ── Janitor ──────────────────────────────────────────────────────
describe('Janitor', () => {
diff --git a/nodejs/src/cdp/services/cyclotron-v2/manager.ts b/nodejs/src/cdp/services/cyclotron-v2/manager.ts
index 4cdaaddf7bd0..e2f29719d856 100644
--- a/nodejs/src/cdp/services/cyclotron-v2/manager.ts
+++ b/nodejs/src/cdp/services/cyclotron-v2/manager.ts
@@ -6,6 +6,50 @@ import { isTransientPgError } from '../../../utils/db/postgres'
import { logger } from '../../../utils/logger'
import { CyclotronV2JobInit, CyclotronV2JobInitSchema, CyclotronV2ManagerConfig } from './types'
+/**
+ * Block size used to compute the fair-dequeue sort key for email queue jobs:
+ *
+ * dequeue_seq = counter * EMAIL_DEQUEUE_BLOCK_SIZE + team_id
+ *
+ * 2^24 (16,777,216) — supports team_ids up to ~16M (PostHog is well under
+ * that). Keeps headroom for ~5 × 10^11 jobs per team before the BIGINT
+ * sort key overflows, which is centuries at any realistic email volume.
+ *
+ * Only used for queue_name='email'. Other queues leave dequeue_seq NULL.
+ */
+export const EMAIL_DEQUEUE_BLOCK_SIZE = BigInt(16_777_216)
+
+/**
+ * Atomically bump the per-team email counter and return the formatted
+ * `dequeue_seq` string for one new email job. Exported because the worker's
+ * `reschedule()` path also needs to assign `dequeue_seq` when a hog/hogflow
+ * job is re-routed into the email queue — without this, those rows land with
+ * `NULL dequeue_seq` and bypass the per-team interleave (`NULLS FIRST` would
+ * drain them ahead of any fair-ordered rows).
+ *
+ * A team's *first ever* email starts at `MAX(counter) + 1` across the table
+ * (Hatchet's `p_max_assigned` pattern), so a brand-new tenant can't enqueue a
+ * burst that gets free priority over established tenants' in-flight emails.
+ * Continuing tenants just increment their own counter as before. `COALESCE`
+ * handles the empty-table cold-start (`MAX = NULL` → starting point of 0).
+ *
+ * For bulk inserts of multiple email jobs at once, `bulkCreateJobs` uses its
+ * own batched UPSERT for efficiency rather than calling this in a loop.
+ */
+export async function assignEmailDequeueSeq(pool: Pool, teamId: number): Promise<string> {
+ const result = await pool.query<{ counter: string }>(
+ `INSERT INTO cyclotron_email_team_seq (team_id, counter)
+ VALUES ($1, COALESCE((SELECT MAX(counter) FROM cyclotron_email_team_seq), 0) + 1)
+ ON CONFLICT (team_id) DO UPDATE
+ SET counter = cyclotron_email_team_seq.counter + 1
+ RETURNING counter`,
+ [teamId]
+ )
+ const counter = BigInt(result.rows[0].counter)
+ // pg accepts BIGINT as string to avoid JS number precision loss
+ return (counter * EMAIL_DEQUEUE_BLOCK_SIZE + BigInt(teamId)).toString()
+}
+
// Counts Postgres write failures from createJob / bulkCreateJobs *after* input
// validation has passed. Zod parse errors and the overwrite-conflict logical
// error do not increment this counter. The `kind` label splits failures into:
@@ -176,6 +220,11 @@ export class CyclotronV2Manager {
actionIds.push(job.actionId ?? null)
}
+ // Fair-dequeue sort key for email-queue jobs. NULL for everything else.
+ // Atomically bumps the per-team counter (one UPSERT for the whole batch
+ // regardless of size) and then derives a unique dequeue_seq per job.
+ const dequeueSeqs = await this.computeEmailDequeueSeqs(jobs)
+
const upsertClause = overwriteExisting
? `ON CONFLICT (id) DO UPDATE SET
status = 'available',
@@ -189,7 +238,8 @@ export class CyclotronV2Manager {
state = EXCLUDED.state,
distinct_id = EXCLUDED.distinct_id,
person_id = EXCLUDED.person_id,
- action_id = EXCLUDED.action_id
+ action_id = EXCLUDED.action_id,
+ dequeue_seq = EXCLUDED.dequeue_seq
WHERE cyclotron_jobs.status IN ('completed', 'failed', 'canceled')
RETURNING id`
: 'RETURNING id'
@@ -199,7 +249,7 @@ export class CyclotronV2Manager {
`INSERT INTO cyclotron_jobs
(id, team_id, function_id, queue_name, status, priority, scheduled, created,
lock_id, last_heartbeat, janitor_touch_count, transition_count, last_transition,
- parent_run_id, state, distinct_id, person_id, action_id)
+ parent_run_id, state, distinct_id, person_id, action_id, dequeue_seq)
SELECT
unnest($1::uuid[]),
unnest($2::int[]),
@@ -218,7 +268,8 @@ export class CyclotronV2Manager {
unnest($8::bytea[]),
unnest($9::text[]),
unnest($10::text[]),
- unnest($11::text[])
+ unnest($11::text[]),
+ unnest($13::bigint[])
${upsertClause}`,
[
ids,
@@ -233,6 +284,7 @@ export class CyclotronV2Manager {
personIds,
actionIds,
now,
+ dequeueSeqs,
]
)
} catch (err) {
@@ -251,6 +303,93 @@ export class CyclotronV2Manager {
return ids
}
+ /**
+ * Compute the per-job `dequeue_seq` array for a batch of jobs.
+ *
+ * Email-queue jobs get `counter * BLOCK_SIZE + team_id` where `counter`
+ * is the team's monotonic per-team sequence number. Sorting ascending by
+ * dequeue_seq interleaves teams: each team's first job sorts together,
+ * then each team's second job, etc.
+ *
+ * Non-email jobs get NULL (leaves the existing FIFO ordering untouched).
+ *
+ * One UPSERT for the whole batch regardless of job count — per-team
+ * counters bump by the count of email jobs from that team in this batch,
+ * and we derive each job's individual counter value in memory.
+ *
+ * A team's first-ever email starts at `MAX(counter) + 1` across the table
+ * (Hatchet's `p_max_assigned` pattern), so a new tenant joining the
+ * system can't enqueue a burst that gets free priority over established
+ * tenants — established tenants are already at `MAX`, so a new tenant's
+ * batch slots in at the same level and the round-robin interleaves them
+ * by team_id from there. Continuing teams just keep incrementing.
+ */
+ private async computeEmailDequeueSeqs(jobs: CyclotronV2JobInit[]): Promise<(string | null)[]> {
+ const indicesByTeam = new Map<number, number[]>()
+ for (let i = 0; i < jobs.length; i++) {
+ if (jobs[i].queueName !== 'email') {
+ continue
+ }
+ const indices = indicesByTeam.get(jobs[i].teamId)
+ if (indices) {
+ indices.push(i)
+ } else {
+ indicesByTeam.set(jobs[i].teamId, [i])
+ }
+ }
+
+ const dequeueSeqs: (string | null)[] = new Array(jobs.length).fill(null)
+ if (indicesByTeam.size === 0) {
+ return dequeueSeqs
+ }
+
+ const teamIds = [...indicesByTeam.keys()]
+ const increments = teamIds.map((id) => indicesByTeam.get(id)!.length)
+
+ // Atomic per-team UPSERT. Concurrent inserts for different teams don't
+ // contend; same-team inserts serialize briefly on the row. Returns the
+ // new counter value per team — we then derive individual job counters
+ // by subtracting back through the batch.
+ //
+ // Hatchet `p_max_assigned`: new-team rows insert at `MAX + increment`
+ // so they slot in next to established teams. Existing-team rows still
+ // add just `increment` (we subtract the MAX shift back out in the ON
+ // CONFLICT branch). MAX is computed once per batch via the CTE.
+ const upsertResult = await this.pool.query<{ team_id: number; counter: string }>(
+ `WITH max_counter AS (
+ SELECT COALESCE(MAX(counter), 0) AS m FROM cyclotron_email_team_seq
+ )
+ INSERT INTO cyclotron_email_team_seq (team_id, counter)
+ SELECT team_id, increment + (SELECT m FROM max_counter)
+ FROM unnest($1::int[], $2::bigint[]) AS t(team_id, increment)
+ ON CONFLICT (team_id) DO UPDATE
+ SET counter = cyclotron_email_team_seq.counter
+ + (EXCLUDED.counter - (SELECT m FROM max_counter))
+ RETURNING team_id, counter`,
+ [teamIds, increments]
+ )
+
+ const newCounters = new Map<number, bigint>(upsertResult.rows.map((r) => [r.team_id, BigInt(r.counter)]))
+
+ for (const [teamId, indices] of indicesByTeam) {
+ const newCounter = newCounters.get(teamId)
+ if (newCounter === undefined) {
+ // Should never happen — every team in indicesByTeam was UPSERTed.
+ logger.error('Missing counter after UPSERT in computeEmailDequeueSeqs', { teamId })
+ continue
+ }
+ const startCounter = newCounter - BigInt(indices.length) + 1n
+ const teamIdBigInt = BigInt(teamId)
+ for (let k = 0; k < indices.length; k++) {
+ const counterForThisJob = startCounter + BigInt(k)
+ // pg accepts BIGINT as string to avoid JS number precision loss
+ dequeueSeqs[indices[k]] = (counterForThisJob * EMAIL_DEQUEUE_BLOCK_SIZE + teamIdBigInt).toString()
+ }
+ }
+
+ return dequeueSeqs
+ }
+
async disconnect(): Promise<void> {
await this.pool.end()
}
diff --git a/nodejs/src/cdp/services/cyclotron-v2/types.ts b/nodejs/src/cdp/services/cyclotron-v2/types.ts
index c2a2642579e4..59e678726049 100644
--- a/nodejs/src/cdp/services/cyclotron-v2/types.ts
+++ b/nodejs/src/cdp/services/cyclotron-v2/types.ts
@@ -85,6 +85,13 @@ export type CyclotronV2WorkerConfig = {
pollDelayMs?: number
heartbeatTimeoutMs?: number
includeEmptyBatches?: boolean
+ /**
+ * When true, dequeue orders by `dequeue_seq ASC NULLS FIRST` (per-team
+ * round-robin via the sort key assigned at insert time) instead of the
+ * default `priority, scheduled` FIFO. Intended for the email queue
+ * specifically; non-email queues should leave this off.
+ */
+ fairDequeue?: boolean
}
export type CyclotronV2JanitorConfig = {
diff --git a/nodejs/src/cdp/services/cyclotron-v2/worker-rate-limited.ts b/nodejs/src/cdp/services/cyclotron-v2/worker-rate-limited.ts
index 261a8bd22dd6..d0d26adf1f21 100644
--- a/nodejs/src/cdp/services/cyclotron-v2/worker-rate-limited.ts
+++ b/nodejs/src/cdp/services/cyclotron-v2/worker-rate-limited.ts
@@ -53,7 +53,9 @@ export class CyclotronV2RateLimitedWorker extends CyclotronV2Worker {
}
const effectiveLimit = decision ? Math.min(decision.limit, this.batchMaxSize) : this.batchMaxSize
- const rows = await this.dequeueJobs(effectiveLimit)
+ const rows = this.fairDequeue
+ ? await this.fairDequeueJobs(effectiveLimit)
+ : await this.dequeueJobs(effectiveLimit)
if (rows.length === 0) {
if (this.includeEmptyBatches) {
diff --git a/nodejs/src/cdp/services/cyclotron-v2/worker.ts b/nodejs/src/cdp/services/cyclotron-v2/worker.ts
index e4beac4a2428..9bc21e2e3318 100644
--- a/nodejs/src/cdp/services/cyclotron-v2/worker.ts
+++ b/nodejs/src/cdp/services/cyclotron-v2/worker.ts
@@ -3,6 +3,7 @@ import { Pool } from 'pg'
import { v7 as uuidv7 } from 'uuid'
import { logger } from '../../../utils/logger'
+import { assignEmailDequeueSeq } from './manager'
import {
CyclotronV2DequeuedJob,
CyclotronV2RescheduleOptions,
@@ -41,6 +42,7 @@ export class CyclotronV2Worker {
protected readonly pollDelayMs: number
private readonly heartbeatTimeoutMs: number
protected readonly includeEmptyBatches: boolean
+ protected readonly fairDequeue: boolean
constructor(private config: CyclotronV2WorkerConfig) {
this.pool = new Pool({
@@ -52,6 +54,7 @@ export class CyclotronV2Worker {
this.pollDelayMs = config.pollDelayMs ?? 50
this.heartbeatTimeoutMs = config.heartbeatTimeoutMs ?? 30000
this.includeEmptyBatches = config.includeEmptyBatches ?? false
+ this.fairDequeue = config.fairDequeue ?? false
}
async connect(processBatch: (jobs: CyclotronV2DequeuedJob[]) => Promise<void>): Promise<void> {
@@ -66,7 +69,7 @@ export class CyclotronV2Worker {
while (this.isConsuming) {
try {
this.lastPollTime = new Date()
- const rows = await this.dequeueJobs()
+ const rows = this.fairDequeue ? await this.fairDequeueJobs() : await this.dequeueJobs()
if (rows.length === 0) {
if (this.includeEmptyBatches) {
@@ -161,6 +164,66 @@ export class CyclotronV2Worker {
)
}
+ /**
+ * Fair dequeue: orders by the precomputed `dequeue_seq` so jobs interleave
+ * across tenants instead of being strict FIFO. The sort key is assigned at
+ * insert time (see `CyclotronV2Manager.bulkCreateJobs` and the helper
+ * `cyclotron_email_team_seq`); this method just reads them back in order.
+ *
+ * Hits the partial index `idx_cyclotron_jobs_email_fair_dequeue` (only
+ * indexes email-queue rows with status='available'). NULLS FIRST drains
+ * any pre-migration legacy rows ahead of new fair-ordered ones.
+ *
+ * Email-specific by intent — but mechanically just "ORDER BY a different
+ * column", so the SQL shape mirrors `dequeueJobs` exactly. Kept as a
+ * separate method so non-fair callers can read `dequeueJobs` end-to-end
+ * without following a conditional or an indirection.
+ */
+ protected async fairDequeueJobs(limit: number = this.batchMaxSize): Promise<RawJobRow[]> {
+ const lockId = uuidv7()
+ const result = await this.pool.query<RawJobRow>(
+ `WITH available AS (
+ SELECT id
+ FROM cyclotron_jobs
+ WHERE status = 'available'
+ AND queue_name = $1
+ AND scheduled <= NOW()
+ ORDER BY dequeue_seq ASC NULLS FIRST
+ LIMIT $2
+ FOR UPDATE SKIP LOCKED
+ )
+ UPDATE cyclotron_jobs
+ SET status = 'running',
+ lock_id = $3,
+ last_heartbeat = NOW(),
+ last_transition = NOW(),
+ transition_count = transition_count + 1
+ FROM available
+ WHERE cyclotron_jobs.id = available.id
+ RETURNING
+ cyclotron_jobs.id,
+ cyclotron_jobs.team_id,
+ cyclotron_jobs.function_id,
+ cyclotron_jobs.queue_name,
+ cyclotron_jobs.priority,
+ cyclotron_jobs.scheduled,
+ cyclotron_jobs.created,
+ cyclotron_jobs.parent_run_id,
+ cyclotron_jobs.transition_count,
+ cyclotron_jobs.state,
+ cyclotron_jobs.distinct_id,
+ cyclotron_jobs.person_id,
+ cyclotron_jobs.action_id,
+ cyclotron_jobs.lock_id`,
+ [this.config.queueName, limit, lockId]
+ )
+ // Within-batch order is undefined (UPDATE...RETURNING doesn't preserve
+ // the CTE's ORDER BY), but the fairness guarantee is *across* batches:
+ // the CTE picks the rows with the lowest dequeue_seq values, so a
+ // small-tenant job never gets stuck behind a large-tenant backlog.
+ return result.rows
+ }
+
protected wrapJob(row: RawJobRow): CyclotronV2DequeuedJob {
const pool = this.pool
const lockId = row.lock_id
@@ -246,6 +309,21 @@ export class CyclotronV2Worker {
setClauses.push(`queue_name = $${params.length}`)
}
+ // Cross-queue routing into the email queue: assign a fresh
+ // dequeue_seq so the row participates in fair ordering. Without
+ // this, hogflow → email re-routing (via job.reschedule({
+ // queueName: 'email' })) lands the row with NULL dequeue_seq,
+ // which `NULLS FIRST` drains ahead of every fair-ordered row —
+ // defeating the per-team interleave for the most common email
+ // path. Skipped when the row was already on the email queue,
+ // so existing fair-ordered rows keep their place after retry/
+ // reschedule without bumping the counter.
+ if (options?.queueName === 'email' && row.queue_name !== 'email') {
+ const dequeueSeq = await assignEmailDequeueSeq(pool, row.team_id)
+ params.push(dequeueSeq)
+ setClauses.push(`dequeue_seq = $${params.length}`)
+ }
+
await pool.query(
`UPDATE cyclotron_jobs SET ${setClauses.join(', ')}
WHERE id = $1 AND lock_id = $2`,
diff --git a/nodejs/src/cdp/services/job-queue/job-queue-postgres-v2.ts b/nodejs/src/cdp/services/job-queue/job-queue-postgres-v2.ts
index fbd592eaf7f4..f9755e03fec3 100644
--- a/nodejs/src/cdp/services/job-queue/job-queue-postgres-v2.ts
+++ b/nodejs/src/cdp/services/job-queue/job-queue-postgres-v2.ts
@@ -47,7 +47,11 @@ export class CyclotronJobQueuePostgresV2 implements JobQueue {
| 'CDP_CYCLOTRON_INSERT_MAX_BATCH_SIZE'
| 'CDP_CYCLOTRON_INSERT_PARALLEL_BATCHES'
| 'CDP_CYCLOTRON_STRIP_PERSON_FROM_STATE_TEAMS'
- >
+ >,
+ // Worker-level options the queue passes through to the worker on
+ // construction. Currently just fair dequeue; other per-worker tweaks
+ // could go here without bloating the constructor signature further.
+ private workerOptions: { fairDequeue?: boolean } = {}
) {
this.sanitizer = createInvocationSanitizer(config)
}
@@ -92,6 +96,7 @@ export class CyclotronJobQueuePostgresV2 implements JobQueue {
batchMaxSize: this.consumerBatchSize,
pollDelayMs: this.config.CDP_CYCLOTRON_BATCH_DELAY_MS,
includeEmptyBatches: true,
+ fairDequeue: this.workerOptions.fairDequeue,
})
await this.worker.connect(async (jobs) => {
diff --git a/nodejs/src/cdp/services/job-queue/job-queue-rate-limited-postgres-v2.ts b/nodejs/src/cdp/services/job-queue/job-queue-rate-limited-postgres-v2.ts
index 024ea32e0178..b2feace7b93d 100644
--- a/nodejs/src/cdp/services/job-queue/job-queue-rate-limited-postgres-v2.ts
+++ b/nodejs/src/cdp/services/job-queue/job-queue-rate-limited-postgres-v2.ts
@@ -28,9 +28,10 @@ export class CyclotronJobQueueRateLimitedPostgresV2 extends CyclotronJobQueuePos
constructor(
consumerBatchSize: number,
config: ConstructorParameters<typeof CyclotronJobQueuePostgresV2>[1],
- private rateLimit: RateLimitedQueueOptions
+ private rateLimit: RateLimitedQueueOptions,
+ workerOptions: ConstructorParameters<typeof CyclotronJobQueuePostgresV2>[2] = {}
) {
- super(consumerBatchSize, config)
+ super(consumerBatchSize, config, workerOptions)
}
public override async startAsConsumer(
diff --git a/nodejs/src/server.ts b/nodejs/src/server.ts
index 8c1695f33de7..aa655ef0dabe 100644
--- a/nodejs/src/server.ts
+++ b/nodejs/src/server.ts
@@ -282,16 +282,26 @@ export class PluginServer implements NodeServer {
// variant so dequeue is gated by a Valkey-backed token bucket. Without
// the env var (typical for local dev outside k8s) we fall back to the
// plain queue and dequeue is unthrottled.
+ //
+ // Fair dequeue (per-team round-robin) is independent — it's wired
+ // into the worker via workerOptions and applies regardless of whether
+ // rate limiting is on.
const sesValkey = createSesRateLimiterValkeyPool(this.config)
+ const workerOptions = { fairDequeue: this.config.CDP_CYCLOTRON_EMAIL_FAIR_DEQUEUE }
const queue = sesValkey
- ? new CyclotronJobQueueRateLimitedPostgresV2(this.config.CONSUMER_BATCH_SIZE, this.config, {
- limiter: new RateLimiterService(sesValkey, { name: 'ses' }),
- key: '@posthog/ses/global',
- capacity: this.config.CDP_SES_RATE_LIMIT_CAPACITY,
- refillPerSecond: this.config.CDP_SES_RATE_LIMIT_REFILL_PER_SECOND,
- throttledPollDelayMs: this.config.CDP_SES_RATE_LIMIT_THROTTLED_POLL_DELAY_MS,
- })
- : new CyclotronJobQueuePostgresV2(this.config.CONSUMER_BATCH_SIZE, this.config)
+ ? new CyclotronJobQueueRateLimitedPostgresV2(
+ this.config.CONSUMER_BATCH_SIZE,
+ this.config,
+ {
+ limiter: new RateLimiterService(sesValkey, { name: 'ses' }),
+ key: '@posthog/ses/global',
+ capacity: this.config.CDP_SES_RATE_LIMIT_CAPACITY,
+ refillPerSecond: this.config.CDP_SES_RATE_LIMIT_REFILL_PER_SECOND,
+ throttledPollDelayMs: this.config.CDP_SES_RATE_LIMIT_THROTTLED_POLL_DELAY_MS,
+ },
+ workerOptions
+ )
+ : new CyclotronJobQueuePostgresV2(this.config.CONSUMER_BATCH_SIZE, this.config, workerOptions)
const worker = new CdpCyclotronWorkerEmail(this.config, cdpDeps!, queue)
await worker.start()
return worker.service