Skip to content

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

feat(cdp-email): gate dequeue behind SES rate-limit valkey bucket (#63480)

Meikel Ratz4014a34cd1d5
diff --git a/nodejs/src/cdp/config.ts b/nodejs/src/cdp/config.ts
index 8f7897281f38..a93b1e5aebc9 100644
--- a/nodejs/src/cdp/config.ts
+++ b/nodejs/src/cdp/config.ts
@@ -86,6 +86,15 @@ export type CdpConfig = ClickhouseConfig & {
// AWS ElastiCache Valkey Serverless requires TLS; toggle off only for local non-TLS test setups.
CDP_VALKEY_TLS: boolean
+ SES_RATE_LIMITER_VALKEY_HOST: string
+ SES_RATE_LIMITER_VALKEY_PORT: number
+ SES_RATE_LIMITER_VALKEY_PASSWORD: string
+ SES_RATE_LIMITER_VALKEY_TLS: boolean
+
+ CDP_SES_RATE_LIMIT_REFILL_PER_SECOND: number
+ CDP_SES_RATE_LIMIT_CAPACITY: number
+ CDP_SES_RATE_LIMIT_THROTTLED_POLL_DELAY_MS: number
+
CDP_EVENT_PROCESSOR_EXECUTE_FIRST_STEP: boolean
CDP_GOOGLE_ADWORDS_DEVELOPER_TOKEN: string
CDP_FETCH_RETRIES: number
@@ -196,6 +205,15 @@ export function getDefaultCdpConfig(): CdpConfig {
CDP_VALKEY_DUAL_ENABLED: false,
CDP_VALKEY_TLS: false,
+ SES_RATE_LIMITER_VALKEY_HOST: '',
+ SES_RATE_LIMITER_VALKEY_PORT: 6379,
+ SES_RATE_LIMITER_VALKEY_PASSWORD: '',
+ SES_RATE_LIMITER_VALKEY_TLS: false,
+
+ CDP_SES_RATE_LIMIT_REFILL_PER_SECOND: 100,
+ CDP_SES_RATE_LIMIT_CAPACITY: 50,
+ CDP_SES_RATE_LIMIT_THROTTLED_POLL_DELAY_MS: 250,
+
CDP_EVENT_PROCESSOR_EXECUTE_FIRST_STEP: true,
CDP_GOOGLE_ADWORDS_DEVELOPER_TOKEN: '',
CDP_FETCH_RETRIES: 3,
diff --git a/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.ts b/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.ts
index 68ed9025366b..938e052c5b47 100644
--- a/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.ts
+++ b/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.ts
@@ -3,8 +3,9 @@ import { v7 as uuidv7 } from 'uuid'
import { CyclotronV2Janitor } from './janitor'
import { CyclotronV2Manager } from './manager'
-import { CyclotronV2DequeuedJob, CyclotronV2JobInit } from './types'
+import { CyclotronV2BatchLimit, CyclotronV2DequeuedJob, CyclotronV2JobInit } from './types'
import { CyclotronV2Worker } from './worker'
+import { CyclotronV2RateLimitedWorker } from './worker-rate-limited'
const DB_URL = 'postgres://posthog:posthog@localhost:5432/test_cyclotron_node'
const QUEUE = 'test-queue'
@@ -488,6 +489,125 @@ describe('Cyclotron V2', () => {
expect(jobs[0].queueName).toBe(QUEUE)
})
+ describe('CyclotronV2RateLimitedWorker', () => {
+ // The hook is consulted on every poll. Returning a positive limit
+ // clamps the SQL LIMIT to min(limit, batchMaxSize); 0 skips the
+ // dequeue and sleeps; undefined falls back to batchMaxSize.
+ const createRateLimitedWorker = (
+ getBatchLimit: () => Promise<CyclotronV2BatchLimit | undefined>,
+ overrides?: Record<string, unknown>
+ ): CyclotronV2RateLimitedWorker =>
+ new CyclotronV2RateLimitedWorker(
+ {
+ pool: { dbUrl: DB_URL },
+ queueName: QUEUE,
+ batchMaxSize: 100,
+ pollDelayMs: 10,
+ includeEmptyBatches: true,
+ ...overrides,
+ },
+ getBatchLimit
+ )
+
+ it('clamps the batch to the granted limit', async () => {
+ for (let i = 0; i < 10; i++) {
+ await manager.createJob({ teamId: 1, queueName: QUEUE })
+ }
+
+ // eslint-disable-next-line @typescript-eslint/require-await
+ const worker = createRateLimitedWorker(async () => ({ limit: 3 }))
+ const jobs = await dequeueOneBatch(worker)
+
+ expect(jobs).toHaveLength(3)
+ expect(await countByStatus('available')).toBe(7)
+ })
+
+ it('skips the dequeue entirely when the granted limit is 0', async () => {
+ await manager.createJob({ teamId: 1, queueName: QUEUE })
+ await manager.createJob({ teamId: 1, queueName: QUEUE })
+
+ // eslint-disable-next-line @typescript-eslint/require-await
+ const worker = createRateLimitedWorker(async () => ({ limit: 0, sleepMs: 5 }), {
+ includeEmptyBatches: false,
+ })
+ const jobs = await dequeueOneBatch(worker, 200)
+
+ expect(jobs).toHaveLength(0)
+ // Critical: the SQL UPDATE never fires — rows stay 'available'.
+ expect(await countByStatus('available')).toBe(2)
+ expect(await countByStatus('running')).toBe(0)
+ })
+
+ it('falls back to batchMaxSize when the hook returns undefined', async () => {
+ for (let i = 0; i < 5; i++) {
+ await manager.createJob({ teamId: 1, queueName: QUEUE })
+ }
+
+ // eslint-disable-next-line @typescript-eslint/require-await
+ const worker = createRateLimitedWorker(async () => undefined)
+ const jobs = await dequeueOneBatch(worker)
+
+ expect(jobs).toHaveLength(5)
+ })
+
+ it('exits promptly when stopConsuming is called during a throttled sleep', async () => {
+ // eslint-disable-next-line @typescript-eslint/require-await
+ const worker = createRateLimitedWorker(async () => ({ limit: 0, sleepMs: 100 }))
+
+ await worker.connect(async () => {})
+ // Let the loop reach the sleep branch.
+ await new Promise((resolve) => setTimeout(resolve, 50))
+
+ const stopStarted = Date.now()
+ await worker.stopConsuming()
+ const stopDuration = Date.now() - stopStarted
+
+ // At most one sleepMs (100ms) + small overhead — never indefinite.
+ expect(stopDuration).toBeLessThan(300)
+ })
+
+ it('keeps looping after the hook rejects', async () => {
+ await manager.createJob({ teamId: 1, queueName: QUEUE })
+ await manager.createJob({ teamId: 1, queueName: QUEUE })
+
+ // Reject once, then return a valid decision so dequeueOneBatch
+ // captures a non-empty batch and resolves.
+ let calls = 0
+ const worker = createRateLimitedWorker(() => {
+ calls += 1
+ if (calls === 1) {
+ return Promise.reject(new Error('boom'))
+ }
+ return Promise.resolve({ limit: 5 })
+ })
+
+ const jobs = await dequeueOneBatch(worker, 1000)
+ expect(jobs).toHaveLength(2)
+ // The first call rejected — the loop's catch swallowed it and tried again.
+ expect(calls).toBeGreaterThan(1)
+ })
+
+ it('skips the limiter entirely when there is no work to dequeue', async () => {
+ // Idle queue → peek returns no rows → worker sleeps without
+ // ever consulting the rate limiter. Keeps the bucket at
+ // capacity and the limiter's metrics silent during idle.
+ let hookCalls = 0
+ const worker = createRateLimitedWorker(() => {
+ hookCalls += 1
+ return Promise.resolve({ limit: 5 })
+ })
+
+ await worker.connect(async () => {})
+ // Let the loop poll several times (pollDelayMs is 10ms in tests).
+ await new Promise((resolve) => setTimeout(resolve, 200))
+ await worker.stopConsuming()
+
+ // Many poll cycles ran (~20 at 10ms cadence) but no jobs exist,
+ // so the limiter hook is never invoked.
+ expect(hookCalls).toBe(0)
+ })
+ })
+
it.each([
['ack', 'completed'],
['fail', 'failed'],
diff --git a/nodejs/src/cdp/services/cyclotron-v2/index.ts b/nodejs/src/cdp/services/cyclotron-v2/index.ts
index 7ad53231dee0..eccf0666cbd5 100644
--- a/nodejs/src/cdp/services/cyclotron-v2/index.ts
+++ b/nodejs/src/cdp/services/cyclotron-v2/index.ts
@@ -1,5 +1,6 @@
export { CyclotronV2Manager, CyclotronJobConflictError } from './manager'
export { CyclotronV2Worker } from './worker'
+export { CyclotronV2RateLimitedWorker } from './worker-rate-limited'
export { CyclotronV2Janitor } from './janitor'
export { CyclotronV2JanitorService } from './janitor-service'
export type {
@@ -11,4 +12,5 @@ export type {
CyclotronV2WorkerConfig,
CyclotronV2JanitorConfig,
CyclotronV2CleanupResult,
+ CyclotronV2BatchLimit,
} from './types'
diff --git a/nodejs/src/cdp/services/cyclotron-v2/types.ts b/nodejs/src/cdp/services/cyclotron-v2/types.ts
index 1832febe45d7..c2a2642579e4 100644
--- a/nodejs/src/cdp/services/cyclotron-v2/types.ts
+++ b/nodejs/src/cdp/services/cyclotron-v2/types.ts
@@ -70,6 +70,14 @@ export type CyclotronV2ManagerConfig = {
depthCheckIntervalMs?: number
}
+/**
+ * Per-poll decision returned by a rate-limited worker's hook.
+ * `{ limit: 0, sleepMs }` → skip the dequeue and sleep.
+ * `{ limit: N }` → dequeue up to `min(N, batchMaxSize)` rows.
+ * `undefined` → fall back to the static `batchMaxSize`.
+ */
+export type CyclotronV2BatchLimit = { limit: number; sleepMs?: number }
+
export type CyclotronV2WorkerConfig = {
pool: CyclotronV2PoolConfig
queueName: string
diff --git a/nodejs/src/cdp/services/cyclotron-v2/worker-rate-limited.ts b/nodejs/src/cdp/services/cyclotron-v2/worker-rate-limited.ts
new file mode 100644
index 000000000000..78f33f967d45
--- /dev/null
+++ b/nodejs/src/cdp/services/cyclotron-v2/worker-rate-limited.ts
@@ -0,0 +1,68 @@
+import { logger } from '../../../utils/logger'
+import { CyclotronV2BatchLimit, CyclotronV2WorkerConfig } from './types'
+import { CyclotronV2DequeuedJob } from './types'
+import { CyclotronV2Worker, sleep } from './worker'
+
+/**
+ * Variant of CyclotronV2Worker that consults a per-poll rate-limit hook before
+ * dequeuing. Returning `{ limit: 0 }` skips the SQL entirely and sleeps;
+ * returning `{ limit: N }` clamps the dequeue batch to `min(N, batchMaxSize)`.
+ *
+ * Used by the email worker to gate SES sends behind a Valkey-backed token
+ * bucket. Other consumers run the plain `CyclotronV2Worker` with no rate-limit
+ * code in their poll loop.
+ */
+export class CyclotronV2RateLimitedWorker extends CyclotronV2Worker {
+ constructor(
+ config: CyclotronV2WorkerConfig,
+ private readonly getBatchLimit: () => Promise<CyclotronV2BatchLimit | undefined>
+ ) {
+ super(config)
+ }
+
+ protected override async runConsumerLoop(
+ processBatch: (jobs: CyclotronV2DequeuedJob[]) => Promise<void>
+ ): Promise<void> {
+ while (this.isConsuming) {
+ try {
+ this.lastPollTime = new Date()
+
+ // Cheap pre-check: only claim tokens if there's actual work to
+ // dequeue. Skipping this on idle polls keeps the bucket at
+ // capacity (preserves burst), and keeps the limiter's metrics
+ // silent when there's nothing to send. The SELECT hits the
+ // same partial index as dequeueJobs — strictly cheaper than the
+ // UPDATE ... SKIP LOCKED we'd otherwise have run.
+ if (!(await this.hasWork())) {
+ await sleep(this.pollDelayMs)
+ continue
+ }
+
+ const decision = await this.getBatchLimit()
+ // === 0 (not <=) so a future bug returning a negative limit
+ // surfaces as a SQL LIMIT error instead of silently sleeping.
+ if (decision && decision.limit === 0) {
+ await sleep(decision.sleepMs ?? this.pollDelayMs)
+ continue
+ }
+ const effectiveLimit = decision ? Math.min(decision.limit, this.batchMaxSize) : this.batchMaxSize
+
+ const rows = await this.dequeueJobs(effectiveLimit)
+
+ if (rows.length === 0) {
+ if (this.includeEmptyBatches) {
+ await processBatch([])
+ }
+ await sleep(this.pollDelayMs)
+ continue
+ }
+
+ const jobs = rows.map((row) => this.wrapJob(row))
+ await processBatch(jobs)
+ } catch (err) {
+ logger.error('CyclotronV2RateLimitedWorker consumer loop error', { error: String(err) })
+ await sleep(this.pollDelayMs)
+ }
+ }
+ }
+}
diff --git a/nodejs/src/cdp/services/cyclotron-v2/worker.ts b/nodejs/src/cdp/services/cyclotron-v2/worker.ts
index 17c93412dd0c..2e834f3d9f32 100644
--- a/nodejs/src/cdp/services/cyclotron-v2/worker.ts
+++ b/nodejs/src/cdp/services/cyclotron-v2/worker.ts
@@ -10,7 +10,7 @@ import {
CyclotronV2WorkerConfig,
} from './types'
-interface RawJobRow {
+export interface RawJobRow {
id: string
team_id: number
function_id: string | null
@@ -27,20 +27,20 @@ interface RawJobRow {
lock_id: string
}
-function sleep(ms: number): Promise<void> {
+export function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms))
}
export class CyclotronV2Worker {
private pool: Pool
- private isConsuming = false
- private lastPollTime = new Date()
+ protected isConsuming = false
+ protected lastPollTime = new Date()
private consumerLoopPromise: Promise<void> | null = null
- private readonly batchMaxSize: number
- private readonly pollDelayMs: number
+ protected readonly batchMaxSize: number
+ protected readonly pollDelayMs: number
private readonly heartbeatTimeoutMs: number
- private readonly includeEmptyBatches: boolean
+ protected readonly includeEmptyBatches: boolean
constructor(private config: CyclotronV2WorkerConfig) {
this.pool = new Pool({
@@ -62,7 +62,7 @@ export class CyclotronV2Worker {
this.consumerLoopPromise = this.runConsumerLoop(processBatch)
}
- private async runConsumerLoop(processBatch: (jobs: CyclotronV2DequeuedJob[]) => Promise<void>): Promise<void> {
+ protected async runConsumerLoop(processBatch: (jobs: CyclotronV2DequeuedJob[]) => Promise<void>): Promise<void> {
while (this.isConsuming) {
try {
this.lastPollTime = new Date()
@@ -85,7 +85,29 @@ export class CyclotronV2Worker {
}
}
- private async dequeueJobs(): Promise<RawJobRow[]> {
+ /**
+ * Cheap pre-check that returns true iff any job is currently dequeueable
+ * from this worker's queue. Used by rate-limited subclasses to skip the
+ * token-bucket claim entirely on idle polls, so the limiter stays silent
+ * when there's nothing to send.
+ *
+ * Hits the same partial index as `dequeueJobs` (`idx_cyclotron_jobs_dequeue`,
+ * filtered on `status = 'available'`), so the query is sub-millisecond and
+ * strictly cheaper than the `UPDATE ... SKIP LOCKED` we'd otherwise run.
+ */
+ protected async hasWork(): Promise<boolean> {
+ const result = await this.pool.query(
+ `SELECT 1 FROM cyclotron_jobs
+ WHERE status = 'available'
+ AND queue_name = $1
+ AND scheduled <= NOW()
+ LIMIT 1`,
+ [this.config.queueName]
+ )
+ return result.rowCount !== null && result.rowCount > 0
+ }
+
+ protected async dequeueJobs(limit: number = this.batchMaxSize): Promise<RawJobRow[]> {
const lockId = uuidv7()
const result = await this.pool.query<RawJobRow>(
`WITH available AS (
@@ -121,7 +143,7 @@ export class CyclotronV2Worker {
cyclotron_jobs.person_id,
cyclotron_jobs.action_id,
cyclotron_jobs.lock_id`,
- [this.config.queueName, this.batchMaxSize, lockId]
+ [this.config.queueName, limit, lockId]
)
// UPDATE...RETURNING doesn't preserve the CTE's ORDER BY,
// so re-sort to maintain priority ordering within the batch
@@ -131,7 +153,7 @@ export class CyclotronV2Worker {
)
}
- private wrapJob(row: RawJobRow): CyclotronV2DequeuedJob {
+ protected wrapJob(row: RawJobRow): CyclotronV2DequeuedJob {
const pool = this.pool
const lockId = row.lock_id
let released = false
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 ce8913a651af..fbd592eaf7f4 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
@@ -9,6 +9,7 @@ import { logger } from '../../../utils/logger'
import { CdpConfig } from '../../config'
import { CyclotronJobInvocation, CyclotronJobInvocationResult, CyclotronJobQueueKind } from '../../types'
import { CyclotronV2DequeuedJob, CyclotronV2JobInit, CyclotronV2Manager, CyclotronV2Worker } from '../cyclotron-v2'
+import { CyclotronV2WorkerConfig } from '../cyclotron-v2/types'
import { JobQueue } from './job-queue.interface'
import { cdpJobSizeCompressedKb, cdpJobSizeKb, createInvocationSanitizer, observeConsumedBatch } from './shared'
@@ -34,7 +35,10 @@ export class CyclotronJobQueuePostgresV2 implements JobQueue {
private sanitizer: ReturnType<typeof createInvocationSanitizer>
constructor(
- private consumerBatchSize: number,
+ // protected — the rate-limited subclass needs this to cap its token
+ // claim at the actual batch size we can process (avoids deducting
+ // tokens we'd never use).
+ protected consumerBatchSize: number,
private config: Pick<
CdpConfig,
| 'CYCLOTRON_NODE_DATABASE_URL'
@@ -63,6 +67,15 @@ export class CyclotronJobQueuePostgresV2 implements JobQueue {
await this.manager.connect()
}
+ /**
+ * Factory hook for the worker. Subclasses override this to plug in a
+ * different worker class (e.g. CyclotronV2RateLimitedWorker) without
+ * having to reimplement `startAsConsumer`.
+ */
+ protected createWorker(workerConfig: CyclotronV2WorkerConfig): CyclotronV2Worker {
+ return new CyclotronV2Worker(workerConfig)
+ }
+
public async startAsConsumer(
queue: CyclotronJobQueueKind,
consumeBatch: (invocations: CyclotronJobInvocation[]) => Promise<{ backgroundTask: Promise<any> }>
@@ -73,7 +86,7 @@ export class CyclotronJobQueuePostgresV2 implements JobQueue {
await this.startAsProducer()
- this.worker = new CyclotronV2Worker({
+ this.worker = this.createWorker({
pool: { dbUrl: this.config.CYCLOTRON_NODE_DATABASE_URL },
queueName: queue,
batchMaxSize: this.consumerBatchSize,
diff --git a/nodejs/src/cdp/services/job-queue/job-queue-rate-limited-postgres-v2.ts b/nodejs/src/cdp/services/job-queue/job-queue-rate-limited-postgres-v2.ts
new file mode 100644
index 000000000000..4ae6545aa615
--- /dev/null
+++ b/nodejs/src/cdp/services/job-queue/job-queue-rate-limited-postgres-v2.ts
@@ -0,0 +1,77 @@
+import { CyclotronJobInvocation, CyclotronJobQueueKind } from '../../types'
+import { CyclotronV2BatchLimit, CyclotronV2RateLimitedWorker, CyclotronV2Worker } from '../cyclotron-v2'
+import { CyclotronV2WorkerConfig } from '../cyclotron-v2/types'
+import { RateLimiterService } from '../rate-limiter/rate-limiter.service'
+import { CyclotronJobQueuePostgresV2 } from './job-queue-postgres-v2'
+
+export interface RateLimitedQueueOptions {
+ limiter: RateLimiterService
+ /** Token-bucket key, e.g. `@posthog/ses/global`. */
+ key: string
+ /** Bucket capacity (burst size). */
+ capacity: number
+ /** Tokens added per second. */
+ refillPerSecond: number
+ /** How long to sleep when the bucket is empty before re-checking. */
+ throttledPollDelayMs: number
+}
+
+/**
+ * Postgres-V2 job queue variant that gates dequeue behind a distributed token
+ * bucket. Used by the email worker to claim SES capacity before pulling jobs.
+ *
+ * The base queue and `CyclotronV2Worker` are completely untouched — other
+ * consumers (hog, hogflow, etc.) construct the base queue and never load the
+ * rate-limit code path.
+ */
+export class CyclotronJobQueueRateLimitedPostgresV2 extends CyclotronJobQueuePostgresV2 {
+ constructor(
+ consumerBatchSize: number,
+ config: ConstructorParameters<typeof CyclotronJobQueuePostgresV2>[1],
+ private rateLimit: RateLimitedQueueOptions
+ ) {
+ super(consumerBatchSize, config)
+ }
+
+ public override async startAsConsumer(
+ queue: CyclotronJobQueueKind,
+ consumeBatch: (invocations: CyclotronJobInvocation[]) => Promise<{ backgroundTask: Promise<any> }>
+ ): Promise<void> {
+ // Fail-closed on startup: unreachable Valkey throws and lets k8s
+ // restart the pod. Sending without the gate would risk SES reputation
+ // damage, so we don't start the consumer until the limiter is healthy.
+ await this.rateLimit.limiter.ping()
+
+ await super.startAsConsumer(queue, consumeBatch)
+ }
+
+ protected override createWorker(workerConfig: CyclotronV2WorkerConfig): CyclotronV2Worker {
+ return new CyclotronV2RateLimitedWorker(workerConfig, () => this.claimBatchLimit())
+ }
+
+ /**
+ * Claim outbound capacity from the bucket before each poll. Returns the
+ * decision the worker applies: how many rows to dequeue, or "skip and
+ * sleep" when nothing is available. Runtime Valkey errors return 0 granted
+ * (fail-closed mid-shift) — the worker sleeps and retries.
+ *
+ * We cap `requested` at `consumerBatchSize` because tokens granted above
+ * that ceiling would be deducted from the Valkey bucket but never used —
+ * `effectiveLimit` in the worker is `min(decision.limit, batchMaxSize)`.
+ * Without the cap, an operator misconfiguration setting capacity > batch
+ * size would silently waste SES budget.
+ */
+ private async claimBatchLimit(): Promise<CyclotronV2BatchLimit | undefined> {
+ const requested = Math.min(this.rateLimit.capacity, this.consumerBatchSize)
+ const granted = await this.rateLimit.limiter.claimUpTo({
+ key: this.rateLimit.key,
+ requested,
+ capacity: this.rateLimit.capacity,
+ refillPerSecond: this.rateLimit.refillPerSecond,
+ })
+ if (granted === 0) {
+ return { limit: 0, sleepMs: this.rateLimit.throttledPollDelayMs }
+ }
+ return { limit: granted }
+ }
+}
diff --git a/nodejs/src/cdp/services/messaging/email.service.test.ts b/nodejs/src/cdp/services/messaging/email.service.test.ts
index d04b6f3de22c..a27d39737434 100644
--- a/nodejs/src/cdp/services/messaging/email.service.test.ts
+++ b/nodejs/src/cdp/services/messaging/email.service.test.ts
@@ -1,5 +1,7 @@
import { mockFetch } from '~/tests/helpers/mocks/request.mock'
+import { MessageRejected, SendingPausedException, TooManyRequestsException } from '@aws-sdk/client-sesv2'
+
import { createExampleInvocation, insertIntegration } from '~/cdp/_tests/fixtures'
import { CyclotronJobInvocationHogFunction } from '~/cdp/types'
import { CyclotronInvocationQueueParametersEmailType } from '~/schema/cyclotron'
@@ -11,6 +13,13 @@ import { Hub, Team } from '../../../types'
import { EmailService, parseAddressList, sanitizeEmailSubject } from './email.service'
import { MailDevAPI } from './helpers/maildev'
+class ThrottlingException extends Error {
+ constructor(message: string) {
+ super(message)
+ this.name = 'ThrottlingException'
+ }
+}
+
describe('sanitizeEmailSubject', () => {
it.each([
['passes through normal text', 'Hello World', 'Hello World'],
@@ -245,6 +254,73 @@ describe('EmailService', () => {
})
})
})
+ describe('SES throttle handling', () => {
+ // SES throttle responses become reschedule-with-backoff rather than
+ // permanent failures. The local Valkey bucket already gates dequeue;
+ // this path is the safety net for when SES disagrees with our estimate.
+ // Retryable: TooManyRequestsException (SES v2's rate-limit class) and
+ // ThrottlingException (generic AWS SDK throttle name surfaced from
+ // the transport layer). SendingPausedException is *not* retryable —
+ // it signals a reputation/account-state issue that needs operator
+ // attention, not a 500ms reschedule.
+ const throttleCases: Array<[string, () => Error]> = [
+ [
+ 'TooManyRequestsException',
+ () => new TooManyRequestsException({ $metadata: {}, message: 'Too many requests' }),
+ ],
+ ['ThrottlingException', () => new ThrottlingException('Rate exceeded')],
+ ]
+ it.each(throttleCases)('reschedules instead of failing when SES returns %s', async (_name, makeError) => {
+ sendEmailSpy.mockRejectedValueOnce(makeError())
+
+ const before = Date.now()
+ const result = await service.executeSendEmail(invocation)
+
+ expect(result.error).toBeUndefined()
+ expect(result.finished).toBe(false)
+ expect(result.invocation.queueScheduledAt).toBeDefined()
+ const scheduledMs = result.invocation.queueScheduledAt!.toMillis()
+ // Jittered 500–1000ms retry: must land in the future but never further
+ // than the upper bound + scheduler overhead.
+ expect(scheduledMs).toBeGreaterThanOrEqual(before + 400)
+ expect(scheduledMs).toBeLessThan(before + 2000)
+ // No business metric emitted on throttle — the eventual retry
+ // will produce email_sent.
+ expect(result.metrics ?? []).toEqual([])
+ })
+
+ it('hard-fails (not retry) when SES returns SendingPausedException', async () => {
+ // Reputation/account-state pause won't recover in 500ms; retrying
+ // just burns reschedules. Hard-fail so the failure surfaces via
+ // email_failed and an operator can investigate.
+ sendEmailSpy.mockRejectedValueOnce(
+ new SendingPausedException({ $metadata: {}, message: 'Sending paused' })
+ )
+
+ const result = await service.executeSendEmail(invocation)
+
+ expect(result.finished).toBe(true)
+ expect(result.error).toMatch(/Failed to send email via SES: Sending paused/)
+ expect(result.metrics).toEqual(
+ expect.arrayContaining([expect.objectContaining({ metric_name: 'email_failed' })])
+ )
+ })
+
+ it('still fails the job for non-throttle SES errors', async () => {
+ sendEmailSpy.mockRejectedValueOnce(
+ new MessageRejected({ $metadata: {}, message: 'something else broke' })
+ )
+
+ const result = await service.executeSendEmail(invocation)
+
+ expect(result.finished).toBe(true)
+ expect(result.error).toMatch(/Failed to send email via SES: something else broke/)
+ // Business metric should record the failure.
+ expect(result.metrics).toEqual(
+ expect.arrayContaining([expect.objectContaining({ metric_name: 'email_failed' })])
+ )
+ })
+ })
})
describe('native email sending with maildev', () => {
let invocation: CyclotronJobInvocationHogFunction
diff --git a/nodejs/src/cdp/services/messaging/email.service.ts b/nodejs/src/cdp/services/messaging/email.service.ts
index ca81fdc149eb..5bcfee0f6fe1 100644
--- a/nodejs/src/cdp/services/messaging/email.service.ts
+++ b/nodejs/src/cdp/services/messaging/email.service.ts
@@ -1,5 +1,7 @@
import { MessageHeader, SESv2Client, SendEmailCommand, SendEmailCommandInput } from '@aws-sdk/client-sesv2'
+import { DateTime } from 'luxon'
import { SendMailOptions } from 'nodemailer'
+import { Counter } from 'prom-client'
import { CyclotronJobInvocationHogFunction, CyclotronJobInvocationResult, IntegrationType } from '~/cdp/types'
import { createAddLogFunction, logEntry } from '~/cdp/utils'
@@ -18,6 +20,57 @@ import {
} from './helpers/tracking-code'
import { RecipientTokensService } from './recipient-tokens.service'
+const sesThrottleResponsesTotal = new Counter({
+ name: 'cdp_ses_throttle_responses_total',
+ help: 'SES API responses classified as throttle/rate-limit. Sustained nonzero rate means the local bucket is set too high vs. the SES quota.',
+ labelNames: ['error_code'],
+})
+
+/**
+ * SES error codes that signal a transient rate-limit shape — safe to retry
+ * shortly after. `TooManyRequestsException` is the SES-v2-specific class;
+ * `ThrottlingException` is a generic AWS SDK error code that can surface
+ * from the underlying transport layer for the same condition (not exported
+ * as a class for sesv2, so we match by `name`).
+ *
+ * `SendingPausedException` is *not* on this list — it signals a reputation
+ * or account-state problem that won't recover in seconds. Retrying within
+ * 500ms just burns reschedules; the job hard-fails instead, surfaces via
+ * `email_failed`, and the underlying SES config needs operator attention.
+ */
+const SES_THROTTLE_ERROR_NAMES = ['TooManyRequestsException', 'ThrottlingException'] as const
+type SesThrottleErrorName = (typeof SES_THROTTLE_ERROR_NAMES)[number]
+
+function isSesThrottleError(error: unknown): error is Error & { name: SesThrottleErrorName } {
+ return error instanceof Error && (SES_THROTTLE_ERROR_NAMES as readonly string[]).includes(error.name)
+}
+
+/**
+ * Tagged error signalling that SES rejected the send for a transient,
+ * rate-limit-shaped reason. The caller schedules a retry instead of failing
+ * the job. Carries the SES error name for metrics and the retry delay we
+ * pick locally (SES doesn't return a Retry-After header).
+ */
+export class SESThrottleError extends Error {
+ public readonly errorCode: SesThrottleErrorName
+ public readonly retryAfterMs: number
+
+ constructor(errorCode: SesThrottleErrorName, retryAfterMs: number, message: string) {
+ super(message)
+ this.name = 'SESThrottleError'
+ this.errorCode = errorCode
+ this.retryAfterMs = retryAfterMs
+ }
+}
+
+function pickThrottleRetryDelayMs(): number {
+ // Constant 500–1000ms jitter is plenty: the local Valkey bucket already
+ // gates re-dequeue at the configured refill rate, so a quick retry will
+ // simply re-claim a token if SES capacity has refreshed. Exponential
+ // backoff isn't needed at this layer.
+ return 500 + Math.floor(Math.random() * 500)
+}
+
export interface EmailServiceConfig {
sesAccessKeyId: string
sesSecretAccessKey: string
@@ -90,6 +143,7 @@ export class EmailService {
const integration = await this.integrationManager.get(params.from.integrationId)
let success: boolean = false
+ let throttled: boolean = false
try {
// Wrong-team references deliberately read as not-found so an ID's existence on another team can't be probed
@@ -121,9 +175,27 @@ export class EmailService {
addLog('info', `Email sent to ${params.to.email}`)
success = true
} catch (error) {
- addLog('error', error.message)
- result.error = error.message
- result.finished = true
+ if (error instanceof SESThrottleError) {
+ // Treat as a transient delivery delay — reschedule rather than fail
+ // the job. Our local bucket is the primary throttle; this path
+ // catches the cases where SES disagrees with our estimate.
+ throttled = true
+ result.finished = false
+ result.invocation.queueScheduledAt = DateTime.utc().plus({ milliseconds: error.retryAfterMs })
+ addLog('warn', `SES rate-limited (${error.errorCode}); rescheduling email in ${error.retryAfterMs}ms`)
+ } else {
+ addLog('error', error.message)
+ result.error = error.message
+ result.finished = true
+ }
+ }
+
+ if (throttled) {
+ // On throttle, skip both the VM-state push and the business-metric
+ // emit. The eventual successful retry will produce `email_sent` and
+ // push the success bit to the VM stack — pushing them now would
+ // double-count and lie about the send outcome.
+ return result
}
// Push the response to the VM stack if running inline (not from the email queue)
@@ -285,6 +357,10 @@ export class EmailService {
throw new Error('No messageId returned from SES')
}
} catch (error: unknown) {
+ if (isSesThrottleError(error)) {
+ sesThrottleResponsesTotal.inc({ error_code: error.name })
+ throw new SESThrottleError(error.name, pickThrottleRetryDelayMs(), error.message)
+ }
const message = error instanceof Error ? error.message : String(error)
throw new Error(`Failed to send email via SES: ${message}`)
}
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
new file mode 100644
index 000000000000..8d11d42f4290
--- /dev/null
+++ b/nodejs/src/cdp/services/rate-limiter/rate-limiter-valkey-pool.ts
@@ -0,0 +1,53 @@
+import type { CommonConfig } from '~/common/config'
+import { RedisV2, createRedisV2PoolFromConfig } from '~/common/redis/redis-v2'
+import { logger } from '~/utils/logger'
+
+import type { CdpConfig } from '../../config'
+
+export type RateLimiterValkeyConfig = Pick<
+ CdpConfig,
+ | 'SES_RATE_LIMITER_VALKEY_HOST'
+ | 'SES_RATE_LIMITER_VALKEY_PORT'
+ | 'SES_RATE_LIMITER_VALKEY_PASSWORD'
+ | 'SES_RATE_LIMITER_VALKEY_TLS'
+> &
+ Pick<CommonConfig, 'REDIS_POOL_MIN_SIZE' | 'REDIS_POOL_MAX_SIZE'>
+
+/**
+ * Creates a connection to the dedicated SES rate-limiter Valkey instance.
+ *
+ * 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.
+ */
+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`)
+ return null
+ }
+
+ logger.info(
+ '🪙',
+ `[${name}] writer=${config.SES_RATE_LIMITER_VALKEY_HOST}:${config.SES_RATE_LIMITER_VALKEY_PORT} tls=${config.SES_RATE_LIMITER_VALKEY_TLS}`
+ )
+
+ const tls = config.SES_RATE_LIMITER_VALKEY_TLS ? {} : undefined
+
+ return createRedisV2PoolFromConfig({
+ connection: {
+ url: config.SES_RATE_LIMITER_VALKEY_HOST,
+ options: {
+ port: config.SES_RATE_LIMITER_VALKEY_PORT,
+ password: config.SES_RATE_LIMITER_VALKEY_PASSWORD,
+ tls,
+ },
+ name,
+ },
+ poolMinSize: config.REDIS_POOL_MIN_SIZE,
+ poolMaxSize: config.REDIS_POOL_MAX_SIZE,
+ })
+}
diff --git a/nodejs/src/cdp/services/rate-limiter/rate-limiter.service.test.ts b/nodejs/src/cdp/services/rate-limiter/rate-limiter.service.test.ts
new file mode 100644
index 000000000000..ab61d331caf5
--- /dev/null
+++ b/nodejs/src/cdp/services/rate-limiter/rate-limiter.service.test.ts
@@ -0,0 +1,198 @@
+import { register } from 'prom-client'
+
+import { RedisV2, createRedisV2PoolFromConfig } from '~/common/redis/redis-v2'
+import { Hub } from '~/types'
+import { closeHub, createHub } from '~/utils/db/hub'
+
+import { deleteKeysWithPrefix } from '../../_tests/redis'
+import { RateLimiterService } from './rate-limiter.service'
+
+const KEY = '@posthog-test/ses-rate-limiter/bucket'
+
+describe('RateLimiterService', () => {
+ jest.retryTimes(3)
+
+ let hub: Hub
+ let redis: RedisV2
+ let limiter: RateLimiterService
+
+ beforeEach(async () => {
+ hub = await createHub()
+ // Reuse the local CDP Redis for tests — same wire protocol, same atomicity.
+ // In production this points at the dedicated SES rate-limiter Valkey.
+ redis = createRedisV2PoolFromConfig({
+ connection: hub.CDP_REDIS_HOST
+ ? {
+ url: hub.CDP_REDIS_HOST,
+ options: { port: hub.CDP_REDIS_PORT, password: hub.CDP_REDIS_PASSWORD },
+ }
+ : { url: hub.REDIS_URL },
+ poolMinSize: hub.REDIS_POOL_MIN_SIZE,
+ poolMaxSize: hub.REDIS_POOL_MAX_SIZE,
+ })
+ limiter = new RateLimiterService(redis, { name: 'ses-rate-limiter' })
+ await deleteKeysWithPrefix(redis, '@posthog-test/ses-rate-limiter')
+ })
+
+ afterEach(async () => {
+ await closeHub(hub)
+ })
+
+ it('cold-starts at full capacity', async () => {
+ const granted = await limiter.claimUpTo({
+ key: KEY,
+ requested: 50,
+ capacity: 50,
+ refillPerSecond: 100,
+ })
+ expect(granted).toBe(50)
+ })
+
+ it('returns 0 when the bucket is drained', async () => {
+ await limiter.claimUpTo({ key: KEY, requested: 50, capacity: 50, refillPerSecond: 100 })
+ // Second claim immediately after — refill in 0ms is negligible, ~0 tokens available
+ const granted = await limiter.claimUpTo({
+ key: KEY,
+ requested: 50,
+ capacity: 50,
+ refillPerSecond: 100,
+ })
+ expect(granted).toBeLessThan(5)
+ })
+
+ it('grants partial when fewer tokens are available than requested', async () => {
+ // First, drain 40 of 50.
+ await limiter.claimUpTo({ key: KEY, requested: 40, capacity: 50, refillPerSecond: 0 })
+ // refillPerSecond=0 keeps the residual at exactly 10 tokens.
+ const granted = await limiter.claimUpTo({
+ key: KEY,
+ requested: 50,
+ capacity: 50,
+ refillPerSecond: 0,
+ })
+ expect(granted).toBe(10)
+ })
+
+ it('refills tokens over time', async () => {
+ await limiter.claimUpTo({ key: KEY, requested: 50, capacity: 50, refillPerSecond: 100 })
+ // Wait 200ms — at 100 tokens/sec, ~20 tokens should refill.
+ await new Promise((resolve) => setTimeout(resolve, 200))
+ const granted = await limiter.claimUpTo({
+ key: KEY,
+ requested: 50,
+ capacity: 50,
+ refillPerSecond: 100,
+ })
+ // Allow a wide margin — real-time-based, can vary on busy CI.
+ expect(granted).toBeGreaterThanOrEqual(10)
+ expect(granted).toBeLessThanOrEqual(30)
+ })
+
+ it('atomically serializes concurrent claims so the sum never exceeds capacity', async () => {
+ // Two pods racing for the same bucket. Single Lua script per call → Valkey
+ // serializes them, so the sum-of-grants is bounded by the bucket capacity.
+ const N = 5
+ const claims = await Promise.all(
+ Array.from({ length: N }, () =>
+ limiter.claimUpTo({ key: KEY, requested: 50, capacity: 50, refillPerSecond: 0 })
+ )
+ )
+ const total = claims.reduce((a, b) => a + b, 0)
+ expect(total).toBe(50)
+ // Exactly one caller got the full bucket; the rest got 0.
+ expect(claims.filter((c) => c > 0)).toHaveLength(1)
+ })
+
+ it('caps tokens at capacity even after long idle', async () => {
+ await limiter.claimUpTo({ key: KEY, requested: 50, capacity: 50, refillPerSecond: 1000 })
+ // Wait long enough that uncapped accrual would exceed capacity.
+ await new Promise((resolve) => setTimeout(resolve, 100))
+ const granted = await limiter.claimUpTo({
+ key: KEY,
+ requested: 1000,
+ capacity: 50,
+ refillPerSecond: 1000,
+ })
+ expect(granted).toBe(50)
+ })
+
+ describe('metric emission', () => {
+ // Counters are module-scoped globals — use deltas (after − before) per
+ // test so we don't have to reset shared state between runs.
+ const readCounter = async (labels: Record<string, string>): Promise<number> => {
+ const metric = register.getSingleMetric('cdp_rate_limiter_claim_total')
+ if (!metric) {
+ return 0
+ }
+ const data = await metric.get()
+ return data.values
+ .filter((v: any) =>
+ Object.entries(labels).every(([k, val]) => (v.labels as Record<string, string>)[k] === val)
+ )
+ .reduce((sum: number, v: any) => sum + v.value, 0)
+ }
+
+ it('increments granted_full when the grant equals the request', async () => {
+ const labels = { limiter: 'ses-rate-limiter', key: KEY, result: 'granted_full' }
+ const before = await readCounter(labels)
+
+ const granted = await limiter.claimUpTo({ key: KEY, requested: 5, capacity: 10, refillPerSecond: 0 })
+ expect(granted).toBe(5)
+
+ const after = await readCounter(labels)
+ expect(after - before).toBe(1)
+ })
+
+ it('increments granted_partial when the grant is less than the request', async () => {
+ // Drain to 2 tokens, then ask for 5.
+ await limiter.claimUpTo({ key: KEY, requested: 8, capacity: 10, refillPerSecond: 0 })
+
+ const labels = { limiter: 'ses-rate-limiter', key: KEY, result: 'granted_partial' }
+ const before = await readCounter(labels)
+
+ const granted = await limiter.claimUpTo({ key: KEY, requested: 5, capacity: 10, refillPerSecond: 0 })
+ expect(granted).toBe(2)
+
+ const after = await readCounter(labels)
+ expect(after - before).toBe(1)
+ })
+
+ it('increments denied when the bucket is empty', async () => {
+ // Drain the bucket fully.
+ await limiter.claimUpTo({ key: KEY, requested: 10, capacity: 10, refillPerSecond: 0 })
+
+ const labels = { limiter: 'ses-rate-limiter', key: KEY, result: 'denied' }
+ const before = await readCounter(labels)
+
+ const granted = await limiter.claimUpTo({ key: KEY, requested: 5, capacity: 10, refillPerSecond: 0 })
+ expect(granted).toBe(0)
+
+ const after = await readCounter(labels)
+ expect(after - before).toBe(1)
+ })
+
+ it('increments valkey_error when the Lua call throws', async () => {
+ // Synthetic broken pool — useClient rejects on every call.
+ const brokenValkey = {
+ useClient: jest.fn().mockRejectedValue(new Error('connection lost')),
+ usePipeline: jest.fn(),
+ } as unknown as RedisV2
+ const brokenLimiter = new RateLimiterService(brokenValkey, { name: 'broken-limiter' })
+
+ const labels = { limiter: 'broken-limiter', key: KEY, result: 'valkey_error' }
+ const before = await readCounter(labels)
+
+ const granted = await brokenLimiter.claimUpTo({
+ key: KEY,
+ requested: 5,
+ capacity: 10,
+ refillPerSecond: 0,
+ })
+ // Fail-closed: thrown error → 0 granted.
+ expect(granted).toBe(0)
+
+ const after = await readCounter(labels)
+ expect(after - before).toBe(1)
+ })
+ })
+})
diff --git a/nodejs/src/cdp/services/rate-limiter/rate-limiter.service.ts b/nodejs/src/cdp/services/rate-limiter/rate-limiter.service.ts
new file mode 100644
index 000000000000..88d4b17df0ec
--- /dev/null
+++ b/nodejs/src/cdp/services/rate-limiter/rate-limiter.service.ts
@@ -0,0 +1,185 @@
+import { Counter, Histogram } from 'prom-client'
+
+import { RedisV2 } from '~/common/redis/redis-v2'
+import { logger } from '~/utils/logger'
+
+/**
+ * Distributed token-bucket rate limiter for "claim up to N" semantics, backed
+ * by a dedicated Valkey instance.
+ *
+ * Differs from KeyedRateLimiterService: that limiter is binary (you get all of
+ * `cost` or none) and grouped per-key for per-function rate limits. This one is
+ * "best-effort" — you ask for up to N tokens and get back however many were
+ * available (0..N), so the email worker can size its dequeue batch to the
+ * available SES budget instead of asking for all-or-nothing.
+ *
+ * Single Lua script per call → atomic across pods. Multiple workers polling
+ * concurrently never overshoot the bucket capacity.
+ */
+
+const claimCounter = new Counter({
+ name: 'cdp_rate_limiter_claim_total',
+ help: 'Token-bucket claim outcomes from the SES rate limiter Valkey.',
+ labelNames: ['limiter', 'key', 'result'],
+})
+
+const claimLatency = new Histogram({
+ name: 'cdp_rate_limiter_claim_duration_ms',
+ help: 'Latency of a single Valkey claim call (Lua roundtrip).',
+ labelNames: ['limiter'],
+ buckets: [0.5, 1, 2, 5, 10, 25, 50, 100, 250, 500],
+})
+
+// Atomic "claim up to" token-bucket script.
+// KEYS[1] = bucket hash key (stores `ts` and `pool`)
+// ARGV[1] = requested tokens (integer)
+// ARGV[2] = pool capacity (max tokens the bucket can hold)
+// ARGV[3] = refill rate (tokens per second)
+// ARGV[4] = TTL seconds — bucket auto-expires when idle so cold-start
+// gives full capacity rather than a stale negative pool.
+//
+// `now` is sourced via `redis.call('TIME')` so all pods share a single
+// monotonic clock — NTP drift between workers can't over- or under-refill
+// the bucket on this code path.
+//
+// Returns the number of tokens granted (0..requested).
+const CLAIM_UP_TO_LUA = `
+local key = KEYS[1]
+local requested = tonumber(ARGV[1])
+local capacity = tonumber(ARGV[2])
+local refillPerSecond = tonumber(ARGV[3])
+local ttlSeconds = tonumber(ARGV[4])
+
+local time = redis.call('TIME')
+-- TIME returns {seconds, microseconds}; flatten to epoch ms.
+local now = tonumber(time[1]) * 1000 + math.floor(tonumber(time[2]) / 1000)
+
+local existing = redis.call('hmget', key, 'ts', 'pool')
+local rawTs = existing[1]
+local rawPool = existing[2]
+
+local available
+if rawTs == false then
+ available = capacity
+else
+ local lastTs = tonumber(rawTs)
+ local elapsedMs = now - lastTs
+ if elapsedMs < 0 then
+ elapsedMs = 0
+ end
+ local currentTokens
+ if rawPool == false then
+ currentTokens = capacity
+ else
+ currentTokens = tonumber(rawPool)
+ end
+ available = math.min(capacity, currentTokens + (elapsedMs / 1000.0) * refillPerSecond)
+end
+
+local rawGranted = math.min(available, requested)
+if rawGranted < 0 then
+ rawGranted = 0
+end
+-- Floor to int — the grant flows into a SQL LIMIT, which must be integer.
+-- The fractional residual stays in the pool so partial refills accumulate
+-- across calls instead of being silently dropped.
+local granted = math.floor(rawGranted)
+local tokensAfter = available - granted
+
+redis.call('hset', key, 'ts', now, 'pool', tokensAfter)
+redis.call('expire', key, ttlSeconds)
+
+return granted
+`
+
+export interface RateLimiterConfig {
+ /** Logical name for metrics/logging only (e.g. 'ses'). */
+ name: string
+}
+
+export interface ClaimRequest {
+ key: string
+ requested: number
+ capacity: number
+ refillPerSecond: number
+ /** Bucket TTL in seconds — long enough that an idle bucket can cold-start at full capacity. */
+ ttlSeconds?: number
+}
+
+export class RateLimiterService {
+ constructor(
+ private readonly valkey: RedisV2,
+ private readonly config: RateLimiterConfig
+ ) {}
+
+ /**
+ * Synchronous startup check — throws if Valkey is unreachable. Pod fails its
+ * health probe, k8s restarts. By design: if the rate limiter can't be reached
+ * we must not send (would risk SES throttling), and the simplest enforcement
+ * is to not start the worker at all.
+ */
+ public async ping(): Promise<void> {
+ const result = await this.valkey.useClient(
+ { name: `rate-limiter:${this.config.name}:ping`, timeout: 5000 },
+ (client) => client.ping()
+ )
+ if (result !== 'PONG') {
+ throw new Error(`RateLimiterService(${this.config.name}): Valkey PING did not return PONG`)
+ }
+ }
+
+ /**
+ * Atomically claim up to `requested` tokens from the bucket. Returns the
+ * number actually granted (0..requested). Multiple callers can race against
+ * the same key — the Lua script serializes them, so the sum of grants across
+ * concurrent callers can never exceed available bucket capacity.
+ *
+ * Runtime errors (Valkey down, command timeout) return 0 — fail-closed.
+ * A startup PING already established reachability; mid-run errors trigger
+ * the worker's empty-batch sleep instead of crashing.
+ */
+ public async claimUpTo(req: ClaimRequest): Promise<number> {
+ const endTimer = claimLatency.startTimer({ limiter: this.config.name })
+ const ttlSeconds = req.ttlSeconds ?? 3600
+ try {
+ // useClient throws on error (failOpen unset), so the catch block
+ // handles Valkey reachability — no need for a null-result branch.
+ const result = await this.valkey.useClient(
+ { name: `rate-limiter:${this.config.name}:claimUpTo`, timeout: 1000 },
+ (client) =>
+ client.eval(
+ CLAIM_UP_TO_LUA,
+ 1,
+ req.key,
+ String(req.requested),
+ String(req.capacity),
+ String(req.refillPerSecond),
+ String(ttlSeconds)
+ )
+ )
+
+ const granted = Number(result)
+ if (!Number.isFinite(granted) || granted < 0) {
+ logger.warn('🪙', `RateLimiterService(${this.config.name}) returned invalid grant`, {
+ key: req.key,
+ raw: result,
+ })
+ claimCounter.inc({ limiter: this.config.name, key: req.key, result: 'valkey_error' })
+ return 0
+ }
+
+ const outcome = granted === 0 ? 'denied' : granted < req.requested ? 'granted_partial' : 'granted_full'
+ claimCounter.inc({ limiter: this.config.name, key: req.key, result: outcome })
+ return granted
+ } catch (err) {
+ logger.warn('🪙', `RateLimiterService(${this.config.name}) claim threw`, {
+ key: req.key,
+ error: String(err),
+ })
+ claimCounter.inc({ limiter: this.config.name, key: req.key, result: 'valkey_error' })
+ return 0
+ } finally {
+ endTimer()
+ }
+ }
+}
diff --git a/nodejs/src/cdp/workflows-e2e.test.ts b/nodejs/src/cdp/workflows-e2e.test.ts
index b74fa6d9082d..e2b980c64a51 100644
--- a/nodejs/src/cdp/workflows-e2e.test.ts
+++ b/nodejs/src/cdp/workflows-e2e.test.ts
@@ -17,6 +17,7 @@ import { KafkaProducerObserver } from '~/tests/helpers/mocks/producer.spy'
import { DateTime } from 'luxon'
import { Pool } from 'pg'
+import { register } from 'prom-client'
import { createCdpConsumerDeps } from '~/tests/helpers/cdp'
import { waitForExpect } from '~/tests/helpers/expectations'
@@ -34,10 +35,12 @@ import {
InternalPersonWithDistinctId,
PersonReadRepository,
} from '../../src/worker/ingestion/persons/repositories/person-repository'
+import { createRedisV2PoolFromConfig } from '../common/redis/redis-v2'
import { FixtureHogFlowBuilder } from './_tests/builders/hogflow.builder'
import { HOG_FILTERS_EXAMPLES } from './_tests/examples'
import { createHogExecutionGlobals, insertHogFunctionTemplate, insertIntegration } from './_tests/fixtures'
import { insertHogFlow } from './_tests/fixtures-hogflows'
+import { deleteKeysWithPrefix } from './_tests/redis'
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'
@@ -45,7 +48,9 @@ import { CdpHogflowSubscriptionMatcherConsumer } from './consumers/cdp-hogflow-s
import { CyclotronJobQueueKafka } from './services/job-queue/job-queue-kafka'
import { CyclotronJobQueuePostgres } from './services/job-queue/job-queue-postgres'
import { CyclotronJobQueuePostgresV2 } from './services/job-queue/job-queue-postgres-v2'
+import { CyclotronJobQueueRateLimitedPostgresV2 } from './services/job-queue/job-queue-rate-limited-postgres-v2'
import { JobQueue } from './services/job-queue/job-queue.interface'
+import { RateLimiterService } from './services/rate-limiter/rate-limiter.service'
import { HogFunctionInvocationGlobals } from './types'
import { convertBatchHogFlowRequestToHogFunctionInvocationGlobals } from './utils'
import { convertToHogFunctionFilterGlobal } from './utils/hog-function-filtering'
@@ -1756,4 +1761,250 @@ describe('Workflows E2E (email queue)', () => {
expect(emailsSent()).toBe(2)
}, 15000)
})
+
+ it('rate-limited variant processes emails end-to-end through the dedicated bucket', async () => {
+ // Verifies the inject-pattern wiring: CyclotronJobQueueRateLimitedPostgresV2
+ // gates dequeue via a Valkey bucket, then the email worker processes the
+ // job normally. Reuses the local test Redis as the bucket store (same
+ // approach as rate-limiter.service.test.ts).
+ await emailWorker.stop()
+
+ const limiterValkey = createRedisV2PoolFromConfig({
+ connection: hub.CDP_REDIS_HOST
+ ? {
+ url: hub.CDP_REDIS_HOST,
+ options: { port: hub.CDP_REDIS_PORT, password: hub.CDP_REDIS_PASSWORD },
+ }
+ : { url: hub.REDIS_URL },
+ poolMinSize: hub.REDIS_POOL_MIN_SIZE,
+ poolMaxSize: hub.REDIS_POOL_MAX_SIZE,
+ })
+ const bucketKey = '@posthog-test/ses-e2e/bucket'
+ await deleteKeysWithPrefix(limiterValkey, '@posthog-test/ses-e2e/')
+
+ const rateLimitedQueue = new CyclotronJobQueueRateLimitedPostgresV2(hub.CONSUMER_BATCH_SIZE, hub, {
+ limiter: new RateLimiterService(limiterValkey, { name: 'ses-e2e' }),
+ key: bucketKey,
+ capacity: 10,
+ refillPerSecond: 10,
+ throttledPollDelayMs: 50,
+ })
+ emailWorker = new CdpCyclotronWorkerEmail(hub, deps, rateLimitedQueue)
+ await emailWorker.start()
+
+ 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: 'Rate-limited 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)
+
+ const { backgroundTask } = await eventsConsumer.processBatch([createGlobals()])
+ await backgroundTask
+
+ // The email is sent — the rate-limited queue gated, dequeued, and processed the job.
+ await waitForExpect(() => {
+ const emailSentCount = mockProducerObserver
+ .getProducedKafkaMessagesForTopic(KAFKA_APP_METRICS_2)
+ .filter((m: any) => m.value.metric_name === 'email_sent')
+ .reduce((sum: number, m: any) => sum + m.value.count, 0)
+ expect(emailSentCount).toBe(1)
+ }, 15000)
+
+ // The bucket has been touched — proves the rate limiter was actually consulted,
+ // not bypassed. `ts` and `pool` are written on every claim (cold start or refill).
+ const bucket = await limiterValkey.useClient({ name: 'read-bucket' }, (client) => client.hgetall(bucketKey))
+ expect(bucket?.ts).toBeTruthy()
+ expect(bucket?.pool).toBeTruthy()
+ })
+
+ it('rate-limits dequeue when the bucket drains, then drains the queue as it refills', async () => {
+ // Tiny bucket (capacity 1, refill 2/sec = 1 token every 500ms) so the
+ // worker has to wait for refills between sends. With 3 emails enqueued
+ // we should see the bucket get denied at least once while the worker
+ // is waiting — and all 3 should still eventually go through.
+ await emailWorker.stop()
+
+ const limiterValkey = createRedisV2PoolFromConfig({
+ connection: hub.CDP_REDIS_HOST
+ ? {
+ url: hub.CDP_REDIS_HOST,
+ options: { port: hub.CDP_REDIS_PORT, password: hub.CDP_REDIS_PASSWORD },
+ }
+ : { url: hub.REDIS_URL },
+ poolMinSize: hub.REDIS_POOL_MIN_SIZE,
+ poolMaxSize: hub.REDIS_POOL_MAX_SIZE,
+ })
+ const bucketKey = '@posthog-test/ses-e2e-throttled/bucket'
+ await deleteKeysWithPrefix(limiterValkey, '@posthog-test/ses-e2e-throttled/')
+
+ const limiterName = 'ses-e2e-throttled'
+ const rateLimitedQueue = new CyclotronJobQueueRateLimitedPostgresV2(hub.CONSUMER_BATCH_SIZE, hub, {
+ limiter: new RateLimiterService(limiterValkey, { name: limiterName }),
+ key: bucketKey,
+ capacity: 1,
+ refillPerSecond: 2,
+ throttledPollDelayMs: 50,
+ })
+ emailWorker = new CdpCyclotronWorkerEmail(hub, deps, rateLimitedQueue)
+ await emailWorker.start()
+
+ // Snapshot the denied counter so we measure only this test's claims.
+ const readDeniedCount = async (): Promise<number> => {
+ const metric = register.getSingleMetric('cdp_rate_limiter_claim_total')
+ if (!metric) {
+ return 0
+ }
+ const data = await metric.get()
+ return data.values
+ .filter(
+ (v: any) =>
+ v.labels.result === 'denied' && v.labels.limiter === limiterName && v.labels.key === bucketKey
+ )
+ .reduce((sum: number, v: any) => sum + v.value, 0)
+ }
+ const deniedBefore = await readDeniedCount()
+
+ 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: 'Throttled 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)
+
+ // Three distinct events → three email jobs queued near-simultaneously.
+ const events = Array.from({ length: 3 }, () => createGlobals({ uuid: new UUIDT().toString() }))
+ const { backgroundTask } = await eventsConsumer.processBatch(events)
+ await backgroundTask
+
+ // All three eventually send — generous timeout because the bucket only
+ // refills 2 tokens/sec.
+ await waitForExpect(() => {
+ const emailSentCount = mockProducerObserver
+ .getProducedKafkaMessagesForTopic(KAFKA_APP_METRICS_2)
+ .filter((m: any) => m.value.metric_name === 'email_sent')
+ .reduce((sum: number, m: any) => sum + m.value.count, 0)
+ expect(emailSentCount).toBe(3)
+ }, 20000)
+
+ // The bucket was denied at least once during processing — proves the
+ // gating actually fired, not that we just dequeued 3 jobs in a row.
+ // (With capacity=1 and three pending jobs, between sends the worker
+ // polls many times finding bucket=0.)
+ const deniedAfter = await readDeniedCount()
+ expect(deniedAfter - deniedBefore).toBeGreaterThan(0)
+ })
+
+ it('does not increment the limiter counter on idle polls (no work, no metric)', async () => {
+ // Regression guard for the peek-before-claim fix. Without it, idle
+ // workers would silently drain the bucket on every poll and the
+ // denied counter would climb even with zero traffic.
+ await emailWorker.stop()
+
+ const limiterValkey = createRedisV2PoolFromConfig({
+ connection: hub.CDP_REDIS_HOST
+ ? {
+ url: hub.CDP_REDIS_HOST,
+ options: { port: hub.CDP_REDIS_PORT, password: hub.CDP_REDIS_PASSWORD },
+ }
+ : { url: hub.REDIS_URL },
+ poolMinSize: hub.REDIS_POOL_MIN_SIZE,
+ poolMaxSize: hub.REDIS_POOL_MAX_SIZE,
+ })
+ const bucketKey = '@posthog-test/ses-e2e-idle/bucket'
+ await deleteKeysWithPrefix(limiterValkey, '@posthog-test/ses-e2e-idle/')
+
+ const limiterName = 'ses-e2e-idle'
+ const rateLimitedQueue = new CyclotronJobQueueRateLimitedPostgresV2(hub.CONSUMER_BATCH_SIZE, hub, {
+ limiter: new RateLimiterService(limiterValkey, { name: limiterName }),
+ key: bucketKey,
+ capacity: 2,
+ refillPerSecond: 1,
+ throttledPollDelayMs: 50,
+ })
+ emailWorker = new CdpCyclotronWorkerEmail(hub, deps, rateLimitedQueue)
+ await emailWorker.start()
+
+ // Sum across all result labels — even granted_* would be wrong here
+ // since no work exists. The whole counter family should be flat.
+ const readAllResults = async (): Promise<number> => {
+ const metric = register.getSingleMetric('cdp_rate_limiter_claim_total')
+ if (!metric) {
+ return 0
+ }
+ const data = await metric.get()
+ return data.values
+ .filter((v: any) => v.labels.limiter === limiterName && v.labels.key === bucketKey)
+ .reduce((sum: number, v: any) => sum + v.value, 0)
+ }
+
+ const before = await readAllResults()
+
+ // Let the worker poll for a full second with no jobs queued — that's
+ // ~20 poll cycles at the default 50ms cadence. None should claim.
+ await new Promise((resolve) => setTimeout(resolve, 1000))
+
+ const after = await readAllResults()
+ expect(after - before).toBe(0)
+ })
})
diff --git a/nodejs/src/server.ts b/nodejs/src/server.ts
index a0c6de9545c1..8c1695f33de7 100644
--- a/nodejs/src/server.ts
+++ b/nodejs/src/server.ts
@@ -26,6 +26,9 @@ import { HogFlowScheduleService } from './cdp/services/hogflow-schedule/hogflow-
import { CyclotronJobQueueKafka } from './cdp/services/job-queue/job-queue-kafka'
import { CyclotronJobQueuePostgres } from './cdp/services/job-queue/job-queue-postgres'
import { CyclotronJobQueuePostgresV2 } from './cdp/services/job-queue/job-queue-postgres-v2'
+import { CyclotronJobQueueRateLimitedPostgresV2 } from './cdp/services/job-queue/job-queue-rate-limited-postgres-v2'
+import { createSesRateLimiterValkeyPool } from './cdp/services/rate-limiter/rate-limiter-valkey-pool'
+import { RateLimiterService } from './cdp/services/rate-limiter/rate-limiter.service'
import { EncryptedFields } from './cdp/utils/encryption-utils'
import { defaultConfig } from './config/config'
import { createIngestionRedisConnectionConfig, createPosthogRedisConnectionConfig } from './config/redis-pools'
@@ -275,7 +278,20 @@ 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)
+ // When the SES rate-limiter Valkey is configured, use the rate-limited
+ // variant so dequeue is gated by a Valkey-backed token bucket. Without
+ // the env var (typical for local dev outside k8s) we fall back to the
+ // plain queue and dequeue is unthrottled.
+ const sesValkey = createSesRateLimiterValkeyPool(this.config)
+ const queue = sesValkey
+ ? new CyclotronJobQueueRateLimitedPostgresV2(this.config.CONSUMER_BATCH_SIZE, this.config, {
+ limiter: new RateLimiterService(sesValkey, { name: 'ses' }),
+ key: '@posthog/ses/global',
+ capacity: this.config.CDP_SES_RATE_LIMIT_CAPACITY,
+ refillPerSecond: this.config.CDP_SES_RATE_LIMIT_REFILL_PER_SECOND,
+ throttledPollDelayMs: this.config.CDP_SES_RATE_LIMIT_THROTTLED_POLL_DELAY_MS,
+ })
+ : new CyclotronJobQueuePostgresV2(this.config.CONSUMER_BATCH_SIZE, this.config)
const worker = new CdpCyclotronWorkerEmail(this.config, cdpDeps!, queue)
await worker.start()
return worker.service