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): add email MX validation service for preventing hard bounces (#67638)

Meikel Ratz6cd48ff81c9e
diff --git a/nodejs/src/cdp/cdp-services.ts b/nodejs/src/cdp/cdp-services.ts
index 08d52e39d150..da45b3ef458d 100644
--- a/nodejs/src/cdp/cdp-services.ts
+++ b/nodejs/src/cdp/cdp-services.ts
@@ -31,6 +31,7 @@ import { HogFunctionTemplateManagerService } from './services/managers/hog-funct
import { IntegrationManagerService } from './services/managers/integration-manager.service'
import { RecipientsManagerService } from './services/managers/recipients-manager.service'
import { TeamWorkflowsConfigService } from './services/managers/team-workflows-config.service'
+import { EmailValidationService } from './services/messaging/email-validation.service'
import { EmailService } from './services/messaging/email.service'
import { EmailTrackingCodeSigner } from './services/messaging/helpers/tracking-code'
import { MessageAssetsService } from './services/messaging/message-assets.service'
@@ -148,6 +149,8 @@ export type CdpCoreServicesConfig = Pick<
| 'CDP_FETCH_BACKOFF_MAX_MS'
| 'CDP_SELF_LOOP_GUARD_MODE'
| 'CDP_EMAIL_TRACKING_URL'
+ | 'CDP_EMAIL_MX_VALIDATION_ENABLED'
+ | 'CDP_EMAIL_MX_VALIDATION_ENFORCE_TEAMS'
| 'HOG_FUNCTION_MONITORING_APP_METRICS_TOPIC'
| 'HOG_FUNCTION_MONITORING_APP_METRICS_PRODUCER'
| 'HOG_FUNCTION_MONITORING_LOG_ENTRIES_TOPIC'
@@ -175,6 +178,13 @@ export interface CdpCoreServicesDeps {
/** Registry of producers backing the CDP outputs (DEFAULT / MSK / Warpstream-ingestion / Warehouse). */
cdpProducerRegistry: KafkaProducerRegistry<CdpProducerName>
internalCaptureService: InternalCaptureService
+ /**
+ * SES Valkey pool shared with the SES rate limiter, opened only on pods whose
+ * capabilities actually execute email actions (hogflow/email cyclotron workers).
+ * `null` on every other CDP consumer and on cdp-api so idle pods don't hold
+ * open connections against the SES Valkey instance.
+ */
+ emailValidationValkey: RedisV2 | null
}
/**
@@ -426,11 +436,17 @@ export function createCdpCoreServices(
const recipientsManager = new RecipientsManagerService(deps.postgres)
const recipientPreferencesService = new RecipientPreferencesService(recipientsManager)
+ // MX verdicts live on the dedicated SES Valkey (same instance as the SES rate
+ // limiter, separate pool). The pool is created by the server only on pods
+ // whose capabilities execute email actions; everywhere else this is null
+ // and EmailValidationService degrades to the local cache + DNS.
+ const emailValidationService = new EmailValidationService(config, deps.emailValidationValkey)
// Observer mirrors writes to Valkey (load-only); only the primary path drives metrics.
const hogFlowDuplicateObserver = new HogFlowDuplicateObserverService(redis, valkeyShadow?.writer ?? null)
const hogFlowExecutor = new HogFlowExecutorService(
hogFlowFunctionsService,
recipientPreferencesService,
+ emailValidationService,
hogFlowDuplicateObserver
)
diff --git a/nodejs/src/cdp/config.ts b/nodejs/src/cdp/config.ts
index 6ad5297c3968..7d6a140a9ae3 100644
--- a/nodejs/src/cdp/config.ts
+++ b/nodejs/src/cdp/config.ts
@@ -52,6 +52,18 @@ export type CdpConfig = ClickhouseConfig & {
CDP_CYCLOTRON_JOB_QUEUE_CONSUMER_MODE: CyclotronJobQueueSource
CDP_CYCLOTRON_STRIP_PERSON_FROM_STATE_TEAMS: string
+ // Master switch for pre-send email MX validation, off by default. When true,
+ // every email send is validated (syntax + MX lookup, cached per domain) and
+ // would-skip outcomes are recorded in Prometheus — shadow mode unless the team
+ // is also matched by CDP_EMAIL_MX_VALIDATION_ENFORCE_TEAMS, which controls
+ // actual skipping.
+ CDP_EMAIL_MX_VALIDATION_ENABLED: boolean
+ // Teams whose predicted hard bounces are actually skipped (same string format as
+ // the other team matchers: '' = none, '*' = all, '2,7' = exact set). Teams not
+ // matched here are observe-only: validation runs and metrics are recorded, but
+ // the send always proceeds.
+ CDP_EMAIL_MX_VALIDATION_ENFORCE_TEAMS: string
+
CDP_LEGACY_EVENT_CONSUMER_GROUP_ID: string
CDP_LEGACY_EVENT_CONSUMER_TOPIC: string
CDP_LEGACY_EVENT_CONSUMER_INCLUDE_WEBHOOKS: boolean
@@ -178,6 +190,8 @@ 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_MX_VALIDATION_ENABLED: false,
+ CDP_EMAIL_MX_VALIDATION_ENFORCE_TEAMS: '',
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/services/hogflows/actions/hog_function.test.ts b/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts
index bce47c813d20..4667b42144f9 100644
--- a/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts
+++ b/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts
@@ -16,6 +16,7 @@ import { HogExecutorService } from '../../hog-executor.service'
import { HogInputsService } from '../../hog-inputs.service'
import { HogFunctionTemplateManagerService } from '../../managers/hog-function-template-manager.service'
import { TeamWorkflowsConfigService } from '../../managers/team-workflows-config.service'
+import { EmailValidationService } from '../../messaging/email-validation.service'
import { EmailService } from '../../messaging/email.service'
import { EmailTrackingCodeSigner } from '../../messaging/helpers/tracking-code'
import { RecipientPreferencesService } from '../../messaging/recipient-preferences.service'
@@ -32,6 +33,7 @@ describe('HogFunctionHandler', () => {
let mockHogFunctionTemplateManager: HogFunctionTemplateManagerService
let mockHogFlowFunctionsService: HogFlowFunctionsService
let mockRecipientPreferencesService: RecipientPreferencesService
+ let mockEmailValidationService: EmailValidationService
let invocation: CyclotronJobInvocationHogFlow
let action: Extract<HogFlowAction, { type: 'function' }>
@@ -80,9 +82,13 @@ describe('HogFunctionHandler', () => {
mockRecipientPreferencesService = {
shouldSkipAction: jest.fn().mockResolvedValue(false),
} as any
+ mockEmailValidationService = {
+ getSkipReason: jest.fn().mockResolvedValue(null),
+ } as any
hogFunctionHandler = new HogFunctionHandler(
mockHogFlowFunctionsService,
mockRecipientPreferencesService,
+ mockEmailValidationService,
'fetch'
)
@@ -325,6 +331,34 @@ describe('HogFunctionHandler', () => {
expect(mockFetch).not.toHaveBeenCalled()
})
+ it('should skip the send and emit email_bounce_prevented when validation predicts a hard bounce', async () => {
+ ;(mockEmailValidationService.getSkipReason as jest.Mock).mockResolvedValueOnce(
+ 'Skipping send: the domain "dead.invalid" has no reachable mail servers, so this message would hard bounce.'
+ )
+
+ const invocationResult = createInvocationResult<CyclotronJobInvocationHogFlow>(invocation, {
+ queue: 'hog',
+ queuePriority: 0,
+ })
+
+ const handlerResult = await hogFunctionHandler.execute({ invocation, action, result: invocationResult })
+
+ // Flow continues to the next action (a skip, not a failure branch), and nothing was sent.
+ expect(handlerResult.nextAction?.id).toBe('exit')
+ expect(mockFetch).not.toHaveBeenCalled()
+ expect(invocationResult.logs[0].message).toContain('no reachable mail servers')
+ expect(invocationResult.metrics).toEqual([
+ {
+ team_id: team.id,
+ app_source_id: invocation.functionId,
+ instance_id: action.id,
+ metric_kind: 'email',
+ metric_name: 'email_bounce_prevented',
+ count: 1,
+ },
+ ])
+ })
+
it('should emit a single billable_invocation metric upon function completion', async () => {
const invocationResult = createInvocationResult<CyclotronJobInvocationHogFlow>(invocation, {
queue: 'hog',
@@ -353,6 +387,7 @@ describe('HogFunctionHandler', () => {
hogFunctionHandler = new HogFunctionHandler(
mockHogFlowFunctionsService,
mockRecipientPreferencesService,
+ mockEmailValidationService,
'email'
)
diff --git a/nodejs/src/cdp/services/hogflows/actions/hog_function.ts b/nodejs/src/cdp/services/hogflows/actions/hog_function.ts
index 3d9f2722109a..4a076a833e55 100644
--- a/nodejs/src/cdp/services/hogflows/actions/hog_function.ts
+++ b/nodejs/src/cdp/services/hogflows/actions/hog_function.ts
@@ -9,6 +9,7 @@ import {
MinimalLogEntry,
} from '../../../types'
import { HogExecutorExecuteAsyncOptions } from '../../hog-executor.service'
+import { EmailValidationService } from '../../messaging/email-validation.service'
import { RecipientPreferencesService } from '../../messaging/recipient-preferences.service'
import { trackHogFlowBillableInvocation } from '../billing-utils'
import { HogFlowFunctionsService } from '../hogflow-functions.service'
@@ -23,6 +24,7 @@ export class HogFunctionHandler implements ActionHandler {
constructor(
private hogFlowFunctionsService: HogFlowFunctionsService,
private recipientPreferencesService: RecipientPreferencesService,
+ private emailValidationService: EmailValidationService,
private hogFlowActionBillingType: 'fetch' | 'email'
) {}
@@ -130,6 +132,32 @@ export class HogFunctionHandler implements ActionHandler {
}
}
+ // Predicted hard bounce (bad syntax / dead domain): skip before the send reaches
+ // SES so it never counts against our bounce rate. Runs after the opt-out check so
+ // an opted-out recipient never triggers a DNS lookup.
+ const emailSkipReason = await this.emailValidationService.getSkipReason(hogFunctionInvocation, action)
+ if (emailSkipReason) {
+ return {
+ finished: true,
+ skipped: true,
+ invocation: hogFunctionInvocation,
+ logs: [{ level: 'info', timestamp: DateTime.now(), message: emailSkipReason }],
+ metrics: [
+ {
+ team_id: hogFunctionInvocation.teamId,
+ app_source_id: hogFunctionInvocation.functionId,
+ instance_id: action.id,
+ metric_kind: 'email',
+ metric_name: 'email_bounce_prevented',
+ count: 1,
+ },
+ ],
+ capturedPostHogEvents: [],
+ warehouseWebhookPayloads: [],
+ emailAssets: [],
+ }
+ }
+
return this.hogFlowFunctionsService.executeWithAsyncFunctions(hogFunctionInvocation, hogExecutorOptions)
}
}
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 b00725bd4be8..71b00950ce95 100644
--- a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts
+++ b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts
@@ -22,6 +22,7 @@ import { RecipientTokensService } from '../messaging/recipient-tokens.service'
import { HogFunctionTemplateManagerService } from '../managers/hog-function-template-manager.service'
import { RecipientsManagerService } from '../managers/recipients-manager.service'
import { TeamWorkflowsConfigService } from '../managers/team-workflows-config.service'
+import { EmailValidationService } from '../messaging/email-validation.service'
import { RecipientPreferencesService } from '../messaging/recipient-preferences.service'
import { HogFlowExecutorService, createHogFlowInvocation } from './hogflow-executor.service'
import { HogFlowFunctionsService } from './hogflow-functions.service'
@@ -99,6 +100,11 @@ describe('Hogflow Executor', () => {
)
const recipientsManager = new RecipientsManagerService(hub.postgres)
const recipientPreferencesService = new RecipientPreferencesService(recipientsManager)
+ // Kill switch off — getSkipReason short-circuits to null, so email validation never does real DNS here.
+ const emailValidationService = new EmailValidationService(
+ { CDP_EMAIL_MX_VALIDATION_ENABLED: false, CDP_EMAIL_MX_VALIDATION_ENFORCE_TEAMS: '' },
+ null
+ )
await insertHogFunctionTemplate(hub.postgres, {
id: 'template-test-hogflow-executor',
@@ -135,7 +141,11 @@ describe('Hogflow Executor', () => {
await insertHogFunctionTemplate(hub.postgres, posthogCaptureTemplate)
- executor = new HogFlowExecutorService(hogFlowFunctionsService, recipientPreferencesService)
+ executor = new HogFlowExecutorService(
+ hogFlowFunctionsService,
+ recipientPreferencesService,
+ emailValidationService
+ )
})
describe('general event processing', () => {
diff --git a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts
index 8eb05add61d3..ea2223a4910e 100644
--- a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts
+++ b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts
@@ -21,6 +21,7 @@ import {
import { convertToHogFunctionFilterGlobal, filterFunctionInstrumented } from '../../utils/hog-function-filtering'
import { createInvocationResult } from '../../utils/invocation-utils'
import { HogExecutorExecuteAsyncOptions } from '../hog-executor.service'
+import { EmailValidationService } from '../messaging/email-validation.service'
import { RecipientPreferencesService } from '../messaging/recipient-preferences.service'
import { ActionHandler } from './actions/action.interface'
import { ConditionalBranchHandler } from './actions/conditional_branch'
@@ -87,13 +88,20 @@ export class HogFlowExecutorService {
constructor(
hogFlowFunctionsService: HogFlowFunctionsService,
recipientPreferencesService: RecipientPreferencesService,
+ emailValidationService: EmailValidationService,
duplicateObserver?: HogFlowDuplicateObserverService
) {
this.duplicateObserver = duplicateObserver ?? null
- const hogFunctionHandler = new HogFunctionHandler(hogFlowFunctionsService, recipientPreferencesService, 'fetch')
+ const hogFunctionHandler = new HogFunctionHandler(
+ hogFlowFunctionsService,
+ recipientPreferencesService,
+ emailValidationService,
+ 'fetch'
+ )
const hogFunctionEmailHandler = new HogFunctionHandler(
hogFlowFunctionsService,
recipientPreferencesService,
+ emailValidationService,
'email'
)
diff --git a/nodejs/src/cdp/services/messaging/email-validation.service.test.ts b/nodejs/src/cdp/services/messaging/email-validation.service.test.ts
new file mode 100644
index 000000000000..8b11fb629598
--- /dev/null
+++ b/nodejs/src/cdp/services/messaging/email-validation.service.test.ts
@@ -0,0 +1,270 @@
+import { register } from 'prom-client'
+
+import { RedisV2 } from '~/common/redis/redis-v2'
+
+import { CyclotronJobInvocationHogFunction } from '../../types'
+import { EmailValidationService, MAX_LOCAL_CACHE_DOMAINS } from './email-validation.service'
+
+const mockResolveMx = jest.fn()
+const mockResolve4 = jest.fn()
+const mockResolve6 = jest.fn()
+
+jest.mock('node:dns/promises', () => ({
+ Resolver: jest.fn().mockImplementation(() => ({
+ resolveMx: mockResolveMx,
+ resolve4: mockResolve4,
+ resolve6: mockResolve6,
+ })),
+}))
+
+const dnsError = (code: string): NodeJS.ErrnoException => Object.assign(new Error(code), { code })
+
+const emailInvocation = (email: unknown, teamId = 2): CyclotronJobInvocationHogFunction =>
+ ({
+ teamId,
+ id: 'inv-1',
+ functionId: 'flow-1',
+ state: { actionId: 'act-1', globals: { inputs: { email: { to: { email } } } } },
+ }) as any
+
+const emailAction = { type: 'function_email', id: 'act-1' } as any
+
+describe('EmailValidationService', () => {
+ let service: EmailValidationService
+
+ beforeEach(() => {
+ jest.clearAllMocks()
+ // Default to a healthy domain so tests only override what they exercise.
+ mockResolveMx.mockResolvedValue([{ exchange: 'mx.example.com', priority: 10 }])
+ mockResolve4.mockResolvedValue(['1.2.3.4'])
+ mockResolve6.mockResolvedValue([])
+ service = new EmailValidationService(
+ { CDP_EMAIL_MX_VALIDATION_ENABLED: true, CDP_EMAIL_MX_VALIDATION_ENFORCE_TEAMS: '2' },
+ null
+ )
+ })
+
+ describe('gating and shadow mode', () => {
+ it('does not validate (returns null, no DNS) for non-email actions', async () => {
+ const reason = await service.getSkipReason(emailInvocation('[email protected]'), {
+ type: 'function_sms',
+ id: 'act-1',
+ } as any)
+ expect(reason).toBeNull()
+ expect(mockResolveMx).not.toHaveBeenCalled()
+ })
+
+ it('does nothing when the kill switch is off, even for a dead domain', async () => {
+ const disabled = new EmailValidationService(
+ { CDP_EMAIL_MX_VALIDATION_ENABLED: false, CDP_EMAIL_MX_VALIDATION_ENFORCE_TEAMS: '*' },
+ null
+ )
+ expect(await disabled.getSkipReason(emailInvocation('[email protected]'), emailAction)).toBeNull()
+ expect(mockResolveMx).not.toHaveBeenCalled()
+ })
+
+ it('shadow mode: validates and records the would-skip, but lets the send proceed', async () => {
+ mockResolveMx.mockRejectedValue(dnsError('ENOTFOUND'))
+ mockResolve4.mockRejectedValue(dnsError('ENOTFOUND'))
+ mockResolve6.mockRejectedValue(dnsError('ENOTFOUND'))
+
+ // Team 3 is not in the enforce list ('2') — observe-only.
+ const reason = await service.getSkipReason(emailInvocation('[email protected]', 3), emailAction)
+
+ expect(reason).toBeNull()
+ expect(mockResolveMx).toHaveBeenCalled()
+ const metric = await register.getSingleMetric('cdp_email_mx_would_skip_total')!.get()
+ expect(metric.values).toContainEqual(
+ expect.objectContaining({ labels: { team_id: '3', reason: 'invalid_domain' } })
+ )
+ })
+
+ it('enforces skips for all teams when configured with "*"', async () => {
+ const wildcard = new EmailValidationService(
+ { CDP_EMAIL_MX_VALIDATION_ENABLED: true, CDP_EMAIL_MX_VALIDATION_ENFORCE_TEAMS: '*' },
+ null
+ )
+ mockResolveMx.mockRejectedValue(dnsError('ENOTFOUND'))
+ mockResolve4.mockRejectedValue(dnsError('ENOTFOUND'))
+ mockResolve6.mockRejectedValue(dnsError('ENOTFOUND'))
+
+ const reason = await wildcard.getSkipReason(emailInvocation('[email protected]', 999), emailAction)
+ expect(reason).toContain('no reachable mail servers')
+ })
+ })
+
+ describe('syntax validation', () => {
+ it.each([
+ ['missing @', 'not-an-email'],
+ ['empty local part', '@example.com'],
+ ['no domain dot', 'user@localhost'],
+ ['whitespace', 'user @example.com'],
+ ['double @', 'a@[email protected]'],
+ ])('blocks %s without a DNS lookup', async (_label, email) => {
+ const reason = await service.getSkipReason(emailInvocation(email), emailAction)
+ expect(reason).toContain('not a valid email address')
+ expect(mockResolveMx).not.toHaveBeenCalled()
+ })
+
+ it.each([
+ ['missing recipient', undefined],
+ ['empty string', ''],
+ ['non-string', 12345],
+ ])('leaves %s for the existing send path (returns null)', async (_label, email) => {
+ const reason = await service.getSkipReason(emailInvocation(email), emailAction)
+ expect(reason).toBeNull()
+ expect(mockResolveMx).not.toHaveBeenCalled()
+ })
+ })
+
+ describe('domain deliverability', () => {
+ it('allows a domain with MX records', async () => {
+ mockResolveMx.mockResolvedValue([{ exchange: 'aspmx.l.google.com', priority: 1 }])
+ expect(await service.getSkipReason(emailInvocation('[email protected]'), emailAction)).toBeNull()
+ })
+
+ it('resolves internationalized domains via their punycode form', async () => {
+ mockResolveMx.mockRejectedValue(dnsError('ENOTFOUND'))
+ mockResolve4.mockRejectedValue(dnsError('ENOTFOUND'))
+ mockResolve6.mockRejectedValue(dnsError('ENOTFOUND'))
+
+ const reason = await service.getSkipReason(emailInvocation('user@bücher.example'), emailAction)
+
+ // The unicode form would error at the resolver (bypassing validation); the
+ // punycode form gets a real verdict — here, a definitive block.
+ expect(mockResolveMx).toHaveBeenCalledWith('xn--bcher-kva.example')
+ expect(reason).toContain('no reachable mail servers')
+ })
+
+ it('allows a domain with no MX but an A record (RFC 5321 implicit MX)', async () => {
+ mockResolveMx.mockRejectedValue(dnsError('ENODATA'))
+ mockResolve4.mockResolvedValue(['93.184.216.34'])
+ expect(await service.getSkipReason(emailInvocation('[email protected]'), emailAction)).toBeNull()
+ })
+
+ it('allows a domain with no MX or A but an AAAA record', async () => {
+ mockResolveMx.mockRejectedValue(dnsError('ENODATA'))
+ mockResolve4.mockRejectedValue(dnsError('ENODATA'))
+ mockResolve6.mockResolvedValue(['2606:2800:220:1:248:1893:25c8:1946'])
+ expect(await service.getSkipReason(emailInvocation('[email protected]'), emailAction)).toBeNull()
+ })
+
+ it('blocks a domain with no MX and no address records', async () => {
+ mockResolveMx.mockRejectedValue(dnsError('ENODATA'))
+ mockResolve4.mockRejectedValue(dnsError('ENODATA'))
+ mockResolve6.mockRejectedValue(dnsError('ENODATA'))
+ expect(await service.getSkipReason(emailInvocation('[email protected]'), emailAction)).toContain(
+ 'no reachable mail servers'
+ )
+ })
+
+ it('blocks a non-existent domain (NXDOMAIN)', async () => {
+ mockResolveMx.mockRejectedValue(dnsError('ENOTFOUND'))
+ mockResolve4.mockRejectedValue(dnsError('ENOTFOUND'))
+ mockResolve6.mockRejectedValue(dnsError('ENOTFOUND'))
+ expect(await service.getSkipReason(emailInvocation('[email protected]'), emailAction)).toContain(
+ 'no reachable mail servers'
+ )
+ })
+
+ it('blocks a domain that publishes a null MX (RFC 7505) without an A-record fallback', async () => {
+ mockResolveMx.mockResolvedValue([{ exchange: '', priority: 0 }])
+ expect(await service.getSkipReason(emailInvocation('[email protected]'), emailAction)).toContain(
+ 'no reachable mail servers'
+ )
+ expect(mockResolve4).not.toHaveBeenCalled()
+ })
+ })
+
+ describe('fail-open on transient DNS errors', () => {
+ it.each([['ESERVFAIL'], ['ETIMEOUT'], ['EREFUSED'], ['ECONNREFUSED']])(
+ 'allows the send when the MX lookup fails with %s',
+ async (code) => {
+ mockResolveMx.mockRejectedValue(dnsError(code))
+ expect(await service.getSkipReason(emailInvocation('[email protected]'), emailAction)).toBeNull()
+ }
+ )
+
+ it('allows the send when the A-record fallback lookup is transiently unavailable', async () => {
+ mockResolveMx.mockRejectedValue(dnsError('ENODATA'))
+ mockResolve4.mockRejectedValue(dnsError('ESERVFAIL'))
+ expect(await service.getSkipReason(emailInvocation('[email protected]'), emailAction)).toBeNull()
+ })
+
+ it('backs off briefly after a transient failure, then re-resolves instead of freezing the verdict', async () => {
+ const now = Date.now()
+ const nowSpy = jest.spyOn(Date, 'now').mockReturnValue(now)
+ try {
+ mockResolveMx.mockRejectedValueOnce(dnsError('ETIMEOUT'))
+ expect(await service.getSkipReason(emailInvocation('[email protected]'), emailAction)).toBeNull()
+
+ // Within the backoff window: still allowed, but without paying another slow lookup.
+ expect(await service.getSkipReason(emailInvocation('[email protected]'), emailAction)).toBeNull()
+ expect(mockResolveMx).toHaveBeenCalledTimes(1)
+
+ // Past the window: DNS is consulted again, so the unknown verdict isn't frozen.
+ nowSpy.mockReturnValue(now + 61_000)
+ mockResolveMx.mockResolvedValue([{ exchange: 'mx.flaky.example', priority: 10 }])
+ expect(await service.getSkipReason(emailInvocation('[email protected]'), emailAction)).toBeNull()
+ expect(mockResolveMx).toHaveBeenCalledTimes(2)
+ } finally {
+ nowSpy.mockRestore()
+ }
+ })
+ })
+
+ describe('per-domain caching', () => {
+ it('resolves each domain once and serves repeats from the in-process cache', async () => {
+ mockResolveMx.mockResolvedValue([{ exchange: 'mx.example.com', priority: 10 }])
+ for (let i = 0; i < 5; i++) {
+ await service.getSkipReason(emailInvocation(`user${i}@example.com`), emailAction)
+ }
+ expect(mockResolveMx).toHaveBeenCalledTimes(1)
+ })
+
+ it('coalesces concurrent lookups for the same domain into a single DNS query', async () => {
+ let resolveLookup: (records: unknown[]) => void = () => {}
+ mockResolveMx.mockReturnValue(new Promise((resolve) => (resolveLookup = resolve)))
+
+ const inFlight = Promise.all(
+ Array.from({ length: 50 }, (_, i) =>
+ service.getSkipReason(emailInvocation(`user${i}@example.com`), emailAction)
+ )
+ )
+ resolveLookup([{ exchange: 'mx.example.com', priority: 10 }])
+ const reasons = await inFlight
+
+ expect(mockResolveMx).toHaveBeenCalledTimes(1)
+ expect(reasons.every((r) => r === null)).toBe(true)
+ })
+
+ it('evicts the oldest domain once the cache is full instead of growing unbounded', async () => {
+ for (let i = 0; i <= MAX_LOCAL_CACHE_DOMAINS; i++) {
+ await service.getSkipReason(emailInvocation(`user@domain-${i}.example`), emailAction)
+ }
+ expect(mockResolveMx).toHaveBeenCalledTimes(MAX_LOCAL_CACHE_DOMAINS + 1)
+
+ // domain-0 was evicted to make room, so it resolves again; a recently
+ // inserted domain is still served from the cache.
+ await service.getSkipReason(emailInvocation('[email protected]'), emailAction)
+ expect(mockResolveMx).toHaveBeenCalledTimes(MAX_LOCAL_CACHE_DOMAINS + 2)
+ await service.getSkipReason(emailInvocation(`user@domain-${MAX_LOCAL_CACHE_DOMAINS}.example`), emailAction)
+ expect(mockResolveMx).toHaveBeenCalledTimes(MAX_LOCAL_CACHE_DOMAINS + 2)
+ })
+
+ it('honors a Valkey-cached verdict without hitting DNS', async () => {
+ const valkey: RedisV2 = {
+ useClient: jest.fn().mockResolvedValue('0'), // '0' = domain previously found undeliverable
+ usePipeline: jest.fn(),
+ }
+ const withValkey = new EmailValidationService(
+ { CDP_EMAIL_MX_VALIDATION_ENABLED: true, CDP_EMAIL_MX_VALIDATION_ENFORCE_TEAMS: '2' },
+ valkey
+ )
+
+ const reason = await withValkey.getSkipReason(emailInvocation('[email protected]'), emailAction)
+ expect(reason).toContain('no reachable mail servers')
+ expect(mockResolveMx).not.toHaveBeenCalled()
+ })
+ })
+})
diff --git a/nodejs/src/cdp/services/messaging/email-validation.service.ts b/nodejs/src/cdp/services/messaging/email-validation.service.ts
new file mode 100644
index 000000000000..59ae6e437c0f
--- /dev/null
+++ b/nodejs/src/cdp/services/messaging/email-validation.service.ts
@@ -0,0 +1,287 @@
+import { MxRecord } from 'node:dns'
+import { Resolver } from 'node:dns/promises'
+import { domainToASCII } from 'node:url'
+import { Counter } from 'prom-client'
+
+import { HogFlowAction } from '~/cdp/schema/hogflow'
+import { buildIntegerMatcher } from '~/common/config/config'
+import { RedisV2 } from '~/common/redis/redis-v2'
+import { ValueMatcher } from '~/types'
+
+import { CdpConfig } from '../../config'
+import { CyclotronJobInvocationHogFunction } from '../../types'
+
+const cdpEmailMxValidationTotal = new Counter({
+ name: 'cdp_email_mx_validation_total',
+ help: 'Pre-send email validation outcomes. `invalid_syntax`/`invalid_domain` are predicted hard bounces; `transient_error` means DNS was unreliable so we allowed the send (fail-open); `hit_*` are cache hits.',
+ labelNames: ['result'],
+})
+
+const cdpEmailMxWouldSkipTotal = new Counter({
+ name: 'cdp_email_mx_would_skip_total',
+ help: 'Sends that pre-send email validation would skip as predicted hard bounces, per team. Increments in both shadow and enforce mode so the series is continuous across the enforce rollout; whether the send was actually skipped depends on CDP_EMAIL_MX_VALIDATION_ENFORCE_TEAMS.',
+ labelNames: ['team_id', 'reason'],
+})
+
+// Deliberately conservative structural check — NOT full RFC 5322. It rejects
+// obviously-malformed addresses (missing `@`, whitespace, no domain dot) while
+// never rejecting an address that could actually deliver.
+const EMAIL_SYNTAX_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
+
+// Valid domains change rarely, so cache the "has mail servers" verdict for a day.
+// Negative verdicts get a shorter TTL so a domain that comes back online recovers
+// without a full day of blocked sends.
+const POSITIVE_TTL_MS = 24 * 60 * 60 * 1000
+const NEGATIVE_TTL_MS = 6 * 60 * 60 * 1000
+
+// Local-only backoff after a transient DNS failure. Short enough that a real
+// verdict is retried quickly, long enough that a resolver outage during a big
+// batch doesn't repeat a 3s-timeout lookup for every send to the same domain.
+// Never written to Valkey, so a blip on one worker isn't frozen fleet-wide.
+const TRANSIENT_BACKOFF_MS = 60 * 1000
+
+// Bound per-lookup latency: the email worker must not stall on a slow resolver.
+const DNS_TIMEOUT_MS = 3000
+const DNS_TRIES = 1
+
+// Bounds worker memory against lists full of unique garbage domains; evicted
+// domains just fall back to Valkey/DNS on their next send. ~150 B per entry,
+// so this caps the cache at roughly 15 MB per worker.
+export const MAX_LOCAL_CACHE_DOMAINS = 100_000
+
+// Same key style as the SES rate limiter's '@posthog/ses/global' on the shared Valkey.
+const VALKEY_KEY_PREFIX = '@posthog/ses/email-mx/'
+
+type CacheEntry = { deliverable: boolean; transient?: boolean; expiresAt: number }
+
+// `none` = domain exists but no records of this type; `transient` = the lookup
+// itself failed (timeout/SERVFAIL) and the verdict is unknown → fail open.
+type ResolveOutcome = 'has' | 'none' | 'transient'
+
+function classifyDnsError(error: unknown): 'none' | 'transient' {
+ const code = (error as NodeJS.ErrnoException | undefined)?.code
+ // ENOTFOUND (NXDOMAIN) and ENODATA are definitive "nothing here" answers.
+ // Everything else (ETIMEOUT, ESERVFAIL, EREFUSED, ECONNREFUSED, …) is a
+ // resolver problem, not a verdict about the domain — fail open.
+ if (code === 'ENOTFOUND' || code === 'ENODATA' || code === 'NOTFOUND' || code === 'NODATA') {
+ return 'none'
+ }
+ return 'transient'
+}
+
+/**
+ * Predicts hard bounces before a send reaches SES: an address with broken
+ * syntax or a domain with no mail servers can never deliver, so attempting the
+ * send only burns our bounce rate. Verdicts are cached per domain (in-process +
+ * the dedicated SES Valkey) so a large batch to the same domains pays the DNS
+ * cost once, protecting the *current* batch rather than only the next one.
+ *
+ * Fail-open by design: only a definitive "this domain has no mail exchange"
+ * blocks a send. A DNS hiccup must never nuke a batch of legitimate mail.
+ *
+ * Rollout is shadow-first: when enabled, every team is validated and would-skip
+ * outcomes are recorded per team in Prometheus, but only teams matched by
+ * CDP_EMAIL_MX_VALIDATION_ENFORCE_TEAMS actually get their sends skipped.
+ */
+export class EmailValidationService {
+ private readonly enabled: boolean
+ private readonly enforceMatcher: ValueMatcher<number>
+ private readonly resolver: Resolver
+ private readonly localCache = new Map<string, CacheEntry>()
+ private readonly inFlight = new Map<string, Promise<boolean>>()
+
+ constructor(
+ config: Pick<CdpConfig, 'CDP_EMAIL_MX_VALIDATION_ENABLED' | 'CDP_EMAIL_MX_VALIDATION_ENFORCE_TEAMS'>,
+ private valkey: RedisV2 | null
+ ) {
+ this.enabled = config.CDP_EMAIL_MX_VALIDATION_ENABLED
+ this.enforceMatcher = buildIntegerMatcher(config.CDP_EMAIL_MX_VALIDATION_ENFORCE_TEAMS, true)
+ this.resolver = new Resolver({ timeout: DNS_TIMEOUT_MS, tries: DNS_TRIES })
+ }
+
+ /**
+ * Returns a human-readable reason to skip the send, or null to proceed.
+ * Only acts on `function_email` actions; anything else (kill switch off,
+ * missing recipient, non-email action) returns null so the existing send
+ * path is untouched. Teams outside the enforce list are observe-only:
+ * validation runs and metrics are recorded, but null is returned.
+ */
+ public async getSkipReason(
+ invocation: CyclotronJobInvocationHogFunction,
+ action: HogFlowAction
+ ): Promise<string | null> {
+ if (!this.enabled || action.type !== 'function_email') {
+ return null
+ }
+
+ const rawEmail = invocation.state.globals.inputs?.email?.to?.email
+ if (typeof rawEmail !== 'string' || rawEmail.trim().length === 0) {
+ // Missing recipient is handled (and surfaced) by the existing opt-out check.
+ return null
+ }
+ const email = rawEmail.trim()
+
+ if (!EMAIL_SYNTAX_RE.test(email)) {
+ cdpEmailMxValidationTotal.inc({ result: 'invalid_syntax' })
+ return this.skipOrObserve(
+ invocation.teamId,
+ 'invalid_syntax',
+ `Skipping send: "${email}" is not a valid email address, so it would hard bounce.`
+ )
+ }
+
+ // domainToASCII lowercases and punycodes IDN domains (`bücher.example` →
+ // `xn--bcher-kva.example`) so the resolver sees the form DNS actually stores;
+ // without it every internationalized domain would error and bypass validation.
+ // It passes unconvertible garbage through unchanged — the lookup then fails
+ // open, which is the safe direction.
+ const rawDomain = email.slice(email.lastIndexOf('@') + 1)
+ const domain = domainToASCII(rawDomain) || rawDomain.toLowerCase()
+ const deliverable = await this.resolveDeliverability(domain)
+ if (!deliverable) {
+ return this.skipOrObserve(
+ invocation.teamId,
+ 'invalid_domain',
+ `Skipping send: the domain "${domain}" has no reachable mail servers, so this message would hard bounce.`
+ )
+ }
+ return null
+ }
+
+ private skipOrObserve(teamId: number, reason: 'invalid_syntax' | 'invalid_domain', message: string): string | null {
+ cdpEmailMxWouldSkipTotal.inc({ team_id: String(teamId), reason })
+ return this.enforceMatcher(teamId) ? message : null
+ }
+
+ private async resolveDeliverability(domain: string): Promise<boolean> {
+ const local = this.localCache.get(domain)
+ if (local && local.expiresAt > Date.now()) {
+ cdpEmailMxValidationTotal.inc({ result: local.transient ? 'transient_backoff' : 'hit_local' })
+ return local.deliverable
+ }
+
+ // Coalesce concurrent lookups for the same domain — a big batch fires
+ // thousands of parallel invocations; the first does the work, the rest wait.
+ const existing = this.inFlight.get(domain)
+ if (existing) {
+ return existing
+ }
+ const promise = this.resolveUncached(domain).finally(() => this.inFlight.delete(domain))
+ this.inFlight.set(domain, promise)
+ return promise
+ }
+
+ private async resolveUncached(domain: string): Promise<boolean> {
+ const cached = await this.readValkey(domain)
+ if (cached !== null) {
+ cdpEmailMxValidationTotal.inc({ result: 'hit_valkey' })
+ this.setLocal(domain, {
+ deliverable: cached,
+ expiresAt: Date.now() + (cached ? POSITIVE_TTL_MS : NEGATIVE_TTL_MS),
+ })
+ return cached
+ }
+
+ const status = await this.dnsLookup(domain)
+ if (status === 'transient') {
+ cdpEmailMxValidationTotal.inc({ result: 'transient_error' })
+ // Unknown verdict — fail open, remember only briefly and only locally,
+ // so a resolver outage neither blocks sends nor stalls every send to
+ // this domain on a fresh 3s-timeout lookup.
+ this.setLocal(domain, { deliverable: true, transient: true, expiresAt: Date.now() + TRANSIENT_BACKOFF_MS })
+ return true
+ }
+
+ const deliverable = status === 'valid'
+ cdpEmailMxValidationTotal.inc({ result: deliverable ? 'valid' : 'invalid_domain' })
+ this.setLocal(domain, {
+ deliverable,
+ expiresAt: Date.now() + (deliverable ? POSITIVE_TTL_MS : NEGATIVE_TTL_MS),
+ })
+ await this.writeValkey(domain, deliverable)
+ return deliverable
+ }
+
+ private async dnsLookup(domain: string): Promise<'valid' | 'invalid' | 'transient'> {
+ let mxRecords: MxRecord[]
+ try {
+ mxRecords = await this.resolver.resolveMx(domain)
+ } catch (error) {
+ const outcome = classifyDnsError(error)
+ if (outcome === 'transient') {
+ return 'transient'
+ }
+ // No MX record set → fall through to the A/AAAA implicit-MX check below.
+ mxRecords = []
+ }
+
+ if (mxRecords.length > 0) {
+ // RFC 7505 "null MX": a single `.`/empty exchange means the domain
+ // explicitly accepts no mail — a definitive block, no A/AAAA fallback.
+ const hasRealExchange = mxRecords.some((r) => r.exchange && r.exchange !== '.')
+ return hasRealExchange ? 'valid' : 'invalid'
+ }
+
+ // RFC 5321 implicit MX: no MX records means the A/AAAA record is the mail target.
+ const a = await this.tryResolve(() => this.resolver.resolve4(domain))
+ if (a === 'transient') {
+ return 'transient'
+ }
+ if (a === 'has') {
+ return 'valid'
+ }
+ const aaaa = await this.tryResolve(() => this.resolver.resolve6(domain))
+ if (aaaa === 'transient') {
+ return 'transient'
+ }
+ return aaaa === 'has' ? 'valid' : 'invalid'
+ }
+
+ private async tryResolve(fn: () => Promise<unknown[]>): Promise<ResolveOutcome> {
+ try {
+ const records = await fn()
+ return records.length > 0 ? 'has' : 'none'
+ } catch (error) {
+ return classifyDnsError(error)
+ }
+ }
+
+ private setLocal(domain: string, entry: CacheEntry): void {
+ // FIFO eviction via Map insertion order — cheap, and precision doesn't
+ // matter here: an evicted hot domain just costs one Valkey/DNS round trip.
+ if (!this.localCache.has(domain) && this.localCache.size >= MAX_LOCAL_CACHE_DOMAINS) {
+ const oldest = this.localCache.keys().next().value
+ if (oldest !== undefined) {
+ this.localCache.delete(oldest)
+ }
+ }
+ this.localCache.set(domain, entry)
+ }
+
+ private async readValkey(domain: string): Promise<boolean | null> {
+ if (!this.valkey) {
+ return null
+ }
+ // failOpen: a Valkey outage returns null (treated as a cache miss), never throws.
+ const value = await this.valkey.useClient({ name: 'email-mx-read', failOpen: true }, (client) =>
+ client.get(VALKEY_KEY_PREFIX + domain)
+ )
+ if (value === '1') {
+ return true
+ }
+ if (value === '0') {
+ return false
+ }
+ return null
+ }
+
+ private async writeValkey(domain: string, deliverable: boolean): Promise<void> {
+ if (!this.valkey) {
+ return
+ }
+ const ttlSeconds = Math.floor((deliverable ? POSITIVE_TTL_MS : NEGATIVE_TTL_MS) / 1000)
+ await this.valkey.useClient({ name: 'email-mx-write', failOpen: true }, (client) =>
+ client.set(VALKEY_KEY_PREFIX + domain, deliverable ? '1' : '0', 'EX', ttlSeconds)
+ )
+ }
+}
diff --git a/nodejs/src/cdp/services/rate-limiter/rate-limiter-valkey-pool.ts b/nodejs/src/cdp/services/rate-limiter/rate-limiter-valkey-pool.ts
index da6f1e9d4fe3..7e9eaed1011b 100644
--- a/nodejs/src/cdp/services/rate-limiter/rate-limiter-valkey-pool.ts
+++ b/nodejs/src/cdp/services/rate-limiter/rate-limiter-valkey-pool.ts
@@ -14,19 +14,22 @@ export type RateLimiterValkeyConfig = Pick<
Pick<CommonConfig, 'REDIS_POOL_MIN_SIZE' | 'REDIS_POOL_MAX_SIZE'>
/**
- * Creates a connection to the dedicated SES rate-limiter Valkey instance.
+ * Creates a connection to the dedicated SES Valkey instance, shared by the
+ * SES rate limiter and the email MX-validation cache (each caller gets its
+ * own pool via `name`).
*
- * Single writer pool — every operation in the rate limiter's Lua script is a
- * write (hset + expire), so there's no use for a read-only replica. Returns
- * null when the host is unset (local dev outside k8s); callers treat that as
- * "rate limiting disabled in this environment" and proceed without the gate.
+ * Single writer pool — the rate limiter's Lua script only writes (hset +
+ * expire) and the MX cache is low-volume, so there's no use for a read-only
+ * replica. Returns null when the host is unset (local dev outside k8s);
+ * callers treat that as "feature disabled in this environment" and proceed
+ * without it.
*/
export function createSesRateLimiterValkeyPool(
config: RateLimiterValkeyConfig,
name = 'ses-rate-limiter'
): RedisV2 | null {
if (!config.SES_RATE_LIMITER_VALKEY_HOST) {
- logger.info('🪙', `[${name}] no host configured — rate limiter disabled`)
+ logger.info('🪙', `[${name}] no SES Valkey host configured — feature disabled`)
return null
}
diff --git a/nodejs/src/cdp/types.ts b/nodejs/src/cdp/types.ts
index 02381dd89920..1daa137b8e9e 100644
--- a/nodejs/src/cdp/types.ts
+++ b/nodejs/src/cdp/types.ts
@@ -236,6 +236,7 @@ export type MinimalAppMetric = {
| 'email_opened'
| 'email_link_clicked'
| 'email_bounced'
+ | 'email_bounce_prevented'
| 'email_blocked'
| 'email_spam'
| 'email_unsubscribed'
diff --git a/nodejs/src/cdp/workflows-e2e.test.ts b/nodejs/src/cdp/workflows-e2e.test.ts
index 42d49e26453b..43edcaa06027 100644
--- a/nodejs/src/cdp/workflows-e2e.test.ts
+++ b/nodejs/src/cdp/workflows-e2e.test.ts
@@ -69,6 +69,22 @@ import { convertToHogFunctionFilterGlobal } from './utils/hog-function-filtering
const ActualKafkaProducerWrapper = jest.requireActual('~/common/kafka/producer').KafkaProducerWrapper
+// DNS is mocked (like fetch) because EmailValidationService's MX lookups are a real
+// network boundary: validation is fail-open, so a CI resolver hiccup would silently
+// turn a "skipped hard bounce" assertion into a sent email — a guaranteed flake.
+// Implementations are domain-aware and set in the email-queue block's beforeEach.
+const mockDnsResolveMx = jest.fn()
+const mockDnsResolve4 = jest.fn()
+const mockDnsResolve6 = jest.fn()
+
+jest.mock('node:dns/promises', () => ({
+ Resolver: jest.fn().mockImplementation(() => ({
+ resolveMx: mockDnsResolveMx,
+ resolve4: mockDnsResolve4,
+ resolve6: mockDnsResolve6,
+ })),
+}))
+
// Use the same env vars as config.ts (lines 221-229) so cleanup pools and hub target the same DBs
const CYCLOTRON_NODE_DB_URL =
process.env.CYCLOTRON_NODE_DATABASE_URL ?? 'postgres://posthog:posthog@localhost:5432/test_cyclotron_node'
@@ -1616,6 +1632,21 @@ describe('Workflows E2E (email queue)', () => {
// captured in `MessageAssetsService` at instantiation.
hub.MESSAGE_ASSETS_CAPTURE_ENABLED = true
+ // Enforce mode for the whole block: existing tests prove deliverable recipients
+ // pass validation untouched; the skip test proves dead domains never reach the queue.
+ hub.CDP_EMAIL_MX_VALIDATION_ENABLED = true
+ hub.CDP_EMAIL_MX_VALIDATION_ENFORCE_TEAMS = '*'
+
+ // `.invalid` domains are NXDOMAIN, everything else resolves as deliverable.
+ const nxdomain = () => Promise.reject(Object.assign(new Error('queryMx ENOTFOUND'), { code: 'ENOTFOUND' }))
+ mockDnsResolveMx.mockImplementation((domain: string) =>
+ domain.endsWith('.invalid') ? nxdomain() : Promise.resolve([{ exchange: 'mx.example.com', priority: 10 }])
+ )
+ mockDnsResolve4.mockImplementation((domain: string) =>
+ domain.endsWith('.invalid') ? nxdomain() : Promise.resolve(['1.2.3.4'])
+ )
+ mockDnsResolve6.mockImplementation(() => Promise.resolve([]))
+
kafkaProducer = await ActualKafkaProducerWrapper.create(hub.KAFKA_CLIENT_RACK)
mockProducerObserver = new KafkaProducerObserver(kafkaProducer)
@@ -1802,6 +1833,78 @@ describe('Workflows E2E (email queue)', () => {
}, 10000)
})
+ it('skips a predicted hard bounce before the email queue and completes the workflow', async () => {
+ // Locks down the pipeline sequencing the unit tests can't: the MX-validation
+ // skip happens on the hogflow worker BEFORE routeEmailToQueue, so a dead-domain
+ // recipient must produce no email_queued/email_sent, no billable_invocation,
+ // exactly one email_bounce_prevented, and a workflow that still runs to exit
+ // instead of wedging on the email queue.
+ 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: 'Predicted bounce',
+ text: 'Should never send',
+ html: '<p>Should never send</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)
+
+ const { backgroundTask } = await eventsConsumer.processBatch([createGlobals()])
+ await backgroundTask
+
+ 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)
+
+ // Wait for the two positive signals first — once the exit 'succeeded' metric
+ // has flushed, the absence of email metrics below is meaningful, since
+ // email_queued would have been emitted earlier in the pipeline.
+ expect(sumCounts((m) => m.value.metric_name === 'email_bounce_prevented')).toBe(1)
+ expect(sumCounts((m) => m.value.metric_name === 'succeeded' && m.value.instance_id === 'exit')).toBe(1)
+
+ expect(sumCounts((m) => m.value.metric_name === 'email_queued')).toBe(0)
+ expect(sumCounts((m) => m.value.metric_name === 'email_sent')).toBe(0)
+ expect(sumCounts((m) => m.value.metric_name === 'email_failed')).toBe(0)
+ expect(sumCounts((m) => m.value.metric_name === 'billable_invocation')).toBe(0)
+ }, 15000)
+
+ await waitForExpect(async () => {
+ const jobs = await queryCyclotronJobs()
+ expect(jobs.filter((j: any) => j.status === 'completed').length).toBeGreaterThanOrEqual(1)
+ expect(jobs.filter((j: any) => j.status === 'failed').length).toBe(0)
+ }, 10000)
+ })
+
it('does not emit duplicate Resuming / Executing / pause logs for the email-queue routing reschedule', async () => {
// Email steps reschedule themselves once to switch onto the dedicated email queue
// (see HogFunctionHandler.execute in actions/hog_function.ts). That second dequeue
diff --git a/nodejs/src/server.ts b/nodejs/src/server.ts
index 3d0a84421a00..0dfc398806c5 100644
--- a/nodejs/src/server.ts
+++ b/nodejs/src/server.ts
@@ -122,7 +122,10 @@ export class PluginServer implements NodeServer {
cdpQuotaServices = this.createCdpQuotaServices(teamManager)
}
- // Build typed deps objects for consumers
+ // Build typed deps objects for consumers. `emailValidationValkey` is null in
+ // the shared deps and set only by the cyclotron workers that run the hogflow
+ // email action (see `withEmailValidationValkey` at their loaders below) — no
+ // other consumer touches the SES Valkey.
const cdpDeps: CdpConsumerBaseDeps | undefined = needsCdp
? {
postgres: this.postgres!,
@@ -136,6 +139,7 @@ export class PluginServer implements NodeServer {
geoipService: cdpServices!.geoipService,
groupRepository: cdpServices!.groupRepository,
quotaLimiting: cdpQuotaServices!.quotaLimiting,
+ emailValidationValkey: null,
}
: undefined
@@ -266,7 +270,11 @@ export class PluginServer implements NodeServer {
// 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)
+ const worker = new CdpCyclotronWorkerHogFlow(
+ this.config,
+ this.withEmailValidationValkey(cdpDeps!),
+ queue
+ )
await worker.start()
return worker.service
})
@@ -287,7 +295,11 @@ export class PluginServer implements NodeServer {
if (capabilities.cdpCyclotronWorkerHogFlowLegacyPg) {
serviceLoaders.push(async () => {
const legacyQueue = new CyclotronJobQueuePostgres(this.config.CONSUMER_BATCH_SIZE, this.config)
- const worker = new CdpCyclotronWorkerHogFlow(this.config, cdpDeps!, legacyQueue)
+ const worker = new CdpCyclotronWorkerHogFlow(
+ this.config,
+ this.withEmailValidationValkey(cdpDeps!),
+ legacyQueue
+ )
await worker.start()
return worker.service
})
@@ -298,7 +310,11 @@ export class PluginServer implements NodeServer {
if (capabilities.cdpCyclotronWorkerEmailLegacyPg) {
serviceLoaders.push(async () => {
const legacyQueue = new CyclotronJobQueuePostgres(this.config.CONSUMER_BATCH_SIZE, this.config)
- const worker = new CdpCyclotronWorkerEmail(this.config, cdpDeps!, legacyQueue)
+ const worker = new CdpCyclotronWorkerEmail(
+ this.config,
+ this.withEmailValidationValkey(cdpDeps!),
+ legacyQueue
+ )
await worker.start()
return worker.service
})
@@ -325,7 +341,7 @@ export class PluginServer implements NodeServer {
throttledPollDelayMs: this.config.CDP_SES_RATE_LIMIT_THROTTLED_POLL_DELAY_MS,
})
: new CyclotronJobQueuePostgresV2(this.config.CONSUMER_BATCH_SIZE, this.config)
- const worker = new CdpCyclotronWorkerEmail(this.config, cdpDeps!, queue)
+ const worker = new CdpCyclotronWorkerEmail(this.config, this.withEmailValidationValkey(cdpDeps!), queue)
await worker.start()
return worker.service
})
@@ -404,6 +420,21 @@ export class PluginServer implements NodeServer {
this.lifecycle.services.push(...readyServices)
}
+ /**
+ * Grants the SES Valkey pool that backs the shared MX-verdict cache to a worker's
+ * deps. Only the cyclotron workers that run the hogflow email action call this, so
+ * the pool is never opened on other CDP consumers or cdp-api — an idle Valkey sized
+ * for the SES rate limiter shouldn't hold connections from pods that never validate.
+ * Null (the shared-deps default) when the kill switch is off, in which case
+ * EmailValidationService degrades to its local cache + DNS.
+ */
+ private withEmailValidationValkey(deps: CdpConsumerBaseDeps): CdpConsumerBaseDeps {
+ if (!this.config.CDP_EMAIL_MX_VALIDATION_ENABLED) {
+ return deps
+ }
+ return { ...deps, emailValidationValkey: createSesRateLimiterValkeyPool(this.config, 'email-mx-validation') }
+ }
+
private getCleanupResources(): CleanupResources {
return {
kafkaProducers: [],
diff --git a/nodejs/tests/helpers/cdp.ts b/nodejs/tests/helpers/cdp.ts
index bca9e473af39..eca99e5fb86f 100644
--- a/nodejs/tests/helpers/cdp.ts
+++ b/nodejs/tests/helpers/cdp.ts
@@ -13,6 +13,7 @@ import {
WARPSTREAM_CYCLOTRON_PRODUCER,
WARPSTREAM_INGESTION_PRODUCER,
} from '../../src/cdp/outputs/producers'
+import { createSesRateLimiterValkeyPool } from '../../src/cdp/services/rate-limiter/rate-limiter-valkey-pool'
import { InternalCaptureService } from '../../src/common/services/internal-capture'
import { Hub } from '../../src/types'
@@ -63,5 +64,8 @@ export function createCdpConsumerDeps(hub: Hub, kafkaProducer?: KafkaProducerWra
geoipService: hub.geoipService,
groupRepository: noopGroupReadRepository,
quotaLimiting: hub.quotaLimiting,
+ emailValidationValkey: hub.CDP_EMAIL_MX_VALIDATION_ENABLED
+ ? createSesRateLimiterValkeyPool(hub, 'email-mx-validation')
+ : null,
}
}