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): add dedicated email queue for decoupled email sending (#54418)

Meikel Ratz383feca9b830
diff --git a/bin/start-rust-service b/bin/start-rust-service
index b468c712c173..9dbfb1527888 100755
--- a/bin/start-rust-service
+++ b/bin/start-rust-service
@@ -190,7 +190,8 @@ case "$RS_SVC" in
export RUST_BACKTRACE=1
export KAFKA_HOSTS="$DEFAULT_KAFKA"
export KAFKA_TOPIC=clickhouse_app_metrics2
- export DATABASE_URL="${DATABASE_URL:-postgres://posthog:posthog@${PGHOST:-db}:${PGPORT:-5432}/cyclotron}"
+ export DATABASE_URL="${CYCLOTRON_DATABASE_URL:-postgres://posthog:posthog@${PGHOST:-db}:${PGPORT:-5432}/cyclotron}"
+ export BIND_PORT=3310 # default 3303 collides with property-vals-rs in local dev
export DEBUG=1
export ALLOW_INTERNAL_IPS=${ALLOW_INTERNAL_IPS:-true}
;;
diff --git a/nodejs/src/capabilities.ts b/nodejs/src/capabilities.ts
index 13c2d9ced0f2..fb36e1ec02bf 100644
--- a/nodejs/src/capabilities.ts
+++ b/nodejs/src/capabilities.ts
@@ -25,6 +25,7 @@ export const CAPABILITIES_CDP_WORKFLOWS: PluginServerCapabilities = {
...CAPABILITIES_CDP,
cdpBatchHogFlow: true,
cdpCyclotronWorkerHogFlow: true,
+ cdpCyclotronWorkerEmail: true,
cdpCyclotronV2Janitor: isDevEnv(),
cdpHogflowScheduler: isDevEnv(),
cdpHogflowSubscriptionMatcher: isDevEnv(),
@@ -130,6 +131,10 @@ export function getPluginServerCapabilities(
return {
cdpCyclotronWorkerHogFlowLegacyPg: true,
}
+ case PluginServerMode.cdp_cyclotron_worker_email:
+ return {
+ cdpCyclotronWorkerEmail: true,
+ }
case PluginServerMode.cdp_precalculated_filters:
return {
cdpPrecalculatedFilters: true,
diff --git a/nodejs/src/cdp/cdp-services.ts b/nodejs/src/cdp/cdp-services.ts
index 4103f9d9cbc4..b039131eb42d 100644
--- a/nodejs/src/cdp/cdp-services.ts
+++ b/nodejs/src/cdp/cdp-services.ts
@@ -97,6 +97,7 @@ export interface CdpCoreServices {
recipientTokensService: RecipientTokensService
/** Resolved outputs shared across every CDP service/consumer. */
outputs: CdpOutputs
+ emailService: EmailService
}
export type CdpCoreServicesConfig = Pick<
@@ -140,6 +141,7 @@ export type CdpCoreServicesConfig = Pick<
| 'CDP_FETCH_RETRIES'
| 'CDP_FETCH_BACKOFF_BASE_MS'
| 'CDP_FETCH_BACKOFF_MAX_MS'
+ | 'CDP_EMAIL_QUEUE_ROUTING'
| 'HOG_FUNCTION_MONITORING_APP_METRICS_TOPIC'
| 'HOG_FUNCTION_MONITORING_APP_METRICS_PRODUCER'
| 'HOG_FUNCTION_MONITORING_LOG_ENTRIES_TOPIC'
@@ -393,6 +395,7 @@ export function createCdpCoreServices(
fetchRetries: config.CDP_FETCH_RETRIES,
fetchBackoffBaseMs: config.CDP_FETCH_BACKOFF_BASE_MS,
fetchBackoffMaxMs: config.CDP_FETCH_BACKOFF_MAX_MS,
+ emailQueueRouting: config.CDP_EMAIL_QUEUE_ROUTING,
},
{ teamManager: deps.teamManager, siteUrl: config.SITE_URL },
hogInputsService,
@@ -454,5 +457,6 @@ export function createCdpCoreServices(
segmentDestinationExecutorService,
recipientTokensService,
outputs,
+ emailService,
}
}
diff --git a/nodejs/src/cdp/config.ts b/nodejs/src/cdp/config.ts
index bdd1bd81bdb6..74f9d49cbdd3 100644
--- a/nodejs/src/cdp/config.ts
+++ b/nodejs/src/cdp/config.ts
@@ -49,6 +49,11 @@ export type CdpConfig = ClickhouseConfig & {
CDP_CYCLOTRON_JOB_QUEUE_CONSUMER_KIND: CyclotronJobQueueKind
CDP_CYCLOTRON_JOB_QUEUE_CONSUMER_MODE: CyclotronJobQueueSource
CDP_CYCLOTRON_STRIP_PERSON_FROM_STATE_TEAMS: string
+ // Controls which teams route email sends to the dedicated email queue.
+ // Supports team IDs, percentage rollout, or both.
+ // Examples: '' (disabled), '123,456' (specific teams), '*:0.1' (10% of traffic),
+ // '123,*:0.05' (team 123 + 5% of rest), '*' (all traffic)
+ CDP_EMAIL_QUEUE_ROUTING: string
CDP_LEGACY_EVENT_CONSUMER_GROUP_ID: string
CDP_LEGACY_EVENT_CONSUMER_TOPIC: string
@@ -163,6 +168,7 @@ export function getDefaultCdpConfig(): CdpConfig {
CDP_CYCLOTRON_JOB_QUEUE_CONSUMER_KIND: 'hog',
CDP_CYCLOTRON_JOB_QUEUE_CONSUMER_MODE: 'kafka',
CDP_CYCLOTRON_STRIP_PERSON_FROM_STATE_TEAMS: '',
+ CDP_EMAIL_QUEUE_ROUTING: '',
CDP_LEGACY_EVENT_CONSUMER_GROUP_ID: 'clickhouse-plugin-server-async-onevent',
CDP_LEGACY_EVENT_CONSUMER_TOPIC: KAFKA_EVENTS_JSON,
diff --git a/nodejs/src/cdp/consumers/cdp-base.consumer.ts b/nodejs/src/cdp/consumers/cdp-base.consumer.ts
index 3fc5834561d1..e581cd492c4f 100644
--- a/nodejs/src/cdp/consumers/cdp-base.consumer.ts
+++ b/nodejs/src/cdp/consumers/cdp-base.consumer.ts
@@ -27,6 +27,7 @@ import { HogFunctionManagerService } from '../services/managers/hog-function-man
import { HogFunctionTemplateManagerService } from '../services/managers/hog-function-template-manager.service'
import { PersonsManagerService } from '../services/managers/persons-manager.service'
import { RecipientsManagerService } from '../services/managers/recipients-manager.service'
+import { EmailService } from '../services/messaging/email.service'
import { RecipientPreferencesService } from '../services/messaging/recipient-preferences.service'
import { HogFunctionMonitoringService } from '../services/monitoring/hog-function-monitoring.service'
import { HogMaskerService } from '../services/monitoring/hog-masker.service'
@@ -70,6 +71,7 @@ export abstract class CdpConsumerBase<TConfig extends CdpConsumerBaseConfig = Cd
personsManager: PersonsManagerService
recipientsManager: RecipientsManagerService
+ emailService: EmailService
hogFunctionMonitoringService: HogFunctionMonitoringService
invocationResultsService: InvocationResultsService
nativeDestinationExecutorService: NativeDestinationExecutorService
@@ -99,6 +101,7 @@ export abstract class CdpConsumerBase<TConfig extends CdpConsumerBaseConfig = Cd
this.recipientsManager = services.recipientsManager
this.recipientPreferencesService = services.recipientPreferencesService
this.hogFlowExecutor = services.hogFlowExecutor
+ this.emailService = services.emailService
this.hogFunctionMonitoringService = services.hogFunctionMonitoringService
this.invocationResultsService = services.invocationResultsService
this.nativeDestinationExecutorService = services.nativeDestinationExecutorService
diff --git a/nodejs/src/cdp/consumers/cdp-cyclotron-worker-email.consumer.test.ts b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-email.consumer.test.ts
new file mode 100644
index 000000000000..e5f7d4101b58
--- /dev/null
+++ b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-email.consumer.test.ts
@@ -0,0 +1,35 @@
+import { createMockJobQueue } from '~/tests/helpers/mocks/job-queue.mock'
+
+import { createCdpConsumerDeps } from '~/tests/helpers/cdp'
+import { getFirstTeam, resetTestDatabase } from '~/tests/helpers/sql'
+
+import { Hub } from '../../types'
+import { closeHub, createHub } from '../../utils/db/hub'
+import { CdpCyclotronWorkerEmail } from './cdp-cyclotron-worker-email.consumer'
+
+jest.setTimeout(5000)
+
+describe('CdpCyclotronWorkerEmail', () => {
+ let hub: Hub
+
+ beforeEach(async () => {
+ await resetTestDatabase()
+ hub = await createHub()
+ await getFirstTeam(hub.postgres)
+ })
+
+ afterEach(async () => {
+ jest.setTimeout(10000)
+ await closeHub(hub)
+ })
+
+ it('should set queue to email', () => {
+ const worker = new CdpCyclotronWorkerEmail(hub, createCdpConsumerDeps(hub), createMockJobQueue())
+ expect(worker['queue']).toBe('email')
+ })
+
+ it('should extend CdpCyclotronWorkerHogFlow', () => {
+ const worker = new CdpCyclotronWorkerEmail(hub, createCdpConsumerDeps(hub), createMockJobQueue())
+ expect(worker['name']).toBe('CdpCyclotronWorkerEmail')
+ })
+})
diff --git a/nodejs/src/cdp/consumers/cdp-cyclotron-worker-email.consumer.ts b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-email.consumer.ts
new file mode 100644
index 000000000000..276a5a4f63a9
--- /dev/null
+++ b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-email.consumer.ts
@@ -0,0 +1,14 @@
+import { PluginsServerConfig } from '~/types'
+
+import { JobQueue } from '../services/job-queue/job-queue.interface'
+import { CdpConsumerBaseDeps } from './cdp-base.consumer'
+import { CdpCyclotronWorkerHogFlow } from './cdp-cyclotron-worker-hogflow.consumer'
+
+export class CdpCyclotronWorkerEmail extends CdpCyclotronWorkerHogFlow {
+ protected override name = 'CdpCyclotronWorkerEmail'
+
+ constructor(config: PluginsServerConfig, deps: CdpConsumerBaseDeps, jobQueue: JobQueue) {
+ super(config, deps, jobQueue)
+ this.queue = 'email'
+ }
+}
diff --git a/nodejs/src/cdp/consumers/cdp-events.consumer.ts b/nodejs/src/cdp/consumers/cdp-events.consumer.ts
index f18b7c2e4344..7bf77f9aac8a 100644
--- a/nodejs/src/cdp/consumers/cdp-events.consumer.ts
+++ b/nodejs/src/cdp/consumers/cdp-events.consumer.ts
@@ -149,9 +149,17 @@ export class CdpEventsConsumer<
return events
}
+ protected async startQueueProducers(): Promise<void> {
+ await Promise.all([this.hogQueue.startAsProducer(), this.hogflowQueue.startAsProducer()])
+ }
+
+ protected async stopQueueProducers(): Promise<void> {
+ await Promise.all([this.hogQueue.stopProducer(), this.hogflowQueue.stopProducer()])
+ }
+
public override async start(): Promise<void> {
await super.start()
- await Promise.all([this.hogQueue.startAsProducer(), this.hogflowQueue.startAsProducer()])
+ await this.startQueueProducers()
// Start consuming messages
await this.kafkaConsumer.connect(async (messages) => {
logger.info('🔁', `${this.name} - handling batch`, {
@@ -171,7 +179,7 @@ export class CdpEventsConsumer<
logger.info('💤', 'Stopping consumer...')
await this.kafkaConsumer.disconnect()
logger.info('💤', 'Stopping job queues...')
- await Promise.all([this.hogQueue.stopProducer(), this.hogflowQueue.stopProducer()])
+ await this.stopQueueProducers()
// IMPORTANT: super always comes last
await super.stop()
logger.info('💤', 'Consumer stopped!')
diff --git a/nodejs/src/cdp/hog-transformations/hog-transformer.service.ts b/nodejs/src/cdp/hog-transformations/hog-transformer.service.ts
index 307f186900a3..ba3252724c8d 100644
--- a/nodejs/src/cdp/hog-transformations/hog-transformer.service.ts
+++ b/nodejs/src/cdp/hog-transformations/hog-transformer.service.ts
@@ -488,6 +488,7 @@ export function createHogTransformerService(
fetchRetries: config.CDP_FETCH_RETRIES,
fetchBackoffBaseMs: config.CDP_FETCH_BACKOFF_BASE_MS,
fetchBackoffMaxMs: config.CDP_FETCH_BACKOFF_MAX_MS,
+ emailQueueRouting: config.CDP_EMAIL_QUEUE_ROUTING,
},
{ teamManager: deps.teamManager, siteUrl: config.SITE_URL },
hogInputsService,
diff --git a/nodejs/src/cdp/services/cyclotron-v2/types.ts b/nodejs/src/cdp/services/cyclotron-v2/types.ts
index 14e315d35eeb..1832febe45d7 100644
--- a/nodejs/src/cdp/services/cyclotron-v2/types.ts
+++ b/nodejs/src/cdp/services/cyclotron-v2/types.ts
@@ -37,6 +37,7 @@ export const CyclotronV2RescheduleOptionsSchema = z.object({
distinctId: z.string().nullish(),
personId: z.string().nullish(),
actionId: z.string().nullish(),
+ queueName: z.string().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 285bdb2b98cd..17c93412dd0c 100644
--- a/nodejs/src/cdp/services/cyclotron-v2/worker.ts
+++ b/nodejs/src/cdp/services/cyclotron-v2/worker.ts
@@ -211,6 +211,10 @@ export class CyclotronV2Worker {
params.push(options.actionId ?? null)
setClauses.push(`action_id = $${params.length}`)
}
+ if (options?.queueName !== undefined) {
+ params.push(options.queueName)
+ setClauses.push(`queue_name = $${params.length}`)
+ }
await pool.query(
`UPDATE cyclotron_jobs SET ${setClauses.join(', ')}
diff --git a/nodejs/src/cdp/services/hog-executor.service.test.ts b/nodejs/src/cdp/services/hog-executor.service.test.ts
index 8161228d31c5..ce4f354d9b2f 100644
--- a/nodejs/src/cdp/services/hog-executor.service.test.ts
+++ b/nodejs/src/cdp/services/hog-executor.service.test.ts
@@ -70,6 +70,7 @@ describe('Hog Executor', () => {
fetchRetries: hub.CDP_FETCH_RETRIES,
fetchBackoffBaseMs: hub.CDP_FETCH_BACKOFF_BASE_MS,
fetchBackoffMaxMs: hub.CDP_FETCH_BACKOFF_MAX_MS,
+ emailQueueRouting: hub.CDP_EMAIL_QUEUE_ROUTING,
},
{ teamManager: hub.teamManager, siteUrl: hub.SITE_URL },
hogInputsService,
@@ -1680,4 +1681,175 @@ describe('Hog Executor', () => {
expect(isConnectionLevelError(error)).toBe(expected)
})
})
+
+ describe('routeEmailToQueue', () => {
+ it('should route the invocation to the email queue', () => {
+ const hogFunction = createHogFunction({
+ name: 'Email function',
+ metadata: { message_category_type: 'marketing' },
+ })
+
+ 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)
+
+ expect(result.finished).toBe(false)
+ expect(result.invocation.queue).toBe('email')
+ expect(result.invocation.queueMetadata?.originQueue).toBe('hogflow')
+ expect(result.metrics).toContainEqual(
+ expect.objectContaining({
+ metric_name: 'email_queued',
+ metric_kind: 'email',
+ })
+ )
+ })
+
+ it('should preserve the same job ID (no new job created)', () => {
+ const hogFunction = createHogFunction({ name: 'Email function' })
+ const invocation: CyclotronJobInvocationHogFunction = {
+ ...createExampleInvocation(hogFunction),
+ 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)
+
+ expect(result.invocation.id).toBe(invocation.id)
+ })
+ })
+
+ describe('email queue routing config', () => {
+ const createEmailInvocation = (): CyclotronJobInvocationHogFunction => {
+ const hogFunction = createHogFunction({ name: 'Email function', team_id: 123 })
+ const invocation: CyclotronJobInvocationHogFunction = {
+ ...createExampleInvocation(hogFunction),
+ teamId: 123,
+ queueParameters: {
+ type: 'email',
+ to: { email: '[email protected]' },
+ from: { integrationId: 1 },
+ subject: 'Test',
+ text: 'Hello',
+ html: '<p>Hello</p>',
+ },
+ }
+ invocation.state.vmState = { stack: [] } as any
+ return invocation
+ }
+
+ const createExecutorWithRouting = (emailQueueRouting: string): HogExecutorService => {
+ const hogInputsService = new HogInputsService(
+ hub.integrationManager,
+ hub.ENCRYPTION_SALT_KEYS,
+ hub.SITE_URL
+ )
+ const emailService = new EmailService(
+ {
+ sesAccessKeyId: hub.SES_ACCESS_KEY_ID,
+ sesSecretAccessKey: hub.SES_SECRET_ACCESS_KEY,
+ sesRegion: hub.SES_REGION,
+ sesEndpoint: hub.SES_ENDPOINT,
+ },
+ hub.integrationManager,
+ hub.ENCRYPTION_SALT_KEYS,
+ hub.SITE_URL
+ )
+ const recipientTokensService = new RecipientTokensService(hub.ENCRYPTION_SALT_KEYS, hub.SITE_URL)
+ return new HogExecutorService(
+ {
+ hogCostTimingUpperMs: hub.CDP_WATCHER_HOG_COST_TIMING_UPPER_MS,
+ googleAdwordsDeveloperToken: hub.CDP_GOOGLE_ADWORDS_DEVELOPER_TOKEN,
+ fetchRetries: hub.CDP_FETCH_RETRIES,
+ fetchBackoffBaseMs: hub.CDP_FETCH_BACKOFF_BASE_MS,
+ fetchBackoffMaxMs: hub.CDP_FETCH_BACKOFF_MAX_MS,
+ emailQueueRouting,
+ },
+ { teamManager: hub.teamManager, siteUrl: hub.SITE_URL },
+ hogInputsService,
+ emailService,
+ recipientTokensService
+ )
+ }
+
+ it('should send inline when routing is empty', async () => {
+ const exec = createExecutorWithRouting('')
+ const invocation = createEmailInvocation()
+
+ const result = await exec.executeWithAsyncFunctions(invocation)
+
+ expect(result.invocation.queue).not.toBe('email')
+ expect(result.finished).toBe(true)
+ })
+
+ it('should route to email queue when team matches', async () => {
+ const exec = createExecutorWithRouting('123')
+ const invocation = createEmailInvocation()
+
+ const result = await exec.executeWithAsyncFunctions(invocation)
+
+ expect(result.invocation.queue).toBe('email')
+ expect(result.finished).toBe(false)
+ })
+
+ it('should send inline when team does not match', async () => {
+ const exec = createExecutorWithRouting('456')
+ const invocation = createEmailInvocation()
+
+ const result = await exec.executeWithAsyncFunctions(invocation)
+
+ expect(result.invocation.queue).not.toBe('email')
+ expect(result.finished).toBe(true)
+ })
+
+ it('should route based on percentage when under threshold', async () => {
+ const exec = createExecutorWithRouting('*:0.5')
+ const invocation = createEmailInvocation()
+
+ jest.spyOn(Math, 'random').mockReturnValue(0.3)
+ const result = await exec.executeWithAsyncFunctions(invocation)
+
+ expect(result.invocation.queue).toBe('email')
+ expect(result.finished).toBe(false)
+ })
+
+ it('should send inline when percentage roll is above threshold', async () => {
+ const exec = createExecutorWithRouting('*:0.5')
+ const invocation = createEmailInvocation()
+
+ jest.spyOn(Math, 'random').mockReturnValue(0.7)
+ const result = await exec.executeWithAsyncFunctions(invocation)
+
+ expect(result.invocation.queue).not.toBe('email')
+ })
+
+ it('should route all teams when config is *', async () => {
+ const exec = createExecutorWithRouting('*')
+ const invocation = createEmailInvocation()
+
+ const result = await exec.executeWithAsyncFunctions(invocation)
+
+ expect(result.invocation.queue).toBe('email')
+ expect(result.invocation.queueMetadata?.originQueue).toBeDefined()
+ expect(result.finished).toBe(false)
+ })
+ })
})
diff --git a/nodejs/src/cdp/services/hog-executor.service.ts b/nodejs/src/cdp/services/hog-executor.service.ts
index d4543bf83233..cdc8c41093d5 100644
--- a/nodejs/src/cdp/services/hog-executor.service.ts
+++ b/nodejs/src/cdp/services/hog-executor.service.ts
@@ -8,7 +8,8 @@ import { ACCESS_TOKEN_PLACEHOLDER } from '~/config/constants'
import { FetchOptions, FetchResponse, InvalidRequestError, SecureRequestError, fetch } from '~/utils/request'
import { tryCatch } from '~/utils/try-catch'
-import { PluginsServerConfig } from '../../types'
+import { buildIntegerMatcherWithPercentage } from '../../config/config'
+import { PluginsServerConfig, ValueMatcher } from '../../types'
import { parseJSON } from '../../utils/json-parse'
import { logger } from '../../utils/logger'
import { TeamManager } from '../../utils/team-manager'
@@ -47,6 +48,7 @@ export interface HogExecutorConfig {
fetchRetries: number
fetchBackoffBaseMs: number
fetchBackoffMaxMs: number
+ emailQueueRouting: string
}
export interface HogExecutorAsyncContext {
@@ -54,6 +56,11 @@ export interface HogExecutorAsyncContext {
siteUrl: string
}
+const cdpEmailQueuedTotal = new Counter({
+ name: 'cdp_email_queued_total',
+ help: 'Total emails routed to the dedicated email queue',
+})
+
const cdpHttpRequests = new Counter({
name: 'cdp_http_requests',
help: 'HTTP requests and their outcomes',
@@ -180,13 +187,17 @@ export type HogExecutorExecuteAsyncOptions = HogExecutorExecuteOptions & {
}
export class HogExecutorService {
+ private emailQueueMatcher: ValueMatcher<number>
+
constructor(
private config: HogExecutorConfig,
private asyncContext: HogExecutorAsyncContext,
private hogInputsService: HogInputsService,
private emailService: EmailService,
private recipientTokensService: RecipientTokensService
- ) {}
+ ) {
+ this.emailQueueMatcher = buildIntegerMatcherWithPercentage(config.emailQueueRouting)
+ }
async buildInputsWithGlobals(
hogFunction: HogFunctionType,
@@ -339,10 +350,33 @@ export class HogExecutorService {
break
}
+ // Queue-aware routing: each worker can execute some actions inline
+ // and routes others to a specialized queue. The email worker sends
+ // emails inline but routes fetches back to hogflow. The hogflow
+ // worker does fetches inline but routes emails to the email queue
+ // (when the team is configured for it via CDP_EMAIL_QUEUE_ROUTING).
+ //
+ // Future: once we add an execution time budget, the email worker
+ // will also handle fetches inline. The only reason to reschedule
+ // back to hogflow will be when overall execution time exceeds the
+ // budget, to avoid blocking the queue.
if (queueParamsType === 'fetch') {
- result = await this.executeFetch(nextInvocation, options)
+ if (invocation.queue === 'email') {
+ result = this.routeToQueue(
+ nextInvocation,
+ nextInvocation.queueMetadata?.originQueue ?? 'hogflow'
+ )
+ } else {
+ result = await this.executeFetch(nextInvocation, options)
+ }
} else if (queueParamsType === 'email') {
- result = await this.emailService.executeSendEmail(nextInvocation)
+ // Route to the email queue only if we're not already there
+ // and the team is configured for it. Otherwise send inline.
+ if (invocation.queue !== 'email' && this.emailQueueMatcher(nextInvocation.teamId)) {
+ result = this.routeEmailToQueue(nextInvocation)
+ } else {
+ result = await this.emailService.executeSendEmail(nextInvocation)
+ }
} else {
throw new Error(`Unknown queue type: ${queueParamsType}`)
}
@@ -356,8 +390,8 @@ export class HogExecutorService {
logs.push(...result.logs)
metrics.push(...result.metrics)
- // If we have finished _or_ something has been scheduled to run later _or_ we have reached the max async functions then we break the loop
- if (result.finished || result.invocation.queueScheduledAt) {
+ // If we have finished _or_ something has been scheduled to run later _or_ the job was routed to a different queue then we break the loop
+ if (result.finished || result.invocation.queueScheduledAt || result.invocation.queue !== invocation.queue) {
break
}
}
@@ -376,6 +410,56 @@ export class HogExecutorService {
return result
}
+ /**
+ * Routes an email send to the dedicated email queue instead of sending inline.
+ * The email worker will pick this up, send via SES, and return the job to the
+ * original queue so the workflow can continue.
+ */
+ private routeEmailToQueue(
+ invocation: CyclotronJobInvocationHogFunction
+ ): CyclotronJobInvocationResult<CyclotronJobInvocationHogFunction> {
+ const result = createInvocationResult<CyclotronJobInvocationHogFunction>(
+ invocation,
+ {
+ queue: 'email',
+ queueParameters: invocation.queueParameters,
+ queueMetadata: {
+ ...invocation.queueMetadata,
+ originQueue: invocation.queue,
+ },
+ },
+ { finished: false }
+ )
+
+ result.metrics.push({
+ team_id: invocation.teamId,
+ app_source_id: invocation.parentRunId ?? invocation.functionId,
+ instance_id: invocation.state.actionId || invocation.id,
+ metric_kind: 'email',
+ metric_name: 'email_queued',
+ count: 1,
+ })
+
+ cdpEmailQueuedTotal.inc()
+
+ return result
+ }
+
+ private routeToQueue(
+ invocation: CyclotronJobInvocationHogFunction,
+ targetQueue: string
+ ): CyclotronJobInvocationResult<CyclotronJobInvocationHogFunction> {
+ return createInvocationResult<CyclotronJobInvocationHogFunction>(
+ invocation,
+ {
+ queue: targetQueue as CyclotronJobInvocationHogFunction['queue'],
+ queueParameters: invocation.queueParameters,
+ queueMetadata: undefined,
+ },
+ { finished: false }
+ )
+ }
+
@instrumented({ key: 'hog-executor.execute', sendException: false })
async execute(
invocation: CyclotronJobInvocationHogFunction,
@@ -719,7 +803,6 @@ export class HogExecutorService {
const maxRetries = options?.maxFetchRetries ?? this.config.fetchRetries
if (canRetry && result.invocation.state.attempts < maxRetries) {
await fetchResponse?.dump()
- result.invocation.queue = 'hog'
result.invocation.queueParameters = params
result.invocation.queuePriority = invocation.queuePriority + 1
result.invocation.queueScheduledAt = DateTime.utc().plus({ milliseconds: backoffMs })
diff --git a/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts b/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts
index 729498d9f09f..4f8d2e34b468 100644
--- a/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts
+++ b/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts
@@ -60,6 +60,7 @@ describe('HogFunctionHandler', () => {
fetchRetries: hub.CDP_FETCH_RETRIES,
fetchBackoffBaseMs: hub.CDP_FETCH_BACKOFF_BASE_MS,
fetchBackoffMaxMs: hub.CDP_FETCH_BACKOFF_MAX_MS,
+ emailQueueRouting: hub.CDP_EMAIL_QUEUE_ROUTING,
},
{ teamManager: hub.teamManager, siteUrl: hub.SITE_URL },
hogInputsService,
diff --git a/nodejs/src/cdp/services/hogflows/actions/hog_function.ts b/nodejs/src/cdp/services/hogflows/actions/hog_function.ts
index a0d5eeb6134e..fb727fb4e368 100644
--- a/nodejs/src/cdp/services/hogflows/actions/hog_function.ts
+++ b/nodejs/src/cdp/services/hogflows/actions/hog_function.ts
@@ -54,8 +54,10 @@ export class HogFunctionHandler implements ActionHandler {
if (!functionResult.finished) {
// Set the state of the function result on the substate of the flow for the next execution
result.invocation.state.currentAction!.hogFunctionState = functionResult.invocation.state
- // Also the queueParameters are required
+ // Preserve queue routing and parameters from the function result
+ result.invocation.queue = functionResult.invocation.queue
result.invocation.queueParameters = functionResult.invocation.queueParameters
+ result.invocation.queueMetadata = functionResult.invocation.queueMetadata
return {
scheduledAt: functionResult.invocation.queueScheduledAt ?? DateTime.now(),
}
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 7765110f31c0..30ba18420f48 100644
--- a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts
+++ b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts
@@ -80,6 +80,7 @@ describe('Hogflow Executor', () => {
fetchRetries: hub.CDP_FETCH_RETRIES,
fetchBackoffBaseMs: hub.CDP_FETCH_BACKOFF_BASE_MS,
fetchBackoffMaxMs: hub.CDP_FETCH_BACKOFF_MAX_MS,
+ emailQueueRouting: hub.CDP_EMAIL_QUEUE_ROUTING,
},
{ teamManager: hub.teamManager, siteUrl: hub.SITE_URL },
hogInputsService,
@@ -1808,4 +1809,378 @@ describe('Hogflow Executor', () => {
expect(emailBilling).toHaveLength(2)
})
})
+
+ describe('email queue routing', () => {
+ it('should route email actions to the email queue when routing is configured', async () => {
+ const team = await getFirstTeam(hub.postgres)
+
+ await insertIntegration(hub.postgres, team.id, {
+ id: 1,
+ kind: 'email',
+ config: {
+ email: '[email protected]',
+ name: 'Test User',
+ domain: 'posthog.com',
+ verified: true,
+ provider: 'maildev',
+ },
+ })
+
+ await insertHogFunctionTemplate(hub.postgres, {
+ id: 'template-email-routing-test',
+ name: 'Email Routing Test',
+ code: `sendEmail(inputs.email)`,
+ inputs_schema: [
+ {
+ type: 'native_email',
+ key: 'email',
+ label: 'Email message',
+ integration: 'email',
+ required: true,
+ default: {
+ to: { email: '', name: '' },
+ from: { email: '', name: '' },
+ subject: '',
+ text: 'Hello!',
+ html: '<div>Hello!</div>',
+ },
+ secret: false,
+ description: '',
+ templating: 'liquid',
+ },
+ ],
+ })
+
+ // Create executor with email queue routing enabled for all teams
+ const routingExecutor = new HogFlowExecutorService(
+ new HogFlowFunctionsService(
+ hub.SITE_URL,
+ new HogFunctionTemplateManagerService(hub.postgres),
+ new HogExecutorService(
+ {
+ hogCostTimingUpperMs: hub.CDP_WATCHER_HOG_COST_TIMING_UPPER_MS,
+ googleAdwordsDeveloperToken: hub.CDP_GOOGLE_ADWORDS_DEVELOPER_TOKEN,
+ fetchRetries: hub.CDP_FETCH_RETRIES,
+ fetchBackoffBaseMs: hub.CDP_FETCH_BACKOFF_BASE_MS,
+ fetchBackoffMaxMs: hub.CDP_FETCH_BACKOFF_MAX_MS,
+ emailQueueRouting: '*',
+ },
+ { teamManager: hub.teamManager, siteUrl: hub.SITE_URL },
+ new HogInputsService(hub.integrationManager, hub.ENCRYPTION_SALT_KEYS, hub.SITE_URL),
+ new EmailService(
+ {
+ sesAccessKeyId: hub.SES_ACCESS_KEY_ID,
+ sesSecretAccessKey: hub.SES_SECRET_ACCESS_KEY,
+ sesRegion: hub.SES_REGION,
+ sesEndpoint: hub.SES_ENDPOINT,
+ },
+ hub.integrationManager,
+ hub.ENCRYPTION_SALT_KEYS,
+ hub.SITE_URL
+ ),
+ new RecipientTokensService(hub.ENCRYPTION_SALT_KEYS, hub.SITE_URL)
+ )
+ ),
+ new RecipientPreferencesService(new RecipientsManagerService(hub.postgres))
+ )
+
+ const hogFlow = new FixtureHogFlowBuilder()
+ .withTeamId(team.id)
+ .withExitCondition('exit_only_at_end')
+ .withWorkflow({
+ actions: {
+ trigger: {
+ type: 'trigger',
+ config: {
+ type: 'event',
+ filters: HOG_FILTERS_EXAMPLES.no_filters.filters ?? {},
+ },
+ },
+ email_1: {
+ type: 'function_email',
+ config: {
+ template_id: 'template-email-routing-test',
+ inputs: {
+ email: {
+ value: {
+ to: { email: '[email protected]', name: 'Recipient' },
+ from: { integrationId: 1, email: '[email protected]' },
+ subject: 'Test Email',
+ text: 'Test',
+ html: '<p>Test</p>',
+ },
+ },
+ },
+ },
+ },
+ },
+ edges: [
+ { from: 'trigger', to: 'email_1', type: 'continue' },
+ { from: 'email_1', to: 'exit', type: 'continue' },
+ ],
+ })
+ .build()
+
+ const invocation = createExampleHogFlowInvocation(hogFlow, {
+ event: {
+ ...createHogExecutionGlobals().event,
+ event: '$pageview',
+ },
+ })
+
+ const result = await routingExecutor.execute(invocation)
+
+ // Should be routed to email queue, not finished
+ expect(result.finished).toBe(false)
+ expect(result.invocation.queue).toBe('email')
+ expect(result.invocation.queueMetadata?.originQueue).toBeDefined()
+ expect(result.invocation.queueParameters).toBeDefined()
+ expect(result.invocation.queueParameters?.type).toBe('email')
+ })
+
+ it('should send email inline when routing is not configured', async () => {
+ const team = await getFirstTeam(hub.postgres)
+
+ await insertIntegration(hub.postgres, team.id, {
+ id: 1,
+ kind: 'email',
+ config: {
+ email: '[email protected]',
+ name: 'Test User',
+ domain: 'posthog.com',
+ verified: true,
+ provider: 'maildev',
+ },
+ })
+
+ const hogFlow = new FixtureHogFlowBuilder()
+ .withTeamId(team.id)
+ .withExitCondition('exit_only_at_end')
+ .withWorkflow({
+ actions: {
+ trigger: {
+ type: 'trigger',
+ config: {
+ type: 'event',
+ filters: HOG_FILTERS_EXAMPLES.no_filters.filters ?? {},
+ },
+ },
+ email_1: {
+ type: 'function_email',
+ config: {
+ template_id: 'template-email-routing-test',
+ inputs: {
+ email: {
+ value: {
+ to: { email: '[email protected]', name: 'Recipient' },
+ from: { integrationId: 1, email: '[email protected]' },
+ subject: 'Test Email',
+ text: 'Test',
+ html: '<p>Test</p>',
+ },
+ },
+ },
+ },
+ },
+ },
+ edges: [
+ { from: 'trigger', to: 'email_1', type: 'continue' },
+ { from: 'email_1', to: 'exit', type: 'continue' },
+ ],
+ })
+ .build()
+
+ const invocation = createExampleHogFlowInvocation(hogFlow, {
+ event: {
+ ...createHogExecutionGlobals().event,
+ event: '$pageview',
+ },
+ })
+
+ // Default executor has emailQueueRouting = '' (inline)
+ let result = await executor.execute(invocation)
+ while (!result.finished) {
+ result = await executor.execute(result.invocation)
+ }
+
+ // Should send inline and complete
+ expect(result.finished).toBe(true)
+ expect(result.invocation.queue).not.toBe('email')
+ })
+
+ it('should complete the full round-trip: hogflow → email queue → email sent → workflow continues', async () => {
+ const team = await getFirstTeam(hub.postgres)
+
+ await insertIntegration(hub.postgres, team.id, {
+ id: 1,
+ kind: 'email',
+ config: {
+ email: '[email protected]',
+ name: 'Test User',
+ domain: 'posthog.com',
+ verified: true,
+ provider: 'maildev',
+ },
+ })
+
+ await insertHogFunctionTemplate(hub.postgres, {
+ id: 'template-email-routing-test',
+ name: 'Email Routing Test',
+ code: `sendEmail(inputs.email)`,
+ inputs_schema: [
+ {
+ type: 'native_email',
+ key: 'email',
+ label: 'Email message',
+ integration: 'email',
+ required: true,
+ default: {
+ to: { email: '', name: '' },
+ from: { email: '', name: '' },
+ subject: '',
+ text: 'Hello!',
+ html: '<div>Hello!</div>',
+ },
+ secret: false,
+ description: '',
+ templating: 'liquid',
+ },
+ ],
+ })
+
+ // Executor with routing enabled (simulates hogflow worker)
+ const hogflowExecutor = new HogFlowExecutorService(
+ new HogFlowFunctionsService(
+ hub.SITE_URL,
+ new HogFunctionTemplateManagerService(hub.postgres),
+ new HogExecutorService(
+ {
+ hogCostTimingUpperMs: hub.CDP_WATCHER_HOG_COST_TIMING_UPPER_MS,
+ googleAdwordsDeveloperToken: hub.CDP_GOOGLE_ADWORDS_DEVELOPER_TOKEN,
+ fetchRetries: hub.CDP_FETCH_RETRIES,
+ fetchBackoffBaseMs: hub.CDP_FETCH_BACKOFF_BASE_MS,
+ fetchBackoffMaxMs: hub.CDP_FETCH_BACKOFF_MAX_MS,
+ emailQueueRouting: '*',
+ },
+ { teamManager: hub.teamManager, siteUrl: hub.SITE_URL },
+ new HogInputsService(hub.integrationManager, hub.ENCRYPTION_SALT_KEYS, hub.SITE_URL),
+ new EmailService(
+ {
+ sesAccessKeyId: hub.SES_ACCESS_KEY_ID,
+ sesSecretAccessKey: hub.SES_SECRET_ACCESS_KEY,
+ sesRegion: hub.SES_REGION,
+ sesEndpoint: hub.SES_ENDPOINT,
+ },
+ hub.integrationManager,
+ hub.ENCRYPTION_SALT_KEYS,
+ hub.SITE_URL
+ ),
+ new RecipientTokensService(hub.ENCRYPTION_SALT_KEYS, hub.SITE_URL)
+ )
+ ),
+ new RecipientPreferencesService(new RecipientsManagerService(hub.postgres))
+ )
+
+ // Executor with no routing (simulates email worker — emails are inline)
+ const emailExecutor = new HogFlowExecutorService(
+ new HogFlowFunctionsService(
+ hub.SITE_URL,
+ new HogFunctionTemplateManagerService(hub.postgres),
+ new HogExecutorService(
+ {
+ hogCostTimingUpperMs: hub.CDP_WATCHER_HOG_COST_TIMING_UPPER_MS,
+ googleAdwordsDeveloperToken: hub.CDP_GOOGLE_ADWORDS_DEVELOPER_TOKEN,
+ fetchRetries: hub.CDP_FETCH_RETRIES,
+ fetchBackoffBaseMs: hub.CDP_FETCH_BACKOFF_BASE_MS,
+ fetchBackoffMaxMs: hub.CDP_FETCH_BACKOFF_MAX_MS,
+ emailQueueRouting: '',
+ },
+ { teamManager: hub.teamManager, siteUrl: hub.SITE_URL },
+ new HogInputsService(hub.integrationManager, hub.ENCRYPTION_SALT_KEYS, hub.SITE_URL),
+ new EmailService(
+ {
+ sesAccessKeyId: hub.SES_ACCESS_KEY_ID,
+ sesSecretAccessKey: hub.SES_SECRET_ACCESS_KEY,
+ sesRegion: hub.SES_REGION,
+ sesEndpoint: hub.SES_ENDPOINT,
+ },
+ hub.integrationManager,
+ hub.ENCRYPTION_SALT_KEYS,
+ hub.SITE_URL
+ ),
+ new RecipientTokensService(hub.ENCRYPTION_SALT_KEYS, hub.SITE_URL)
+ )
+ ),
+ new RecipientPreferencesService(new RecipientsManagerService(hub.postgres))
+ )
+
+ const hogFlow = new FixtureHogFlowBuilder()
+ .withTeamId(team.id)
+ .withExitCondition('exit_only_at_end')
+ .withWorkflow({
+ actions: {
+ trigger: {
+ type: 'trigger',
+ config: {
+ type: 'event',
+ filters: HOG_FILTERS_EXAMPLES.no_filters.filters ?? {},
+ },
+ },
+ email_1: {
+ type: 'function_email',
+ config: {
+ template_id: 'template-email-routing-test',
+ inputs: {
+ email: {
+ value: {
+ to: { email: '[email protected]', name: 'Recipient' },
+ from: { integrationId: 1, email: '[email protected]' },
+ subject: 'Test Email',
+ text: 'Test text',
+ html: '<p>Test html</p>',
+ },
+ },
+ },
+ },
+ },
+ exit: {
+ type: 'exit',
+ config: {},
+ },
+ },
+ edges: [
+ { from: 'trigger', to: 'email_1', type: 'continue' },
+ { from: 'email_1', to: 'exit', type: 'continue' },
+ ],
+ })
+ .build()
+
+ const invocation = createExampleHogFlowInvocation(hogFlow, {
+ event: {
+ ...createHogExecutionGlobals().event,
+ event: '$pageview',
+ },
+ })
+
+ // Step 1: Hogflow worker executes — should route to email queue
+ const hogflowResult = await hogflowExecutor.execute(invocation)
+ expect(hogflowResult.finished).toBe(false)
+ expect(hogflowResult.invocation.queue).toBe('email')
+ expect(hogflowResult.invocation.queueParameters?.type).toBe('email')
+
+ // Step 2: Email worker picks up the job — should send the email and continue
+ let emailResult = await emailExecutor.execute(hogflowResult.invocation)
+ while (!emailResult.finished) {
+ emailResult = await emailExecutor.execute(emailResult.invocation)
+ }
+
+ // Workflow should complete
+ expect(emailResult.finished).toBe(true)
+ expect(emailResult.error).toBeUndefined()
+
+ // Verify email_sent metric was emitted
+ const emailSentMetrics = emailResult.metrics.filter((m) => m.metric_name === 'email_sent')
+ expect(emailSentMetrics).toHaveLength(1)
+ })
+ })
})
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 6d0b99bc5111..ce8913a651af 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
@@ -206,6 +206,7 @@ export class CyclotronJobQueuePostgresV2 implements JobQueue {
distinctId: extractDistinctId(result.invocation),
personId: extractPersonId(result.invocation),
actionId: extractActionId(result.invocation),
+ queueName: result.invocation.queue,
})
}
})
diff --git a/nodejs/src/cdp/services/messaging/email.service.ts b/nodejs/src/cdp/services/messaging/email.service.ts
index 69757a0efd79..1b7e279eb77c 100644
--- a/nodejs/src/cdp/services/messaging/email.service.ts
+++ b/nodejs/src/cdp/services/messaging/email.service.ts
@@ -112,8 +112,8 @@ export class EmailService {
result.finished = true
}
- // Finally we create the response object as the VM expects
- result.invocation.state.vmState!.stack.push({
+ // Push the response to the VM stack if running inline (not from the email queue)
+ result.invocation.state.vmState?.stack.push({
success,
})
@@ -222,7 +222,7 @@ export class EmailService {
FeedbackForwardingEmailAddress: from.email,
}
- const isTransactionalEmail = result.invocation.hogFunction.metadata?.message_category_type === 'transactional'
+ const isTransactionalEmail = result.invocation.hogFunction?.metadata?.message_category_type === 'transactional'
// Automatically add unsubscribe headers for non-transactional emails
if (sendEmailParams.Content?.Simple && !isTransactionalEmail) {
sendEmailParams.Content.Simple.Headers = this.generateUnsubscribeHeaders({
diff --git a/nodejs/src/cdp/templates/test/test-helpers.ts b/nodejs/src/cdp/templates/test/test-helpers.ts
index 4d3697f88a82..c29cbbcf9bba 100644
--- a/nodejs/src/cdp/templates/test/test-helpers.ts
+++ b/nodejs/src/cdp/templates/test/test-helpers.ts
@@ -208,6 +208,7 @@ export class TemplateTester {
fetchRetries: config.CDP_FETCH_RETRIES,
fetchBackoffBaseMs: config.CDP_FETCH_BACKOFF_BASE_MS,
fetchBackoffMaxMs: config.CDP_FETCH_BACKOFF_MAX_MS,
+ emailQueueRouting: config.CDP_EMAIL_QUEUE_ROUTING,
},
{ teamManager: undefined as any, siteUrl: config.SITE_URL },
hogInputsService,
diff --git a/nodejs/src/cdp/types.ts b/nodejs/src/cdp/types.ts
index ff609381bae2..cf383b3a1944 100644
--- a/nodejs/src/cdp/types.ts
+++ b/nodejs/src/cdp/types.ts
@@ -229,6 +229,7 @@ export type MinimalAppMetric = {
| 'fetch'
| 'billable_invocation'
| 'dropped'
+ | 'email_queued'
| 'email_sent'
| 'email_delivered'
| 'email_failed'
@@ -253,7 +254,7 @@ export interface HogFunctionTiming {
}
// IMPORTANT: All queue names should be lowercase and only [A-Z0-9] characters are allowed.
-export const CYCLOTRON_INVOCATION_JOB_QUEUES = ['hog', 'hogoverflow', 'hogflow'] as const
+export const CYCLOTRON_INVOCATION_JOB_QUEUES = ['hog', 'hogoverflow', 'hogflow', 'email'] as const
export type CyclotronJobQueueKind = (typeof CYCLOTRON_INVOCATION_JOB_QUEUES)[number]
export const CYCLOTRON_JOB_QUEUE_SOURCES = ['postgres', 'postgres-v2', 'kafka'] as const
diff --git a/nodejs/src/cdp/workflows-e2e.test.ts b/nodejs/src/cdp/workflows-e2e.test.ts
index 401c4bdf336e..5a3a7a86fcd7 100644
--- a/nodejs/src/cdp/workflows-e2e.test.ts
+++ b/nodejs/src/cdp/workflows-e2e.test.ts
@@ -36,8 +36,9 @@ import {
} from '../../src/worker/ingestion/persons/repositories/person-repository'
import { FixtureHogFlowBuilder } from './_tests/builders/hogflow.builder'
import { HOG_FILTERS_EXAMPLES } from './_tests/examples'
-import { createHogExecutionGlobals, insertHogFunctionTemplate } from './_tests/fixtures'
+import { createHogExecutionGlobals, insertHogFunctionTemplate, insertIntegration } from './_tests/fixtures'
import { insertHogFlow } from './_tests/fixtures-hogflows'
+import { CdpCyclotronWorkerEmail } from './consumers/cdp-cyclotron-worker-email.consumer'
import { CdpCyclotronWorkerHogFlow } from './consumers/cdp-cyclotron-worker-hogflow.consumer'
import { CdpEventsConsumer } from './consumers/cdp-events.consumer'
import { CdpHogflowSubscriptionMatcherConsumer } from './consumers/cdp-hogflow-subscription-matcher.consumer'
@@ -1027,3 +1028,332 @@ describe.each(['postgres-v2' as const, 'postgres' as const])('Workflows E2E (%s)
})
})
})
+
+// Email queue routing is postgres-v2 only — the email worker reschedules jobs
+// between queue names on the same v2 backend. We keep this block outside the
+// `describe.each` so the legacy postgres mode doesn't also try to exercise it.
+describe('Workflows E2E (email queue)', () => {
+ jest.setTimeout(30000)
+
+ let eventsConsumer: CdpEventsConsumer
+ let hogflowWorker: CdpCyclotronWorkerHogFlow
+ let emailWorker: CdpCyclotronWorkerEmail
+
+ let hub: Hub
+ let kafkaProducer: KafkaProducerWrapper
+ let mockProducerObserver: KafkaProducerObserver
+ let team: Team
+ let cyclotronPool: Pool
+
+ beforeAll(() => {
+ cyclotronPool = new Pool({ connectionString: CYCLOTRON_NODE_DB_URL })
+ })
+
+ afterAll(async () => {
+ await cyclotronPool.end()
+ })
+
+ beforeEach(async () => {
+ MockKafkaProducerWrapper.create = jest.fn((...args) => {
+ return ActualKafkaProducerWrapper.create(...args)
+ })
+
+ await resetKafka()
+ await resetTestDatabase()
+ await cyclotronPool.query('DELETE FROM cyclotron_jobs')
+
+ hub = await createHub()
+ // Route all teams' emails through the dedicated queue
+ hub.CDP_EMAIL_QUEUE_ROUTING = '*'
+ hub.CDP_CYCLOTRON_BATCH_DELAY_MS = 50
+
+ kafkaProducer = await ActualKafkaProducerWrapper.create(hub.KAFKA_CLIENT_RACK)
+ mockProducerObserver = new KafkaProducerObserver(kafkaProducer)
+
+ team = await getFirstTeam(hub.postgres)
+ mockProducerObserver.resetKafkaProducer()
+
+ // Email integration — provider 'maildev' routes to local SMTP (port 1025)
+ await insertIntegration(hub.postgres, team.id, {
+ id: 1,
+ kind: 'email',
+ config: {
+ email: '[email protected]',
+ name: 'Test Sender',
+ domain: 'posthog.com',
+ verified: true,
+ provider: 'maildev',
+ },
+ })
+
+ // Native-email template that the workflow's email action invokes
+ await insertHogFunctionTemplate(hub.postgres, {
+ id: 'template-workflows-e2e-email',
+ name: 'Workflows E2E Email',
+ code: `sendEmail(inputs.email)`,
+ inputs_schema: [
+ {
+ type: 'native_email',
+ key: 'email',
+ label: 'Email message',
+ integration: 'email',
+ required: true,
+ default: {
+ to: { email: '', name: '' },
+ from: { email: '', name: '' },
+ subject: '',
+ text: 'Hello!',
+ html: '<div>Hello!</div>',
+ },
+ secret: false,
+ description: '',
+ templating: 'liquid',
+ },
+ ],
+ })
+
+ const deps = createCdpConsumerDeps(hub, kafkaProducer)
+ const kafkaQueue = new CyclotronJobQueueKafka(hub.KAFKA_CLIENT_RACK, hub, hub.CONSUMER_BATCH_SIZE)
+ // Each consumer gets a dedicated CyclotronJobQueuePostgresV2 — sharing one
+ // across two consumers collides on `this.worker` and the shared pg pool.
+ // Mirrors the prod deployment model where each capability runs in its own pod.
+ const eventsProducerQueue = new CyclotronJobQueuePostgresV2(hub.CONSUMER_BATCH_SIZE, hub)
+ const hogflowConsumerQueue = new CyclotronJobQueuePostgresV2(hub.CONSUMER_BATCH_SIZE, hub)
+ const emailConsumerQueue = new CyclotronJobQueuePostgresV2(hub.CONSUMER_BATCH_SIZE, hub)
+
+ eventsConsumer = new CdpEventsConsumer(hub, deps, {
+ hogQueue: kafkaQueue,
+ hogflowQueue: eventsProducerQueue,
+ })
+ await Promise.all([kafkaQueue.startAsProducer(), eventsProducerQueue.startAsProducer()])
+
+ // Hogflow worker polls jobs with queue_name='hogflow' and re-stamps email
+ // jobs to queue_name='email' so the email worker picks them up
+ hogflowWorker = new CdpCyclotronWorkerHogFlow(hub, deps, hogflowConsumerQueue)
+ await hogflowWorker.start()
+
+ // Email worker polls jobs with queue_name='email', sends via EmailService,
+ // and continues the workflow inline (until it hits a fetch or terminates)
+ emailWorker = new CdpCyclotronWorkerEmail(hub, deps, emailConsumerQueue)
+ await emailWorker.start()
+ })
+
+ afterEach(async () => {
+ await Promise.all([
+ eventsConsumer?.stop() ?? Promise.resolve(),
+ hogflowWorker?.stop() ?? Promise.resolve(),
+ emailWorker?.stop() ?? Promise.resolve(),
+ ])
+ await kafkaProducer.disconnect()
+ await closeHub(hub)
+ mockProducerObserver.resetKafkaProducer()
+ })
+
+ async function queryCyclotronJobs(): Promise<any[]> {
+ const result = await cyclotronPool.query(`SELECT *, status AS status FROM cyclotron_jobs ORDER BY created ASC`)
+ return result.rows
+ }
+
+ function createGlobals(): HogFunctionInvocationGlobals {
+ return createHogExecutionGlobals({
+ project: { id: team.id } as any,
+ event: {
+ uuid: 'b3a1fe86-b10c-43cc-acaf-d208977608d0',
+ event: '$pageview',
+ properties: {
+ $current_url: 'https://posthog.com',
+ $lib_version: '1.0.0',
+ },
+ timestamp: '2024-09-03T09:00:00Z',
+ } as any,
+ })
+ }
+
+ it('routes the email through the dedicated queue and continues the workflow', async () => {
+ const hogFlow = new FixtureHogFlowBuilder()
+ .withTeamId(team.id)
+ .withStatus('active')
+ .withExitCondition('exit_only_at_end')
+ .withWorkflow({
+ actions: {
+ trigger: {
+ type: 'trigger',
+ config: { type: 'event', filters: HOG_FILTERS_EXAMPLES.no_filters.filters ?? {} },
+ },
+ email_1: {
+ type: 'function_email',
+ config: {
+ template_id: 'template-workflows-e2e-email',
+ inputs: {
+ email: {
+ value: {
+ to: { email: '[email protected]', name: 'Recipient' },
+ from: { integrationId: 1, email: '[email protected]' },
+ subject: 'Test Email',
+ text: 'Test text',
+ html: '<p>Test html</p>',
+ },
+ },
+ },
+ },
+ },
+ exit: { type: 'exit', config: {} },
+ },
+ edges: [
+ { from: 'trigger', to: 'email_1', type: 'continue' },
+ { from: 'email_1', to: 'exit', type: 'continue' },
+ ],
+ })
+ .build()
+ await insertHogFlow(hub.postgres, hogFlow)
+
+ // Trigger the workflow via the events consumer (real Kafka producer + v2 queue)
+ const { backgroundTask } = await eventsConsumer.processBatch([createGlobals()])
+ await backgroundTask
+
+ // Verify both metric stages fire EXACTLY ONCE — regression guard against
+ // a double-counting bug where each metric (incl. unrelated ones like the
+ // exit_node 'succeeded') was being pushed twice per invocation. The
+ // AppMetricsAggregator dedupes by key in-memory, so we sum `count` across
+ // all messages rather than counting messages: one push at count=1 looks
+ // identical to two pushes at count=1 unless we sum.
+ await waitForExpect(() => {
+ const sumCounts = (filter: (m: any) => boolean) =>
+ mockProducerObserver
+ .getProducedKafkaMessagesForTopic(KAFKA_APP_METRICS_2)
+ .filter(filter)
+ .reduce((sum: number, m: any) => sum + m.value.count, 0)
+
+ expect(sumCounts((m) => m.value.metric_name === 'email_queued')).toBe(1)
+ expect(sumCounts((m) => m.value.metric_name === 'email_sent')).toBe(1)
+ // The exit action's 'succeeded' metric has nothing to do with the email
+ // pipeline — including it locks down that the doubling isn't email-specific.
+ // (The instance_id matches the action key from FixtureHogFlowBuilder.)
+ expect(sumCounts((m) => m.value.metric_name === 'succeeded' && m.value.instance_id === 'exit')).toBe(1)
+ }, 15000)
+
+ // Workflow should reach a terminal state once the email worker has continued through exit
+ await waitForExpect(async () => {
+ const jobs = await queryCyclotronJobs()
+ const terminal = jobs.filter(
+ (j: any) => j.status === 'completed' || j.status === 'failed' || j.status === 'canceled'
+ )
+ expect(terminal.length).toBeGreaterThanOrEqual(1)
+ }, 10000)
+ })
+
+ it('re-routes between hogflow and email queues across email → fetch → email', async () => {
+ // Exercises the full ping-pong:
+ // hogflow worker → email queue (email_1) → email worker sends → routes back to hogflow
+ // → hogflow worker does fetch → email queue (email_2) → email worker sends → exits
+ // Proves queueMetadata.originQueue is honored on the return trip from the email worker.
+ await insertHogFunctionTemplate(hub.postgres, {
+ id: 'template-workflows-e2e-fetch',
+ name: 'Workflows E2E Fetch',
+ code: `
+ let res := fetch(inputs.url, {'method': inputs.method});
+ print('Fetch result:', res.status);
+ `,
+ inputs_schema: [
+ { key: 'url', type: 'string', required: true },
+ { key: 'method', type: 'string', required: false },
+ ],
+ })
+
+ mockFetch.mockResolvedValue({
+ status: 200,
+ headers: { 'Content-Type': 'application/json' },
+ json: () => Promise.resolve({ success: true }),
+ text: () => Promise.resolve(JSON.stringify({ success: true })),
+ dump: () => Promise.resolve(),
+ })
+
+ const emailAction = (label: string) => ({
+ type: 'function_email' as const,
+ config: {
+ template_id: 'template-workflows-e2e-email',
+ inputs: {
+ email: {
+ value: {
+ to: { email: '[email protected]', name: 'Recipient' },
+ from: { integrationId: 1, email: '[email protected]' },
+ subject: label,
+ text: label,
+ html: `<p>${label}</p>`,
+ },
+ },
+ },
+ },
+ })
+
+ const hogFlow = new FixtureHogFlowBuilder()
+ .withTeamId(team.id)
+ .withStatus('active')
+ .withExitCondition('exit_only_at_end')
+ .withWorkflow({
+ actions: {
+ trigger: {
+ type: 'trigger',
+ config: { type: 'event', filters: HOG_FILTERS_EXAMPLES.no_filters.filters ?? {} },
+ },
+ email_1: emailAction('First email'),
+ fetch_1: {
+ type: 'function',
+ config: {
+ template_id: 'template-workflows-e2e-fetch',
+ inputs: {
+ url: { value: 'https://example.com/between-emails' },
+ method: { value: 'POST' },
+ },
+ },
+ },
+ email_2: emailAction('Second email'),
+ exit: { type: 'exit', config: {} },
+ },
+ edges: [
+ { from: 'trigger', to: 'email_1', type: 'continue' },
+ { from: 'email_1', to: 'fetch_1', type: 'continue' },
+ { from: 'fetch_1', to: 'email_2', type: 'continue' },
+ { from: 'email_2', to: 'exit', type: 'continue' },
+ ],
+ })
+ .build()
+ await insertHogFlow(hub.postgres, hogFlow)
+
+ const { backgroundTask } = await eventsConsumer.processBatch([createGlobals()])
+ await backgroundTask
+
+ // The fetch must fire exactly once — happens on the hogflow worker between
+ // the two email queue hops. If it never fires, the email worker is failing
+ // to route back to hogflow after the first send.
+ await waitForExpect(() => {
+ expect(mockFetch).toHaveBeenCalledTimes(1)
+ expect(mockFetch).toHaveBeenCalledWith(
+ 'https://example.com/between-emails',
+ expect.objectContaining({ method: 'POST' })
+ )
+ }, 15000)
+
+ // Two emails were queued and two were sent — one for each side of the fetch.
+ // Sum `count` across all messages: with aggregator in-memory dedup we'd
+ // miss a 2× per-send bug by only counting messages, not their counts.
+ await waitForExpect(() => {
+ const sumCounts = (filter: (m: any) => boolean) =>
+ mockProducerObserver
+ .getProducedKafkaMessagesForTopic(KAFKA_APP_METRICS_2)
+ .filter(filter)
+ .reduce((sum: number, m: any) => sum + m.value.count, 0)
+
+ expect(sumCounts((m) => m.value.metric_name === 'email_queued')).toBe(2)
+ expect(sumCounts((m) => m.value.metric_name === 'email_sent')).toBe(2)
+ }, 15000)
+
+ await waitForExpect(async () => {
+ const jobs = await queryCyclotronJobs()
+ const terminal = jobs.filter(
+ (j: any) => j.status === 'completed' || j.status === 'failed' || j.status === 'canceled'
+ )
+ expect(terminal.length).toBeGreaterThanOrEqual(1)
+ }, 10000)
+ })
+})
diff --git a/nodejs/src/common/config.ts b/nodejs/src/common/config.ts
index e86a61087f44..202795e6e1ee 100644
--- a/nodejs/src/common/config.ts
+++ b/nodejs/src/common/config.ts
@@ -27,6 +27,7 @@ export enum PluginServerMode {
cdp_cohort_membership = 'cdp-cohort-membership',
cdp_cyclotron_worker_hogflow = 'cdp-cyclotron-worker-hogflow',
cdp_cyclotron_worker_hogflow_legacy_pg = 'cdp-cyclotron-worker-hogflow-legacy-pg',
+ cdp_cyclotron_worker_email = 'cdp-cyclotron-worker-email',
cdp_api = 'cdp-api',
cdp_legacy_on_event = 'cdp-legacy-on-event',
evaluation_scheduler = 'evaluation-scheduler',
diff --git a/nodejs/src/config/config.test.ts b/nodejs/src/config/config.test.ts
new file mode 100644
index 000000000000..b3a1d15a4346
--- /dev/null
+++ b/nodejs/src/config/config.test.ts
@@ -0,0 +1,19 @@
+import { buildIntegerMatcherWithPercentage } from './config'
+
+describe('buildIntegerMatcherWithPercentage', () => {
+ it.each([
+ ['', 123, false],
+ [undefined, 123, false],
+ ['*', 123, true],
+ ['*', 456, true],
+ ['123,456', 123, true],
+ ['123,456', 456, true],
+ ['123,456', 789, false],
+ ['*:1.0', 123, true],
+ ['*:0', 123, false],
+ ['123,*:0', 123, true],
+ ['123,*:0', 456, false],
+ ])('buildIntegerMatcherWithPercentage(%s)(%s) === %s', (config, id, expected) => {
+ expect(buildIntegerMatcherWithPercentage(config as string | undefined)(id as number)).toBe(expected)
+ })
+})
diff --git a/nodejs/src/config/config.ts b/nodejs/src/config/config.ts
index ac841ae95b17..1d5e91aef1a7 100644
--- a/nodejs/src/config/config.ts
+++ b/nodejs/src/config/config.ts
@@ -142,6 +142,50 @@ export function buildIntegerMatcher(config: string | undefined, allowStar: boole
}
}
+/**
+ * Builds a matcher that supports team IDs and/or percentage-based rollout.
+ *
+ * Formats:
+ * '' → no match
+ * '*' → match all
+ * '123,456' → only teams 123 and 456
+ * '*:0.1' → 10% of all traffic (random per call)
+ * '123,*:0.05' → team 123 always + 5% of all other teams
+ */
+export function buildIntegerMatcherWithPercentage(config: string | undefined): ValueMatcher<number> {
+ if (!config || config.trim().length === 0) {
+ return () => false
+ }
+ if (config.trim() === '*') {
+ return () => true
+ }
+
+ const parts = config.split(',').map((s) => s.trim())
+ const teamIds = new Set<number>()
+ let percentage = 0
+
+ for (const part of parts) {
+ if (part.startsWith('*:')) {
+ percentage = parseFloat(part.slice(2))
+ } else {
+ const num = parseInt(part)
+ if (!isNaN(num)) {
+ teamIds.add(num)
+ }
+ }
+ }
+
+ return (teamId: number) => {
+ if (teamIds.has(teamId)) {
+ return true
+ }
+ if (percentage > 0) {
+ return Math.random() < percentage
+ }
+ return false
+ }
+}
+
export function buildStringMatcher(config: string | undefined, allowStar: boolean): ValueMatcher<string> {
// Builds a ValueMatcher on a comma-separated list of values.
// Optionally, supports a '*' value to match everything
diff --git a/nodejs/src/server.ts b/nodejs/src/server.ts
index 984f07850877..a0c6de9545c1 100644
--- a/nodejs/src/server.ts
+++ b/nodejs/src/server.ts
@@ -8,6 +8,7 @@ import { CdpApi } from './cdp/cdp-api'
import { CdpConsumerBaseDeps } from './cdp/consumers/cdp-base.consumer'
import { CdpBatchHogFlowRequestsConsumer } from './cdp/consumers/cdp-batch-hogflow.consumer'
import { CdpCohortMembershipConsumer } from './cdp/consumers/cdp-cohort-membership.consumer'
+import { CdpCyclotronWorkerEmail } from './cdp/consumers/cdp-cyclotron-worker-email.consumer'
import { CdpCyclotronWorkerHogFlow } from './cdp/consumers/cdp-cyclotron-worker-hogflow.consumer'
import { CdpCyclotronWorker } from './cdp/consumers/cdp-cyclotron-worker.consumer'
import { CdpDatawarehouseEventsConsumer } from './cdp/consumers/cdp-data-warehouse-events.consumer'
@@ -91,6 +92,7 @@ export class PluginServer implements NodeServer {
capabilities.cdpCyclotronWorker ||
capabilities.cdpCyclotronWorkerHogFlow ||
capabilities.cdpCyclotronWorkerHogFlowLegacyPg ||
+ capabilities.cdpCyclotronWorkerEmail ||
capabilities.cdpPrecalculatedFilters ||
capabilities.cdpCohortMembership ||
capabilities.cdpBatchHogFlow ||
@@ -236,7 +238,14 @@ export class PluginServer implements NodeServer {
if (capabilities.cdpCyclotronWorkerHogFlow) {
serviceLoaders.push(async () => {
- const worker = new CdpCyclotronWorkerHogFlow(this.config, cdpDeps!, postgresV2Queue)
+ // Dedicated queue instance per consumer worker — sharing one
+ // CyclotronJobQueuePostgresV2 across two consumers (hogflow + email)
+ // collides on `this.worker`, `pendingJobs`, and the pg pool. In
+ // prod each capability runs in its own pod so they get fresh
+ // instances naturally; locally we'd silently double-process when
+ // both capabilities are enabled in the same process.
+ const queue = new CyclotronJobQueuePostgresV2(this.config.CONSUMER_BATCH_SIZE, this.config)
+ const worker = new CdpCyclotronWorkerHogFlow(this.config, cdpDeps!, queue)
await worker.start()
return worker.service
})
@@ -263,6 +272,16 @@ export class PluginServer implements NodeServer {
})
}
+ if (capabilities.cdpCyclotronWorkerEmail) {
+ serviceLoaders.push(async () => {
+ // Dedicated queue instance — see note on cdpCyclotronWorkerHogFlow above.
+ const queue = new CyclotronJobQueuePostgresV2(this.config.CONSUMER_BATCH_SIZE, this.config)
+ const worker = new CdpCyclotronWorkerEmail(this.config, cdpDeps!, queue)
+ await worker.start()
+ return worker.service
+ })
+ }
+
if (capabilities.cdpHogflowScheduler) {
serviceLoaders.push(() => {
const scheduler = new HogFlowScheduleService(this.config)
diff --git a/nodejs/src/types.ts b/nodejs/src/types.ts
index 2633902c49ba..b5f509c46476 100644
--- a/nodejs/src/types.ts
+++ b/nodejs/src/types.ts
@@ -167,6 +167,7 @@ export interface PluginServerCapabilities {
cdpCyclotronWorker?: boolean
cdpCyclotronWorkerHogFlow?: boolean
cdpCyclotronWorkerHogFlowLegacyPg?: boolean
+ cdpCyclotronWorkerEmail?: boolean
cdpPrecalculatedFilters?: boolean
cdpCohortMembership?: boolean
cdpApi?: boolean