: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(cdp-email): size SES rate-limit claim to visible row count (#64235)
Meikel Ratzbebc08456b2d
diff --git a/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.ts b/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.tsindex 938e052c5b47..192c34f9c24e 100644--- a/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.ts+++ b/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.ts@@ -490,11 +490,12 @@ describe('Cyclotron V2', () => {})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.+ // The hook is consulted on every poll. It receives the number of+ // rows actually visible (capped at batchMaxSize). 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>,+ getBatchLimit: (requested: number) => Promise<CyclotronV2BatchLimit | undefined>,overrides?: Record<string, unknown>): CyclotronV2RateLimitedWorker =>new CyclotronV2RateLimitedWorker(@@ -510,9 +511,7 @@ describe('Cyclotron V2', () => {)it('clamps the batch to the granted limit', async () => {- for (let i = 0; i < 10; i++) {- await manager.createJob({ teamId: 1, queueName: QUEUE })- }+ await manager.bulkCreateJobs(Array.from({ length: 10 }, () => ({ teamId: 1, queueName: QUEUE })))// eslint-disable-next-line @typescript-eslint/require-awaitconst worker = createRateLimitedWorker(async () => ({ limit: 3 }))@@ -539,9 +538,7 @@ describe('Cyclotron V2', () => {})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 })- }+ await manager.bulkCreateJobs(Array.from({ length: 5 }, () => ({ teamId: 1, queueName: QUEUE })))// eslint-disable-next-line @typescript-eslint/require-awaitconst worker = createRateLimitedWorker(async () => undefined)@@ -606,6 +603,43 @@ describe('Cyclotron V2', () => {// so the limiter hook is never invoked.expect(hookCalls).toBe(0)})++ it('passes the visible row count to the limiter hook', async () => {+ // Sparse-traffic regression guard. 3 ready rows + batchMaxSize=100+ // → hook must be asked for 3 tokens, not 100. Without pre-sizing,+ // a single trickle of jobs would drain the full bucket per send.+ await manager.bulkCreateJobs(Array.from({ length: 3 }, () => ({ teamId: 1, queueName: QUEUE })))++ const requestedHistory: number[] = []+ const worker = createRateLimitedWorker((requested) => {+ requestedHistory.push(requested)+ return Promise.resolve({ limit: requested })+ })++ await dequeueOneBatch(worker)++ // First (and only relevant) call: 3 rows visible → 3 requested.+ expect(requestedHistory[0]).toBe(3)+ })++ it('caps the visible row count at batchMaxSize', async () => {+ // Backlog of 10 rows with batchMaxSize=4 should ask for 4+ // (the batch ceiling), not 10.+ await manager.bulkCreateJobs(Array.from({ length: 10 }, () => ({ teamId: 1, queueName: QUEUE })))++ const requestedHistory: number[] = []+ const worker = createRateLimitedWorker(+ (requested) => {+ requestedHistory.push(requested)+ return Promise.resolve({ limit: requested })+ },+ { batchMaxSize: 4 }+ )++ await dequeueOneBatch(worker)++ expect(requestedHistory[0]).toBe(4)+ })})it.each([diff --git a/nodejs/src/cdp/services/cyclotron-v2/worker-rate-limited.ts b/nodejs/src/cdp/services/cyclotron-v2/worker-rate-limited.tsindex 78f33f967d45..261a8bd22dd6 100644--- a/nodejs/src/cdp/services/cyclotron-v2/worker-rate-limited.ts+++ b/nodejs/src/cdp/services/cyclotron-v2/worker-rate-limited.ts@@ -5,17 +5,21 @@ 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)`.+ * dequeuing. The hook receives the count of rows actually visible for this+ * poll (capped at `batchMaxSize`); returning `{ limit: 0 }` skips the SQL+ * entirely and sleeps, `{ 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.+ * bucket. Sizing the claim to the visible row count is what keeps a sparse+ * stream of email jobs (one ready row at a time) from draining the bucket's+ * full capacity per send — see `countWork` on the base worker. 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>+ private readonly getBatchLimit: (requested: number) => Promise<CyclotronV2BatchLimit | undefined>) {super(config)}@@ -27,18 +31,20 @@ export class CyclotronV2RateLimitedWorker extends CyclotronV2Worker {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())) {+ // Pre-size the token-bucket claim to the number of rows actually+ // available for this poll, capped at batchMaxSize. Idle polls+ // (count === 0) skip the limiter entirely so the bucket stays+ // at capacity for the next burst. Sparse polls (count < capacity)+ // only consume what they'll send, fixing the "1 ready job drains+ // the whole bucket" failure mode of asking for full capacity+ // every time.+ const visibleRows = await this.countWork(this.batchMaxSize)+ if (visibleRows === 0) {await sleep(this.pollDelayMs)continue}- const decision = await this.getBatchLimit()+ const decision = await this.getBatchLimit(visibleRows)// === 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) {diff --git a/nodejs/src/cdp/services/cyclotron-v2/worker.ts b/nodejs/src/cdp/services/cyclotron-v2/worker.tsindex 2e834f3d9f32..e4beac4a2428 100644--- a/nodejs/src/cdp/services/cyclotron-v2/worker.ts+++ b/nodejs/src/cdp/services/cyclotron-v2/worker.ts@@ -86,25 +86,33 @@ export class CyclotronV2Worker {}/**- * 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.+ * Cheap pre-check that returns how many jobs are currently dequeueable from+ * this worker's queue, capped at `limit`. Used by rate-limited subclasses+ * to size their token-bucket claim to "exactly what we plan to dequeue"+ * instead of always claiming the bucket's full capacity — keeps unused+ * tokens in the bucket when traffic is sparse and a single job per poll is+ * what we end up dequeuing.** 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.+ * A short race exists between this count and the subsequent dequeue —+ * concurrent pods may grab some rows in the gap via `SKIP LOCKED` — so+ * `dequeueJobs` can return fewer rows than counted. That's bounded by+ * concurrency × poll rate and rate-limiter refill absorbs the slack.*/- 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]+ protected async countWork(limit: number): Promise<number> {+ const result = await this.pool.query<{ n: number }>(+ `SELECT COUNT(*)::int AS n FROM (+ SELECT 1 FROM cyclotron_jobs+ WHERE status = 'available'+ AND queue_name = $1+ AND scheduled <= NOW()+ LIMIT $2+ ) sub`,+ [this.config.queueName, limit])- return result.rowCount !== null && result.rowCount > 0+ return result.rows[0].n}protected async dequeueJobs(limit: number = this.batchMaxSize): Promise<RawJobRow[]> {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.tsindex 4ae6545aa615..024ea32e0178 100644--- a/nodejs/src/cdp/services/job-queue/job-queue-rate-limited-postgres-v2.ts+++ b/nodejs/src/cdp/services/job-queue/job-queue-rate-limited-postgres-v2.ts@@ -46,26 +46,29 @@ export class CyclotronJobQueueRateLimitedPostgresV2 extends CyclotronJobQueuePos}protected override createWorker(workerConfig: CyclotronV2WorkerConfig): CyclotronV2Worker {- return new CyclotronV2RateLimitedWorker(workerConfig, () => this.claimBatchLimit())+ return new CyclotronV2RateLimitedWorker(workerConfig, (requested) => this.claimBatchLimit(requested))}/**- * 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.+ * Claim outbound capacity from the bucket before each poll. `requested` is+ * the number of rows the worker actually sees as dequeueable right now+ * (capped at batchMaxSize). We additionally cap it at bucket capacity, in+ * case capacity < batchMaxSize. Returns the decision the worker applies:+ * how many rows to dequeue, or "skip and sleep" when nothing was granted.+ * 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.+ * Pre-sizing `requested` to the visible row count is what fixes the+ * "sparse traffic drains the bucket" failure mode: if only one row is+ * ready we ask for one token, not `capacity`. Granted tokens above the+ * row count would otherwise be deducted from the bucket but never used+ * (the worker's `effectiveLimit` is `min(decision.limit, batchMaxSize)`).*/- private async claimBatchLimit(): Promise<CyclotronV2BatchLimit | undefined> {- const requested = Math.min(this.rateLimit.capacity, this.consumerBatchSize)+ private async claimBatchLimit(requested: number): Promise<CyclotronV2BatchLimit | undefined> {+ const claimRequested = Math.min(requested, this.rateLimit.capacity)const granted = await this.rateLimit.limiter.claimUpTo({key: this.rateLimit.key,- requested,+ requested: claimRequested,capacity: this.rateLimit.capacity,refillPerSecond: this.rateLimit.refillPerSecond,})diff --git a/nodejs/src/cdp/workflows-e2e.test.ts b/nodejs/src/cdp/workflows-e2e.test.tsindex c34c5bf40371..fe5df4a66453 100644--- a/nodejs/src/cdp/workflows-e2e.test.ts+++ b/nodejs/src/cdp/workflows-e2e.test.ts@@ -2013,4 +2013,97 @@ describe('Workflows E2E (email queue)', () => {const after = await readAllResults()expect(after - before).toBe(0)})++ it('claims only the visible row count (sparse traffic does not drain the bucket)', async () => {+ // Regression guard for the pre-size fix. Without it, a single ready+ // email would claim the bucket's full capacity — draining ~capacity-1+ // tokens of SES budget per actual send — even though the worker can+ // only dequeue one row. Pre-sizing asks the limiter for exactly the+ // number of rows the worker is about to dequeue.+ //+ // refillPerSecond=0 freezes the bucket between the claim and our+ // assertion, so the post-claim pool is a deterministic measure of+ // what was deducted (capacity minus tokens granted on the one claim).+ 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-presize/bucket'+ await deleteKeysWithPrefix(limiterValkey, '@posthog-test/ses-e2e-presize/')++ const capacity = 10+ const rateLimitedQueue = new CyclotronJobQueueRateLimitedPostgresV2(hub.CONSUMER_BATCH_SIZE, hub, {+ limiter: new RateLimiterService(limiterValkey, { name: 'ses-e2e-presize' }),+ key: bucketKey,+ capacity,+ refillPerSecond: 0,+ 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: 'Sparse-traffic 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)++ // Exactly ONE event → one email job — the sparse-traffic scenario.+ const { backgroundTask } = await eventsConsumer.processBatch([createGlobals({ uuid: new UUIDT().toString() })])+ await backgroundTask++ 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)++ // Bucket should retain ~capacity-1 tokens — we claimed 1, not capacity.+ // Without the pre-size fix `pool` would be 0 here (the whole bucket+ // drained on the one claim).+ const bucket = await limiterValkey.useClient({ name: 'read-bucket' }, (client) => client.hgetall(bucketKey))+ const pool = parseFloat(bucket?.pool ?? '0')+ expect(pool).toBeGreaterThanOrEqual(capacity - 1)+ })})