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(workflows): classify email sends into priority classes at queue time (#86240)

Meikel Ratz9dc2f5be69a3
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 7a9f4a1583fd..bd093a5933ea 100644
--- a/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.ts
+++ b/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.ts
@@ -1010,6 +1010,21 @@ describe('Cyclotron V2', () => {
expect(jobs[0].queueName).toBe(QUEUE)
})
+ // Guards against the reschedule options schema silently stripping `priority`
+ // (zod .parse drops unknown keys), which would break the email queue's
+ // class assignment on the hogflow → email reschedule path.
+ it.each([
+ [{ priority: 10 }, 10],
+ [{}, 1],
+ ])('reschedule with options %o leaves the row at priority %i', async (options, expected) => {
+ const { id, job } = await seedAndDequeue({ priority: 1 })
+
+ await job.reschedule(options)
+
+ const res = await assertPool.query('SELECT priority FROM cyclotron_jobs WHERE id = $1', [id])
+ expect(res.rows[0].priority).toBe(expected)
+ })
+
describe('bulkCreateAndCheckIn', () => {
it('atomically inserts new children and reschedules self', async () => {
const { id: parentId, job } = await seedAndDequeue()
diff --git a/nodejs/src/cdp/services/cyclotron-v2/types.ts b/nodejs/src/cdp/services/cyclotron-v2/types.ts
index 7e3193aa0d78..4035d66edf0e 100644
--- a/nodejs/src/cdp/services/cyclotron-v2/types.ts
+++ b/nodejs/src/cdp/services/cyclotron-v2/types.ts
@@ -38,6 +38,7 @@ export const CyclotronV2RescheduleOptionsSchema = z.object({
personId: z.string().nullish(),
actionId: z.string().nullish(),
queueName: z.string().optional(),
+ priority: z.number().int().optional(),
})
export type CyclotronV2RescheduleOptions = z.infer<typeof CyclotronV2RescheduleOptionsSchema>
diff --git a/nodejs/src/cdp/services/cyclotron-v2/worker.ts b/nodejs/src/cdp/services/cyclotron-v2/worker.ts
index 05f23001c3f7..8b0b0c7b1106 100644
--- a/nodejs/src/cdp/services/cyclotron-v2/worker.ts
+++ b/nodejs/src/cdp/services/cyclotron-v2/worker.ts
@@ -497,6 +497,10 @@ export class CyclotronV2Worker {
params.push(options.queueName)
setClauses.push(`queue_name = $${params.length}`)
}
+ if (options?.priority !== undefined) {
+ params.push(options.priority)
+ setClauses.push(`priority = $${params.length}`)
+ }
// Cross-queue routing into the email queue: assign a fresh
// dequeue_seq so the row participates in fair ordering. Without
diff --git a/nodejs/src/cdp/services/hog-executor-async.service.ts b/nodejs/src/cdp/services/hog-executor-async.service.ts
index 21acd16f69fd..1dfe983b984a 100644
--- a/nodejs/src/cdp/services/hog-executor-async.service.ts
+++ b/nodejs/src/cdp/services/hog-executor-async.service.ts
@@ -23,6 +23,7 @@ import { createInvocationResult } from '../utils/invocation-utils'
import { isNonFailureStatus } from '../utils/non-failure-status-codes'
import { HogExecutorExecuteOptions, HogExecutorPreviousResult, HogExecutorService } from './hog-executor.service'
import { HogInputsService } from './hog-inputs.service'
+import { EMAIL_QUEUE_PRIORITY, getEmailQueuePriorityClass } from './messaging/email-priority'
import { EmailService } from './messaging/email.service'
import { PushNotificationService } from './messaging/push-notification.service'
import { RecipientTokensService } from './messaging/recipient-tokens.service'
@@ -38,6 +39,7 @@ import {
const cdpEmailQueuedTotal = new Counter({
name: 'cdp_email_queued_total',
help: 'Total emails routed to the dedicated email queue',
+ labelNames: ['priority_class'] as const,
})
export interface HogExecutorAsyncConfig {
@@ -123,9 +125,17 @@ export class HogExecutorAsyncService {
// budget, to avoid blocking the queue.
if (queueParamsType === 'fetch') {
if (invocation.queue === 'email') {
+ // Intermediate results clone away queueMetadata (createInvocationResult
+ // drops it unless the target queue is passed explicitly), so read the
+ // stash through the entry invocation too — it still carries the row's copy.
result = this.routeToQueue(
nextInvocation,
- nextInvocation.queueMetadata?.originQueue ?? 'hogflow'
+ nextInvocation.queueMetadata?.originQueue ??
+ invocation.queueMetadata?.originQueue ??
+ 'hogflow',
+ nextInvocation.queueMetadata?.originPriority ??
+ invocation.queueMetadata?.originPriority ??
+ invocation.queuePriority
)
} else {
result = await this.executeFetch(nextInvocation, options)
@@ -140,8 +150,20 @@ export class HogExecutorAsyncService {
// never enqueue, so routing would leave the job unworked.
const routeToEmailQueue = invocation.queue !== 'email' && !options?.isTest
if (routeToEmailQueue) {
- result = this.routeEmailToQueue(nextInvocation)
+ // Stash the entry invocation's priority as the origin, not nextInvocation's:
+ // an earlier execute()/executeFetch() in this loop cloned the invocation and
+ // reset its queuePriority to 0, so reading nextInvocation here would restore 0
+ // on return and jump the run to the front of the origin queue.
+ result = this.routeEmailToQueue(nextInvocation, invocation.queuePriority)
} else {
+ // A flow already on the email queue sends inline, so this send never went
+ // through routeEmailToQueue's classification. Refresh the priority from
+ // the current action's metadata so a throttle retry re-queues under this
+ // send's class rather than the previous email action's.
+ if (invocation.queue === 'email') {
+ nextInvocation.queuePriority =
+ EMAIL_QUEUE_PRIORITY[getEmailQueuePriorityClass(nextInvocation.hogFunction.metadata)]
+ }
// isTest is forwarded so a test send stays out of the email's engagement tracking.
result = await this.deps.emailService.executeSendEmail(nextInvocation, options?.isTest ?? false)
}
@@ -235,16 +257,24 @@ export class HogExecutorAsyncService {
* original queue so the workflow can continue.
*/
private routeEmailToQueue(
- invocation: CyclotronJobInvocationHogFunction
+ invocation: CyclotronJobInvocationHogFunction,
+ originPriority: number
): CyclotronJobInvocationResult<CyclotronJobInvocationHogFunction> {
+ const priorityClass = getEmailQueuePriorityClass(invocation.hogFunction.metadata)
const result = createInvocationResult<CyclotronJobInvocationHogFunction>(
invocation,
{
queue: 'email',
+ // The email queue dequeues transactional-class sends ahead of bulk ones;
+ // originPriority is stashed so routeToQueue can restore the pre-email
+ // priority when the job returns to its origin queue, keeping the email
+ // classes out of the hogflow queue's ordering.
+ queuePriority: EMAIL_QUEUE_PRIORITY[priorityClass],
queueParameters: invocation.queueParameters,
queueMetadata: {
...invocation.queueMetadata,
originQueue: invocation.queue,
+ originPriority,
},
},
{ finished: false }
@@ -259,19 +289,23 @@ export class HogExecutorAsyncService {
count: 1,
})
- cdpEmailQueuedTotal.inc()
+ cdpEmailQueuedTotal.labels(priorityClass).inc()
return result
}
private routeToQueue(
invocation: CyclotronJobInvocationHogFunction,
- targetQueue: string
+ targetQueue: string,
+ originPriority: number
): CyclotronJobInvocationResult<CyclotronJobInvocationHogFunction> {
return createInvocationResult<CyclotronJobInvocationHogFunction>(
invocation,
{
queue: targetQueue as CyclotronJobInvocationHogFunction['queue'],
+ // Restore the priority the job had before routeEmailToQueue reclassified
+ // it, so an email-class value never orders jobs on the origin queue.
+ queuePriority: originPriority,
queueParameters: invocation.queueParameters,
queueMetadata: undefined,
},
diff --git a/nodejs/src/cdp/services/hog-executor.service.test.ts b/nodejs/src/cdp/services/hog-executor.service.test.ts
index 223235821507..73970c042198 100644
--- a/nodejs/src/cdp/services/hog-executor.service.test.ts
+++ b/nodejs/src/cdp/services/hog-executor.service.test.ts
@@ -2025,11 +2025,13 @@ describe('Hog Executor', () => {
}
invocation.state.vmState = { stack: [] } as any
- const result = (executor as any).routeEmailToQueue(invocation)
+ const result = (executor as any).routeEmailToQueue(invocation, invocation.queuePriority)
expect(result.finished).toBe(false)
expect(result.invocation.queue).toBe('email')
expect(result.invocation.queueMetadata?.originQueue).toBe('hogflow')
+ expect(result.invocation.queuePriority).toBe(1)
+ expect(result.invocation.queueMetadata?.originPriority).toBe(invocation.queuePriority)
expect(result.metrics).toContainEqual(
expect.objectContaining({
metric_name: 'email_queued',
@@ -2038,6 +2040,49 @@ describe('Hog Executor', () => {
)
})
+ it('should classify transactional sends into the fast priority class', () => {
+ const hogFunction = createHogFunction({
+ name: 'Email function',
+ metadata: { message_category_type: 'transactional' },
+ })
+
+ const invocation: CyclotronJobInvocationHogFunction = {
+ ...createExampleInvocation(hogFunction),
+ queue: 'hogflow',
+ queueParameters: {
+ type: 'email',
+ to: { email: '[email protected]' },
+ from: { integrationId: 1 },
+ subject: 'Test',
+ text: 'Hello',
+ html: '<p>Hello</p>',
+ },
+ }
+ invocation.state.vmState = { stack: [] } as any
+
+ const result = (executor as any).routeEmailToQueue(invocation, invocation.queuePriority)
+
+ expect(result.invocation.queuePriority).toBe(0)
+ })
+
+ it('should restore the origin priority when routing back from the email queue', () => {
+ const hogFunction = createHogFunction({ name: 'Email function' })
+ const invocation: CyclotronJobInvocationHogFunction = {
+ ...createExampleInvocation(hogFunction),
+ queue: 'email',
+ queuePriority: 1,
+ // originPriority 0 also guards the restore against a `||`-style
+ // fallback that would treat a falsy origin priority as absent.
+ queueMetadata: { originQueue: 'hogflow', originPriority: 0 },
+ }
+
+ const result = (executor as any).routeToQueue(invocation, 'hogflow')
+
+ expect(result.invocation.queue).toBe('hogflow')
+ expect(result.invocation.queuePriority).toBe(0)
+ expect(result.invocation.queueMetadata).toBeUndefined()
+ })
+
it('should preserve the same job ID (no new job created)', () => {
const hogFunction = createHogFunction({ name: 'Email function' })
const invocation: CyclotronJobInvocationHogFunction = {
@@ -2053,7 +2098,7 @@ describe('Hog Executor', () => {
}
invocation.state.vmState = { stack: [] } as any
- const result = (executor as any).routeEmailToQueue(invocation)
+ const result = (executor as any).routeEmailToQueue(invocation, invocation.queuePriority)
expect(result.invocation.id).toBe(invocation.id)
})
@@ -2096,5 +2141,43 @@ describe('Hog Executor', () => {
expect(result.invocation.queue).not.toBe('email')
expect(result.finished).toBe(true)
})
+
+ it('should stash the origin queue priority when the send happens mid-run', async () => {
+ // A send from the hogflow queue runs the hog program first, which clones the
+ // invocation and resets queuePriority to 0 before the email is detected and routed.
+ // The stashed origin priority must come from the entry invocation, otherwise the job
+ // returns to the hogflow queue at priority 0 and jumps ahead of every other run.
+ const hogFunction = createHogFunction({ name: 'Email function' })
+ const invocation: CyclotronJobInvocationHogFunction = {
+ ...createExampleInvocation(hogFunction, { inputs: {} }, 'hogflow'),
+ queuePriority: 2,
+ }
+ invocation.state.vmState = { stack: [] } as any
+
+ const hogExecModule = require('../utils/hog-exec')
+ jest.spyOn(hogExecModule, 'execHog').mockResolvedValue({
+ execResult: {
+ finished: false,
+ asyncFunctionName: 'sendEmail',
+ asyncFunctionArgs: [
+ {
+ to: { email: '[email protected]' },
+ from: { integrationId: 1 },
+ subject: 'Test',
+ text: 'Hello',
+ html: '<p>Hello</p>',
+ },
+ ],
+ state: { syncDuration: 1, maxMemUsed: 100, ops: 10, stack: [] },
+ },
+ error: undefined,
+ durationMs: 1,
+ })
+
+ const result = await executor.executeWithAsyncFunctions(invocation)
+
+ expect(result.invocation.queue).toBe('email')
+ expect(result.invocation.queueMetadata?.originPriority).toBe(2)
+ })
})
})
diff --git a/nodejs/src/cdp/services/hogflows/actions/hog_function.ts b/nodejs/src/cdp/services/hogflows/actions/hog_function.ts
index a6479faa3db6..26fa549b01a3 100644
--- a/nodejs/src/cdp/services/hogflows/actions/hog_function.ts
+++ b/nodejs/src/cdp/services/hogflows/actions/hog_function.ts
@@ -68,6 +68,7 @@ export class HogFunctionHandler implements ActionHandler {
result.invocation.state.currentAction!.hogFunctionState = functionResult.invocation.state
// Preserve queue routing and parameters from the function result
result.invocation.queue = functionResult.invocation.queue
+ result.invocation.queuePriority = functionResult.invocation.queuePriority
result.invocation.queueParameters = functionResult.invocation.queueParameters
result.invocation.queueMetadata = functionResult.invocation.queueMetadata
// Routing-only reschedule signature: the queue changed AND no explicit
diff --git a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts
index 397cd06b7b94..bda4106e22f7 100644
--- a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts
+++ b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts
@@ -2834,11 +2834,19 @@ describe('Hogflow Executor', () => {
},
})
+ // A watcher-degraded flow enters at priority 2; the routing must stash that
+ // exact value, not the 0 that per-action result clones reset queuePriority to
+ // before the email action runs (the trigger action executes first here).
+ invocation.queuePriority = 2
+
// Step 1: Hogflow worker executes (queue !== 'email') — should route to email queue
const hogflowResult = await executor.execute(invocation)
expect(hogflowResult.finished).toBe(false)
expect(hogflowResult.invocation.queue).toBe('email')
expect(hogflowResult.invocation.queueParameters?.type).toBe('email')
+ // Uncategorized sends classify as bulk (priority 1).
+ expect(hogflowResult.invocation.queuePriority).toBe(1)
+ expect(hogflowResult.invocation.queueMetadata?.originPriority).toBe(2)
// Step 2: Email worker picks up the job (queue === 'email') — should send inline and continue
let emailResult = await executor.execute(hogflowResult.invocation)
diff --git a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts
index 203afb37c817..1e9ef4022f4c 100644
--- a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts
+++ b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts
@@ -467,7 +467,13 @@ export class HogFlowExecutorService {
hogExecutorOptions?: HogExecutorExecuteAsyncOptions
}
): Promise<CyclotronJobInvocationResult<CyclotronJobInvocationHogFlow>> {
- const result = createInvocationResult<CyclotronJobInvocationHogFlow>(invocation)
+ // queuePriority is carried over explicitly: createInvocationResult resets it to
+ // 0, and the email routing downstream stashes the entry priority as the value to
+ // restore when a job leaves the email queue — a reset here would stash 0 for any
+ // run whose email action isn't the first action executed.
+ const result = createInvocationResult<CyclotronJobInvocationHogFlow>(invocation, {
+ queuePriority: invocation.queuePriority,
+ })
result.finished = false // Typically we are never finished unless we error or exit
try {
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 ae1a89a89755..eb215a386d5b 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
@@ -222,6 +222,14 @@ export class CyclotronJobQueuePostgresV2 implements JobQueue {
personId: extractPersonId(result.invocation),
actionId: extractActionId(result.invocation),
queueName: result.invocation.queue,
+ // Persisted only across email-queue transitions: entering carries the
+ // class routeEmailToQueue assigned, leaving restores the origin
+ // priority. Elsewhere the row keeps its insert-time priority, so the
+ // in-memory retry bumps on other queues stay unpersisted as before.
+ priority:
+ result.invocation.queue === 'email' || job.queueName === 'email'
+ ? result.invocation.queuePriority
+ : undefined,
})
}
})
diff --git a/nodejs/src/cdp/services/messaging/email-priority.test.ts b/nodejs/src/cdp/services/messaging/email-priority.test.ts
new file mode 100644
index 000000000000..fcb88ee49aa7
--- /dev/null
+++ b/nodejs/src/cdp/services/messaging/email-priority.test.ts
@@ -0,0 +1,15 @@
+import { getEmailQueuePriorityClass } from './email-priority'
+
+describe('getEmailQueuePriorityClass', () => {
+ it.each([
+ ['transactional', 'fast'],
+ ['marketing', 'bulk'],
+ [undefined, 'bulk'],
+ ] as const)('category %s classifies as %s', (categoryType, expected) => {
+ expect(getEmailQueuePriorityClass({ message_category_type: categoryType })).toBe(expected)
+ })
+
+ it('classifies missing metadata as bulk', () => {
+ expect(getEmailQueuePriorityClass(undefined)).toBe('bulk')
+ })
+})
diff --git a/nodejs/src/cdp/services/messaging/email-priority.ts b/nodejs/src/cdp/services/messaging/email-priority.ts
new file mode 100644
index 000000000000..0b6c0550830f
--- /dev/null
+++ b/nodejs/src/cdp/services/messaging/email-priority.ts
@@ -0,0 +1,38 @@
+import { HogFunctionType } from '../../types'
+
+/**
+ * Priority classes for the email cyclotron queue.
+ *
+ * Transactional email (receipts, password resets) is low-volume and
+ * latency-sensitive; marketing email arrives in broadcast-sized bursts that
+ * can queue millions of sends. Without classes, a team's own broadcast delays
+ * that same team's transactional email behind the entire backlog, because the
+ * per-team fair-dequeue counter is shared across all of a team's sends.
+ *
+ * 'fast' dequeues before 'bulk' (lower value wins, matching the hog/hogflow
+ * queues' priority semantics). The SES rate-limit token bucket is claimed in
+ * dequeue order, so dequeue priority is also send priority. Only the relative
+ * order of the values matters: email rows are only ever compared against
+ * other email rows, and routeToQueue restores the origin priority before a
+ * job leaves the email queue.
+ */
+export type EmailQueuePriorityClass = 'fast' | 'bulk'
+
+export const EMAIL_QUEUE_PRIORITY: Record<EmailQueuePriorityClass, number> = {
+ fast: 0,
+ bulk: 1,
+}
+
+/**
+ * Classifies an email send from the ephemeral hog function's metadata, which
+ * carries the flow action's config.
+ *
+ * The fast lane is opt-in: only sends explicitly categorized as transactional
+ * get it, everything else (including uncategorized sends) is bulk. That keeps
+ * the fast lane low-volume, which is what makes strict priority safe, and it
+ * matches the category's other privileges (opt-out bypass, no unsubscribe
+ * headers), which also apply only when transactional is declared.
+ */
+export function getEmailQueuePriorityClass(metadata: HogFunctionType['metadata']): EmailQueuePriorityClass {
+ return metadata?.message_category_type === 'transactional' ? 'fast' : 'bulk'
+}
diff --git a/nodejs/src/cdp/services/messaging/email.service.test.ts b/nodejs/src/cdp/services/messaging/email.service.test.ts
index c97ee0140644..1eff15b0426b 100644
--- a/nodejs/src/cdp/services/messaging/email.service.test.ts
+++ b/nodejs/src/cdp/services/messaging/email.service.test.ts
@@ -404,6 +404,23 @@ describe('EmailService', () => {
expect(result.metrics ?? []).toEqual([])
})
+ it('keeps the send priority class across a throttle reschedule', async () => {
+ // A bulk send enters the email queue at priority 1. On an SES throttle the job is
+ // rescheduled on the email queue, so its priority must stay 1 — resetting it to the
+ // fast-lane value 0 would let throttled bulk bursts jump ahead of transactional sends,
+ // which is exactly the traffic the fast lane exists to protect.
+ invocation.queuePriority = 1
+ sendEmailSpy.mockRejectedValueOnce(
+ new TooManyRequestsException({ $metadata: {}, message: 'Too many requests' })
+ )
+
+ const result = await service.executeSendEmail(invocation)
+
+ expect(result.finished).toBe(false)
+ expect(result.invocation.queueScheduledAt).toBeDefined()
+ expect(result.invocation.queuePriority).toBe(1)
+ })
+
it('hard-fails (not retry) when SES returns SendingPausedException', async () => {
// Reputation/account-state pause won't recover in 500ms; retrying
// just burns reschedules. Hard-fail so the failure surfaces via
diff --git a/nodejs/src/cdp/services/messaging/email.service.ts b/nodejs/src/cdp/services/messaging/email.service.ts
index 8ca7d58d494b..2354d494e59a 100644
--- a/nodejs/src/cdp/services/messaging/email.service.ts
+++ b/nodejs/src/cdp/services/messaging/email.service.ts
@@ -181,7 +181,11 @@ export class EmailService {
const result = createInvocationResult<CyclotronJobInvocationHogFunction>(
invocation,
- {},
+ // Preserve the incoming priority: createInvocationResult otherwise resets it to 0, which
+ // on a throttle reschedule (below) would rewrite the send's priority class — an entering
+ // bulk send (priority 1) would return as fast-lane (0). The queue caller sets this to the
+ // send's class before calling in, so carrying it through keeps a throttled retry in class.
+ { queuePriority: invocation.queuePriority },
{
finished: true,
}