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): reserve retry slots for tier-cap-denied emails (#97705)

Meikel Ratz5e139824fe3b
diff --git a/nodejs/src/cdp/services/messaging/email.service.test.ts b/nodejs/src/cdp/services/messaging/email.service.test.ts
index 4b16a4257294..5aecb2cfd993 100644
--- a/nodejs/src/cdp/services/messaging/email.service.test.ts
+++ b/nodejs/src/cdp/services/messaging/email.service.test.ts
@@ -17,7 +17,7 @@ import { TeamWorkflowsConfigService } from '../managers/team-workflows-config.se
import { RateLimiterService } from '../rate-limiter/rate-limiter.service'
import { selectEmailSenderIntegrationId } from './email-sender-selection'
import { EmailSuppressionService, emailSuppressionConfigFromEnv } from './email-suppression.service'
-import { EmailService, parseAddressList, sanitizeEmailSubject } from './email.service'
+import { EmailService, parseAddressList, sanitizeEmailSubject, teamEmailCapBuckets } from './email.service'
import { MailDevAPI } from './helpers/maildev'
import { EmailTrackingCodeSigner } from './helpers/tracking-code'
@@ -747,10 +747,20 @@ describe('EmailService', () => {
})
it.each([
- ['parks the send until the reported refill horizon', 30 * 60 * 1000, 30 * 60 * 1000],
- ['clamps the wake to one hour on a longer horizon', 24 * 60 * 60 * 1000, 60 * 60 * 1000],
- ])('%s', async (_name, retryAfterMs, clampedBaseMs) => {
- claimAllOrNothingPair.mockResolvedValue({ granted: false, deniedIndex: 1, retryAfterMs })
+ // A reserved slot is exclusive and is parked on exactly; spreading it would
+ // collide it with the slot in front.
+ ['parks exactly on a reserved slot', 30 * 60 * 1000, true, 30 * 60 * 1000, 30 * 60 * 1000],
+ // Past the horizon nothing is reserved: every overflow caller gets the same
+ // wake back and spreads itself 1x-2x across the horizon.
+ [
+ 'spreads an overflow wake across the horizon',
+ 60 * 60 * 1000,
+ false,
+ 60 * 60 * 1000,
+ 2 * 60 * 60 * 1000,
+ ],
+ ])('%s', async (_name, retryAfterMs, reserved, minMs, maxMs) => {
+ claimAllOrNothingPair.mockResolvedValue({ granted: false, deniedIndex: 1, retryAfterMs, reserved })
const before = Date.now()
const result = await cappedService.executeSendEmail(invocation)
@@ -761,16 +771,20 @@ describe('EmailService', () => {
// The reschedule must carry the email payload forward, same as the workflow limit.
expect(result.invocation.queueParameters).toEqual(invocation.queueParameters)
const scheduledMs = result.invocation.queueScheduledAt!.toMillis()
- // Jitter is 1x-2x the clamped horizon; the slack absorbs scheduler overhead.
- expect(scheduledMs).toBeGreaterThanOrEqual(before + clampedBaseMs)
- expect(scheduledMs).toBeLessThan(before + 2 * clampedBaseMs + 5000)
+ expect(scheduledMs).toBeGreaterThanOrEqual(before + minMs)
+ expect(scheduledMs).toBeLessThan(before + maxMs + 5000)
})
it('retries on the token bucket cadence when the limiter reports no horizon', async () => {
// A Valkey fault denies with no horizon. Parking on the daily cap's pacing
// interval would hold the email long after the limiter recovered.
jest.spyOn(Math, 'random').mockReturnValue(0)
- claimAllOrNothingPair.mockResolvedValue({ granted: false, deniedIndex: null, retryAfterMs: null })
+ claimAllOrNothingPair.mockResolvedValue({
+ granted: false,
+ deniedIndex: null,
+ retryAfterMs: null,
+ reserved: false,
+ })
const before = Date.now()
const result = await cappedService.executeSendEmail(invocation)
@@ -783,13 +797,118 @@ describe('EmailService', () => {
})
it('sends when the claim is granted', async () => {
- claimAllOrNothingPair.mockResolvedValue({ granted: true, deniedIndex: null, retryAfterMs: null })
+ claimAllOrNothingPair.mockResolvedValue({
+ granted: true,
+ deniedIndex: null,
+ retryAfterMs: null,
+ reserved: false,
+ })
const result = await cappedService.executeSendEmail(invocation)
+ // The reservation horizon must reach the limiter, or denials fall back to
+ // shared-horizon wakes and a denied backlog re-herds.
+ expect(claimAllOrNothingPair).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.any(Number),
+ 60 * 60 * 1000
+ )
expect(result.finished).toBe(true)
expect(cappedSendSpy).toHaveBeenCalled()
})
+
+ // A team over its tier cap must not slow anyone else down: its denied sends get
+ // their own future slots instead of all waking together, and another team's send
+ // goes straight out. Runs against the real limiter.
+ it('spreads a capped team over distinct slots while another team keeps sending', async () => {
+ const hourlyCap = 360
+ const dailyCap = 8640
+ const 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,
+ })
+ const limiter = new RateLimiterService(redis, { name: 'team-email-cap-test' })
+ const configService = new TeamWorkflowsConfigService(hub.postgres, hub.pubSub)
+ jest.spyOn(configService, 'getEmailSendingTier').mockResolvedValue(0)
+ const enforcedService = new EmailService(
+ {
+ sesAccessKeyId: hub.SES_ACCESS_KEY_ID,
+ sesSecretAccessKey: hub.SES_SECRET_ACCESS_KEY,
+ sesRegion: hub.SES_REGION,
+ sesEndpoint: hub.SES_ENDPOINT,
+ sesTrackedConfigurationSet: hub.SES_TRACKED_CONFIGURATION_SET,
+ sesUntrackedConfigurationSet: hub.SES_UNTRACKED_CONFIGURATION_SET,
+ teamEmailCapMode: 'enforce',
+ teamEmailTierHourlyCaps: [hourlyCap],
+ teamEmailTierDailyCaps: [dailyCap],
+ },
+ hub.integrationManager,
+ configService,
+ hub.ENCRYPTION_SALT_KEYS,
+ hub.SITE_URL,
+ new EmailTrackingCodeSigner(hub.ENCRYPTION_SALT_KEYS, hub.CDP_EMAIL_TRACKING_URL),
+ new EmailSuppressionService(hub.postgres, emailSuppressionConfigFromEnv()),
+ new RecipientsManagerService(hub.postgres),
+ undefined,
+ null,
+ limiter
+ )
+ const enforcedSendSpy = jest.spyOn(enforcedService.sesV2Client!, 'send') as any
+ enforcedSendSpy.mockResolvedValue({ MessageId: 'test-message-id' })
+
+ // Drain the capped team's hourly bucket so every send below is a denial. The
+ // 0.1 tokens/s refill makes the slot spacing 10s, far above test wall-clock.
+ const buckets = teamEmailCapBuckets(team.id, hourlyCap, dailyCap)
+ await limiter.claimUpTo({
+ key: buckets[0].key,
+ requested: hourlyCap,
+ capacity: buckets[0].capacity,
+ refillPerSecond: buckets[0].refillPerSecond,
+ })
+
+ const parkedAt: number[] = []
+ for (let i = 0; i < 4; i++) {
+ const denied = await enforcedService.executeSendEmail(invocation)
+ expect(denied.finished).toBe(false)
+ parkedAt.push(denied.invocation.queueScheduledAt!.toMillis())
+ }
+ // Distinct slots one token interval apart, not a herd at the shared horizon.
+ for (let i = 1; i < parkedAt.length; i++) {
+ const gapMs = parkedAt[i] - parkedAt[i - 1]
+ expect(gapMs).toBeGreaterThan(9_000)
+ expect(gapMs).toBeLessThan(11_000)
+ }
+
+ // A second team's buckets are cold, so its send goes straight out. Tier caps
+ // isolate per team; the capped team's backlog must not reach anyone else.
+ const otherTeam = (await createTestTeamFixture(hub.postgres)).team
+ await insertIntegration(hub.postgres, otherTeam.id, {
+ id: otherTeam.id + 1,
+ kind: 'email',
+ config: {
+ email: '[email protected]',
+ name: 'Test User',
+ domain: 'posthog.com',
+ verified: true,
+ provider: 'ses',
+ },
+ })
+ const other = createExampleInvocation({ team_id: otherTeam.id, id: 'function-other-team' })
+ other.id = 'invocation-other-team'
+ other.state.vmState = { stack: [] } as any
+ other.queueParameters = createEmailParams()
+ other.queueParameters.from = { integrationId: otherTeam.id + 1 }
+ const otherResult = await enforcedService.executeSendEmail(other)
+
+ expect(otherResult.finished).toBe(true)
+ expect(enforcedSendSpy).toHaveBeenCalledTimes(1)
+ })
})
})
describe('native email sending with maildev', () => {
diff --git a/nodejs/src/cdp/services/messaging/email.service.ts b/nodejs/src/cdp/services/messaging/email.service.ts
index dd7a50fc0177..7a5f21baa7bc 100644
--- a/nodejs/src/cdp/services/messaging/email.service.ts
+++ b/nodejs/src/cdp/services/messaging/email.service.ts
@@ -118,18 +118,6 @@ function pickTokenBucketRetryDelayMs(refillPerSecond: number): number {
const CAP_RETRY_MIN_MS = 1_000
const CAP_RETRY_MAX_MS = 60 * 60 * 1_000
-function pickCapRetryDelayMs(retryAfterMs: number | null, refillPerSecond: number): number {
- // A denial with no horizon means the limiter itself failed, not that the cap was reached.
- // Valkey recovers in seconds, but a daily cap paces in hours, so that bucket's refill is the
- // wrong clock for this wake. Use the token-bucket cadence, which has a much shorter ceiling.
- if (retryAfterMs === null) {
- return pickTokenBucketRetryDelayMs(refillPerSecond)
- }
- // The 1x-2x jitter spreads re-claims so a parked backlog does not wake on the same instant.
- const clampedMs = Math.min(Math.max(retryAfterMs, CAP_RETRY_MIN_MS), CAP_RETRY_MAX_MS)
- return Math.floor(clampedMs * (1 + Math.random()))
-}
-
// How far denied sends park. Everything at or below the top bucket is a real slot.
// Above the top bucket is overflow: the backlog is deeper than one hour of refill.
// A sustained rate up there means a team queues more email than its limit can send.
@@ -665,14 +653,20 @@ export class EmailService {
// Both buckets in one atomic claim, granted whole or not at all. A denial consumes
// nothing, so a rescheduled multi-recipient send cannot burn the partial refill on
// every retry and starve the team's other emails while never sending itself.
- const claim = await this.teamEmailRateLimiter.claimAllOrNothingPair([buckets[0], buckets[1]], requested)
+ const claim = await this.teamEmailRateLimiter.claimAllOrNothingPair(
+ [buckets[0], buckets[1]],
+ requested,
+ CAP_RETRY_MAX_MS
+ )
if (claim.granted) {
return null
}
const denied = buckets[claim.deniedIndex ?? 1]
teamEmailCapDelayedTotal.inc({ tier: String(tier), bucket: denied.name, mode })
+ const retryDelayMs = pickReservedRetryDelayMs(claim.retryAfterMs, denied.refillPerSecond, claim.reserved)
+ emailReservedParkMs.labels('team-email').observe(retryDelayMs)
return {
- retryDelayMs: pickCapRetryDelayMs(claim.retryAfterMs, denied.refillPerSecond),
+ retryDelayMs,
label: denied.label,
}
}
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
index fe8b83cceb85..3feefc2b4f05 100644
--- a/nodejs/src/cdp/services/rate-limiter/rate-limiter.service.test.ts
+++ b/nodejs/src/cdp/services/rate-limiter/rate-limiter.service.test.ts
@@ -209,7 +209,7 @@ describe('RateLimiterService', () => {
],
30
)
- expect(claim).toEqual({ granted: true, deniedIndex: null, retryAfterMs: null })
+ expect(claim).toEqual({ granted: true, deniedIndex: null, retryAfterMs: null, reserved: false })
// Both pools were charged: the remainder is all that is left to claim.
expect(await limiter.claimUpTo({ key: KEY_A, requested: 50, capacity: 50, refillPerSecond: 0 })).toBe(20)
expect(await limiter.claimUpTo({ key: KEY_B, requested: 100, capacity: 100, refillPerSecond: 0 })).toBe(70)
@@ -227,7 +227,7 @@ describe('RateLimiterService', () => {
30
)
// refillPerSecond 0 means the missing tokens never accrue, so no horizon is reported.
- expect(claim).toEqual({ granted: false, deniedIndex: 1, retryAfterMs: null })
+ expect(claim).toEqual({ granted: false, deniedIndex: 1, retryAfterMs: null, reserved: false })
expect(await limiter.claimUpTo({ key: KEY_A, requested: 50, capacity: 50, refillPerSecond: 0 })).toBe(50)
expect(await limiter.claimUpTo({ key: KEY_B, requested: 10, capacity: 10, refillPerSecond: 0 })).toBe(10)
})
@@ -242,7 +242,7 @@ describe('RateLimiterService', () => {
],
30
)
- expect(claim).toEqual({ granted: false, deniedIndex: 1, retryAfterMs: 10_000 })
+ expect(claim).toEqual({ granted: false, deniedIndex: 1, retryAfterMs: 10_000, reserved: false })
})
it('reports the slower bucket when both are short', async () => {
@@ -256,7 +256,7 @@ describe('RateLimiterService', () => {
],
30
)
- expect(claim).toEqual({ granted: false, deniedIndex: 0, retryAfterMs: 40_000 })
+ expect(claim).toEqual({ granted: false, deniedIndex: 0, retryAfterMs: 40_000, reserved: false })
})
it('fails closed when the Lua call throws', async () => {
@@ -272,7 +272,78 @@ describe('RateLimiterService', () => {
],
5
)
- expect(claim).toEqual({ granted: false, deniedIndex: null, retryAfterMs: null })
+ expect(claim).toEqual({ granted: false, deniedIndex: null, retryAfterMs: null, reserved: false })
+ })
+
+ it('hands successive reserved denials distinct, later slots, paced by the slower bucket', async () => {
+ // Both buckets are short, so the slower one (0.5/s) sets the pace. The first
+ // caller waits 40s (its missing tokens). The next one gets the slot after
+ // that, a full 60s later. Nobody wakes at the same time.
+ const buckets: [
+ { key: string; capacity: number; refillPerSecond: number },
+ { key: string; capacity: number; refillPerSecond: number },
+ ] = [
+ { key: `${KEY_A}/resv`, capacity: 10, refillPerSecond: 2 },
+ { key: `${KEY_B}/resv`, capacity: 10, refillPerSecond: 0.5 },
+ ]
+ const first = await limiter.claimAllOrNothingPair(buckets, 30, 600_000)
+ const second = await limiter.claimAllOrNothingPair(buckets, 30, 600_000)
+
+ expect(first.granted).toBe(false)
+ expect(first.reserved).toBe(true)
+ // First in line pays only the 40s shortfall, not a full 60s slot.
+ expect(first.retryAfterMs).toBe(40_000)
+ expect(second.reserved).toBe(true)
+ expect(second.retryAfterMs!).toBeGreaterThan(first.retryAfterMs!)
+ expect(second.retryAfterMs!).toBeLessThanOrEqual(100_000)
+ })
+
+ it('stops advancing the reservation cursor at the horizon', async () => {
+ const buckets: [
+ { key: string; capacity: number; refillPerSecond: number },
+ { key: string; capacity: number; refillPerSecond: number },
+ ] = [
+ { key: `${KEY_A}/resv-cap`, capacity: 50, refillPerSecond: 0 },
+ { key: `${KEY_B}/resv-cap`, capacity: 10, refillPerSecond: 2 },
+ ]
+ // The first slot (10s) fits inside the 20s horizon. The next one would not,
+ // so everyone after the first just gets "come back in 20s" with no slot.
+ const first = await limiter.claimAllOrNothingPair(buckets, 30, 20_000)
+ const second = await limiter.claimAllOrNothingPair(buckets, 30, 20_000)
+ const third = await limiter.claimAllOrNothingPair(buckets, 30, 20_000)
+
+ expect(first.retryAfterMs).toBe(10_000)
+ expect(first.reserved).toBe(true)
+ expect(second.retryAfterMs).toBe(20_000)
+ expect(second.reserved).toBe(false)
+ expect(third.retryAfterMs).toBe(20_000)
+ expect(third.reserved).toBe(false)
+ })
+
+ it('keeps one reservation line when the slower bucket changes', async () => {
+ const buckets: [
+ { key: string; capacity: number; refillPerSecond: number },
+ { key: string; capacity: number; refillPerSecond: number },
+ ] = [
+ { key: `${KEY_A}/line`, capacity: 10, refillPerSecond: 2 },
+ { key: `${KEY_B}/line`, capacity: 100, refillPerSecond: 0.5 },
+ ]
+ // The second bucket still covers the request, so the first one (10s
+ // shortfall, 15s spacing) sets the pace for the first two denials.
+ const first = await limiter.claimAllOrNothingPair(buckets, 30, 600_000)
+ const second = await limiter.claimAllOrNothingPair(buckets, 30, 600_000)
+
+ // Now drain the second bucket so it becomes the slower one. The line has
+ // to continue behind the parked sends. A cursor kept only on the bucket
+ // that is currently slower would start a fresh line here and hand this
+ // send a slot at ~16s, ahead of the send already parked at ~25s.
+ await limiter.claimUpTo({ key: buckets[1].key, requested: 78, capacity: 100, refillPerSecond: 0.5 })
+ const third = await limiter.claimAllOrNothingPair(buckets, 30, 600_000)
+
+ expect(first.reserved).toBe(true)
+ expect(second.retryAfterMs!).toBeGreaterThan(first.retryAfterMs!)
+ expect(third.reserved).toBe(true)
+ expect(third.retryAfterMs!).toBeGreaterThan(second.retryAfterMs!)
})
})
diff --git a/nodejs/src/cdp/services/rate-limiter/rate-limiter.service.ts b/nodejs/src/cdp/services/rate-limiter/rate-limiter.service.ts
index b173da9fa119..1d4b178a0574 100644
--- a/nodejs/src/cdp/services/rate-limiter/rate-limiter.service.ts
+++ b/nodejs/src/cdp/services/rate-limiter/rate-limiter.service.ts
@@ -138,21 +138,30 @@ return {0, math.ceil(slotAt - now), 1}
// ARGV[1] = requested tokens (integer)
// ARGV[2..4] = capacity, refill/sec, TTL seconds for KEYS[1]
// ARGV[5..7] = capacity, refill/sec, TTL seconds for KEYS[2]
-// Returns {1, 0, 0} when granted. On denial: {0, i, retryAfterMs}, where i is the
-// first bucket (1-based) that came up short and retryAfterMs is how long until BOTH
-// buckets have their missing tokens back (the slower one decides). That is a lower
-// bound, not a reservation: other callers can take those tokens first, so the wake
-// still has to claim. A bucket that never refills has no horizon, and then the
-// denial reports none.
+// ARGV[8] = reserve-on-deny horizon in ms; 0 disables reservation.
+// Returns {1, 0, 0, 0} when granted. On denial: {0, i, retryAfterMs, reserved},
+// where i is the first bucket (1-based) that came up short. With ARGV[8] = 0,
+// retryAfterMs is only how long until BOTH buckets have their missing tokens back
+// (the slower one decides). Every denied caller gets that same answer, so they all
+// wake together. With ARGV[8] > 0 the denial also books the caller a slot on the
+// slowest short bucket, the same ticket-at-a-counter idea as the claim-up-to script
+// above: the first denied caller waits only for the missing tokens, everyone after
+// gets the next slot, one interval later. Slots never go out past ARGV[8]; past
+// that the caller gets ARGV[8] back with reserved=0 and asks again when it wakes.
+// A slot is a place in line, not a promise: the wake still has to claim. A bucket
+// that never refills has no horizon, and then the denial reports none and books
+// nothing.
const CLAIM_ALL_OR_NOTHING_PAIR_LUA = `
local time = redis.call('TIME')
local now = tonumber(time[1]) * 1000 + math.floor(tonumber(time[2]) / 1000)
local requested = tonumber(ARGV[1])
+local reserveOnDenyMaxMs = tonumber(ARGV[8])
local available = {}
local deniedIndex = 0
local retryAfterMs = 0
local horizonKnown = true
+local slowRefill = 0
for i = 1, 2 do
local capacity = tonumber(ARGV[(i - 1) * 3 + 2])
local refillPerSecond = tonumber(ARGV[(i - 1) * 3 + 3])
@@ -179,6 +188,7 @@ for i = 1, 2 do
local bucketRetryMs = math.ceil(((requested - avail) / refillPerSecond) * 1000)
if bucketRetryMs > retryAfterMs then
retryAfterMs = bucketRetryMs
+ slowRefill = refillPerSecond
end
else
horizonKnown = false
@@ -189,9 +199,45 @@ end
if deniedIndex > 0 then
if not horizonKnown then
- return {0, deniedIndex, 0}
+ return {0, deniedIndex, 0, 0}
end
- return {0, deniedIndex, retryAfterMs}
+ if reserveOnDenyMaxMs <= 0 then
+ return {0, deniedIndex, retryAfterMs, 0}
+ end
+ -- First in line: wait only for the pair's shortfall (that is retryAfterMs).
+ -- Behind someone: take the slot after theirs, one interval of the slowest
+ -- bucket later. Same idea as the claim-up-to script above.
+ -- There is ONE line for the pair, kept on both keys: the base is the later of
+ -- the two cursors and the new slot is written back to both. Keeping the line
+ -- on only the currently slower bucket splits it when the slower bucket
+ -- changes (hourly runs dry first, then daily), and a fresh line lets new
+ -- arrivals cut ahead of sends that are already parked.
+ local rawResvA = redis.call('hget', KEYS[1], 'resv')
+ local rawResvB = redis.call('hget', KEYS[2], 'resv')
+ local base = now
+ if rawResvA ~= false and tonumber(rawResvA) > base then
+ base = tonumber(rawResvA)
+ end
+ if rawResvB ~= false and tonumber(rawResvB) > base then
+ base = tonumber(rawResvB)
+ end
+ local slotAt
+ if base > now then
+ slotAt = base + (requested / slowRefill) * 1000
+ else
+ slotAt = now + retryAfterMs
+ end
+ if slotAt - now < retryAfterMs then
+ slotAt = now + retryAfterMs
+ end
+ if slotAt - now > reserveOnDenyMaxMs then
+ return {0, deniedIndex, reserveOnDenyMaxMs, 0}
+ end
+ redis.call('hset', KEYS[1], 'resv', slotAt)
+ redis.call('expire', KEYS[1], tonumber(ARGV[4]))
+ redis.call('hset', KEYS[2], 'resv', slotAt)
+ redis.call('expire', KEYS[2], tonumber(ARGV[7]))
+ return {0, deniedIndex, math.ceil(slotAt - now), 1}
end
for i = 1, 2 do
@@ -200,7 +246,7 @@ for i = 1, 2 do
redis.call('expire', KEYS[i], ttlSeconds)
end
-return {1, 0, 0}
+return {1, 0, 0, 0}
`
export interface RateLimiterConfig {
@@ -328,14 +374,15 @@ export class RateLimiterService {
}
/**
- * Atomically claim `requested` tokens from BOTH buckets, or neither. A denial consumes
- * nothing, so a caller that retries a multi-token claim cannot drain the buckets while never
+ * Atomically claim `requested` tokens from BOTH buckets, or neither. A denial consumes no
+ * tokens, so a caller that retries a multi-token claim cannot drain the buckets while never
* succeeding. Returns which bucket denied (index into `buckets`), or null when granted.
- * A denial also carries `retryAfterMs`, the time until every short bucket's refill has
- * accrued its missing tokens. Both buckets are measured, so a pair that is short on the
- * hourly and the daily bucket reports the slower one. It is a lower bound (competing callers
- * may take the tokens first), so callers use it to schedule the retry, never to skip the
- * re-claim.
+ * A denial also says when to come back (`retryAfterMs`), paced by the slower of the two
+ * buckets. With `reserveOnDenyMs` = 0 that is a shared answer and every denied caller gets
+ * the same one. With `reserveOnDenyMs` > 0 the denial books the caller its own slot in
+ * line instead, like claimOrReserve does, never further out than `reserveOnDenyMs`.
+ * `reserved` tells the caller which of the two it got. A slot is a place in line, not a
+ * promise: the wake still has to claim.
* Runtime errors deny with `deniedIndex: null` and `retryAfterMs: null` — fail-closed, like
* claimUpTo.
*
@@ -346,8 +393,9 @@ export class RateLimiterService {
*/
public async claimAllOrNothingPair(
buckets: [Omit<ClaimRequest, 'requested'>, Omit<ClaimRequest, 'requested'>],
- requested: number
- ): Promise<{ granted: boolean; deniedIndex: 0 | 1 | null; retryAfterMs: number | null }> {
+ requested: number,
+ reserveOnDenyMs: number = 0
+ ): Promise<{ granted: boolean; deniedIndex: 0 | 1 | null; retryAfterMs: number | null; reserved: boolean }> {
const endTimer = claimLatency.startTimer({ limiter: this.config.name })
try {
const result = await this.valkey.useClient(
@@ -364,27 +412,31 @@ export class RateLimiterService {
String(buckets[0].ttlSeconds ?? 3600),
String(buckets[1].capacity),
String(buckets[1].refillPerSecond),
- String(buckets[1].ttlSeconds ?? 3600)
+ String(buckets[1].ttlSeconds ?? 3600),
+ String(reserveOnDenyMs)
)
)
- const [granted, deniedBucket, retryAfterMs] = Array.isArray(result) ? result.map(Number) : [NaN, NaN, NaN]
+ const [granted, deniedBucket, retryAfterMs, reserved] = Array.isArray(result)
+ ? result.map(Number)
+ : [NaN, NaN, NaN, 0]
if (granted !== 0 && granted !== 1) {
logger.warn('🪙', `RateLimiterService(${this.config.name}) pair claim returned invalid result`, {
keys: [buckets[0].key, buckets[1].key],
raw: result,
})
claimCounter.inc({ limiter: this.config.name, result: 'valkey_error' })
- return { granted: false, deniedIndex: null, retryAfterMs: null }
+ return { granted: false, deniedIndex: null, retryAfterMs: null, reserved: false }
}
claimCounter.inc({ limiter: this.config.name, result: granted === 1 ? 'granted_full' : 'denied' })
return granted === 1
- ? { granted: true, deniedIndex: null, retryAfterMs: null }
+ ? { granted: true, deniedIndex: null, retryAfterMs: null, reserved: false }
: {
granted: false,
deniedIndex: deniedBucket === 2 ? 1 : 0,
retryAfterMs: Number.isFinite(retryAfterMs) && retryAfterMs > 0 ? retryAfterMs : null,
+ reserved: reserved === 1,
}
} catch (err) {
logger.warn('🪙', `RateLimiterService(${this.config.name}) pair claim threw`, {
@@ -392,7 +444,7 @@ export class RateLimiterService {
error: String(err),
})
claimCounter.inc({ limiter: this.config.name, result: 'valkey_error' })
- return { granted: false, deniedIndex: null, retryAfterMs: null }
+ return { granted: false, deniedIndex: null, retryAfterMs: null, reserved: false }
} finally {
endTimer()
}
diff --git a/nodejs/src/cdp/services/rate-limiter/rate-limiter.valkey.integration.test.ts b/nodejs/src/cdp/services/rate-limiter/rate-limiter.valkey.integration.test.ts
index b242d722ad00..20bb408223fc 100644
--- a/nodejs/src/cdp/services/rate-limiter/rate-limiter.valkey.integration.test.ts
+++ b/nodejs/src/cdp/services/rate-limiter/rate-limiter.valkey.integration.test.ts
@@ -41,6 +41,6 @@ describe('RateLimiterService on Valkey Cluster', () => {
const limiter = new RateLimiterService(valkeyPool, { name: 'team-email-cluster-test' })
const claim = await limiter.claimAllOrNothingPair([buckets[0], buckets[1]], 10)
- expect(claim).toEqual({ granted: true, deniedIndex: null, retryAfterMs: null })
+ expect(claim).toEqual({ granted: true, deniedIndex: null, retryAfterMs: null, reserved: false })
})
})
diff --git a/nodejs/src/cdp/workflows-e2e.serial.test.ts b/nodejs/src/cdp/workflows-e2e.serial.test.ts
index 7c416424c34d..cfd6175c3a61 100644
--- a/nodejs/src/cdp/workflows-e2e.serial.test.ts
+++ b/nodejs/src/cdp/workflows-e2e.serial.test.ts
@@ -42,7 +42,7 @@ import { UUIDT } from '~/common/utils/utils'
import { createCdpConsumerDeps } from '~/tests/helpers/cdp'
import { waitForExpect } from '~/tests/helpers/expectations'
import { TEST_KAFKA_TOPICS, ensureKafkaTopics } from '~/tests/helpers/kafka'
-import { getFirstTeam, resetBehavioralCohortsDatabase, resetTestDatabase } from '~/tests/helpers/sql'
+import { createTeam, getFirstTeam, resetBehavioralCohortsDatabase, resetTestDatabase } from '~/tests/helpers/sql'
import { Hub, Team } from '../../src/types'
import { createRedisV2PoolFromConfig } from '../common/redis/redis-v2'
@@ -3611,6 +3611,155 @@ describe('Workflows E2E (email queue)', () => {
}
})
+ it("a team over its tier cap does not hold up another team's emails", async () => {
+ // Two teams, each with one email workflow. Team A sits on a tier that allows
+ // 2 emails per hour and gets 6 sends queued; team B is on a high tier with 3
+ // sends. The whole pipeline is real and the tier caps are enforced: B's emails
+ // must all go out while A's over-cap sends park on future slots from A's own
+ // refill, without cycling.
+ //
+ // The default email worker was built with the caps off, so swap in one that
+ // enforces them. Tier 0 allows 2/hour, tier 1 is effectively unlimited.
+ await emailWorker.stop()
+ hub.EMAIL_TEAM_SENDING_CAP_MODE = 'enforce'
+ hub.EMAIL_TEAM_SENDING_CAP_HOURLY_BY_TIER = '2,10000'
+ hub.EMAIL_TEAM_SENDING_CAP_DAILY_BY_TIER = '48,240000'
+ const enforcedQueue = new CyclotronJobQueuePostgresV2(hub.CONSUMER_BATCH_SIZE, hub)
+ emailWorker = new CdpCyclotronWorkerEmail(hub, deps, enforcedQueue)
+ await emailWorker.start()
+
+ // The tier buckets are keyed by team id and the test Redis keeps data between
+ // runs, so team A's bucket must start full or a previous run drains this one.
+ const capValkey = 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,
+ })
+ await deleteKeysWithPrefix(capValkey, '@posthog/team-email-rate-hour')
+ await deleteKeysWithPrefix(capValkey, '@posthog/team-email-rate-day')
+
+ // Team A has no config row and defaults to tier 0. Team B gets tier 1.
+ const teamBId = await createTeam(hub.postgres, team.organization_id)
+ await hub.postgres.query(
+ PostgresUse.COMMON_WRITE,
+ `INSERT INTO workflows_teamworkflowsconfig
+ (team_id, capture_workflows_engagement_events, email_tracking_consent_mode,
+ email_sending_suspension_reason, ses_tenant_sending_status, email_sending_tier)
+ VALUES ($1, false, 'off', '', '', 1)`,
+ [teamBId],
+ 'set-team-email-tier'
+ )
+ await insertIntegration(hub.postgres, teamBId, {
+ id: 2,
+ kind: 'email',
+ config: {
+ email: '[email protected]',
+ name: 'Test Sender',
+ domain: 'posthog.com',
+ verified: true,
+ provider: 'maildev',
+ },
+ })
+
+ const buildFlow = (teamId: number, integrationId: number, triggerEvent: string, recipient: string): HogFlow =>
+ new FixtureHogFlowBuilder()
+ .withTeamId(teamId)
+ .withStatus('active')
+ .withExitCondition('exit_only_at_end')
+ .withWorkflow({
+ actions: {
+ trigger: {
+ type: 'trigger',
+ config: { type: 'event', ...eventNameFilter(triggerEvent) },
+ },
+ email_1: {
+ type: 'function_email',
+ config: {
+ template_id: 'template-workflows-e2e-email',
+ inputs: {
+ email: {
+ value: {
+ to: { email: recipient, name: 'Recipient' },
+ from: { integrationId, email: '[email protected]' },
+ subject: `To ${recipient}`,
+ text: 'Test text',
+ html: '<p>Test html</p>',
+ },
+ },
+ },
+ },
+ },
+ exit: { type: 'exit', config: {} },
+ },
+ edges: [
+ { from: 'trigger', to: 'email_1', type: 'continue' },
+ { from: 'email_1', to: 'exit', type: 'continue' },
+ ],
+ })
+ .build()
+
+ const flowA = buildFlow(team.id, 1, 'tier_a', '[email protected]')
+ const flowB = buildFlow(teamBId, 2, 'tier_b', '[email protected]')
+ await insertHogFlow(hub.postgres, flowA)
+ await insertHogFlow(hub.postgres, flowB)
+
+ const teamBGlobals = (i: number): HogFunctionInvocationGlobals =>
+ createHogExecutionGlobals({
+ project: { id: teamBId } as any,
+ event: {
+ uuid: new UUIDT().toString(),
+ event: 'tier_b',
+ distinct_id: `person_tier_b_${i}`,
+ properties: {},
+ timestamp: '2024-09-03T09:00:00Z',
+ } as any,
+ })
+ const events = [
+ ...Array.from({ length: 6 }, (_, i) =>
+ createGlobals({
+ event: 'tier_a',
+ uuid: new UUIDT().toString(),
+ distinct_id: `person_tier_a_${i}`,
+ } as any)
+ ),
+ ...Array.from({ length: 3 }, (_, i) => teamBGlobals(i)),
+ ]
+ const { backgroundTask } = await eventsConsumer.processBatch(events)
+ await backgroundTask
+
+ // Team B's 3 runs finish end to end; team A gets its 2 in-budget sends out.
+ await waitForExpect(async () => {
+ const jobs = await queryCyclotronJobs()
+ const bJobs = jobs.filter((j: any) => j.function_id === flowB.id)
+ expect(bJobs.length).toBe(3)
+ expect(bJobs.every((j: any) => j.status === 'completed')).toBe(true)
+
+ const sent = mockProducerObserver
+ .getProducedKafkaMessagesForTopic(KAFKA_APP_METRICS_2)
+ .filter((m: any) => m.value.app_source === 'hog_flow')
+ .filter((m: any) => m.value.metric_name === 'email_sent')
+ .reduce((sum: number, m: any) => sum + m.value.count, 0)
+ expect(sent).toBe(5)
+ }, 15000)
+
+ // Team A's 4 over-cap sends are parked far in the future (its refill is one
+ // token per 30 minutes), each dequeued once on the email queue.
+ const jobs = await queryCyclotronJobs()
+ const parkedA = jobs.filter(
+ (j: any) => j.function_id === flowA.id && j.queue_name === 'email' && j.status === 'available'
+ )
+ expect(parkedA.length).toBe(4)
+ for (const job of parkedA) {
+ expect(new Date(job.scheduled).getTime()).toBeGreaterThan(Date.now() + 25 * 60 * 1000)
+ expect(job.transition_count).toBeLessThanOrEqual(4)
+ }
+ })
+
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