: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
fix(workflows): put both team email cap keys in one valkey cluster slot (#96122)
Meikel Ratz020af2d4dbd8
diff --git a/nodejs/src/cdp/services/messaging/email.service.ts b/nodejs/src/cdp/services/messaging/email.service.tsindex 21829ffc137a..81385170da33 100644--- a/nodejs/src/cdp/services/messaging/email.service.ts+++ b/nodejs/src/cdp/services/messaging/email.service.ts@@ -167,11 +167,14 @@ type TeamEmailCapBucket = {label: string}-function teamEmailCapBuckets(teamId: number, hourlyCap: number, dailyCap: number): TeamEmailCapBucket[] {+// The `{teamId}` hash tag puts both bucket keys in the same cluster slot. Enforce mode claims+// both keys in one Lua call (claimAllOrNothingPair), and clustered Valkey rejects a multi-key+// call whose keys hash to different slots with a CROSSSLOT error.+export function teamEmailCapBuckets(teamId: number, hourlyCap: number, dailyCap: number): TeamEmailCapBucket[] {return [{name: 'hour',- key: `@posthog/team-email-rate-hour/${teamId}`,+ key: `@posthog/team-email-rate-hour/{${teamId}}`,capacity: hourlyCap,refillPerSecond: hourlyCap / 3600,ttlSeconds: TEAM_EMAIL_HOUR_BUCKET_TTL_SECONDS,@@ -179,7 +182,7 @@ function teamEmailCapBuckets(teamId: number, hourlyCap: number, dailyCap: number},{name: 'day',- key: `@posthog/team-email-rate-day/${teamId}`,+ key: `@posthog/team-email-rate-day/{${teamId}}`,capacity: dailyCap,refillPerSecond: dailyCap / 86400,ttlSeconds: TEAM_EMAIL_DAY_BUCKET_TTL_SECONDS,diff --git a/nodejs/src/cdp/services/rate-limiter/rate-limiter.service.ts b/nodejs/src/cdp/services/rate-limiter/rate-limiter.service.tsindex 74f5990577cc..272248d86ba9 100644--- a/nodejs/src/cdp/services/rate-limiter/rate-limiter.service.ts+++ b/nodejs/src/cdp/services/rate-limiter/rate-limiter.service.ts@@ -240,6 +240,11 @@ export class RateLimiterService {* nothing, 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.* Runtime errors deny with `deniedIndex: null` — fail-closed, like claimUpTo.+ *+ * On clustered Valkey the two keys must hash to the same slot (give them the same `{...}`+ * hash tag), because the Lua script touches both keys in one call and the cluster rejects+ * cross-slot calls with a CROSSSLOT error. Single-node Valkey accepts any pair of keys, so+ * tests and local dev do not catch a violation; production does, on every claim.*/public async claimAllOrNothingPair(buckets: [Omit<ClaimRequest, 'requested'>, Omit<ClaimRequest, 'requested'>],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.tsnew file mode 100644index 000000000000..ffe9f225b336--- /dev/null+++ b/nodejs/src/cdp/services/rate-limiter/rate-limiter.valkey.integration.test.ts@@ -0,0 +1,46 @@+import Redis from 'ioredis'++import { RedisClient, RedisClientPipeline, RedisV2 } from '~/common/redis/redis-v2'++import { teamEmailCapBuckets } from '../messaging/email.service'+import { RateLimiterService } from './rate-limiter.service'++const host = process.env.CDP_VALKEY_HOST ?? '127.0.0.1'+const port = Number(process.env.CDP_VALKEY_PORT ?? 6390)++describe('RateLimiterService on Valkey Cluster', () => {+ let valkey: Redis.Redis+ let valkeyPool: RedisV2++ beforeAll(async () => {+ valkey = new Redis(port, host, { maxRetriesPerRequest: 1 })+ await valkey.ping()+ valkeyPool = {+ useClient: async (_options, callback) => callback(valkey as unknown as RedisClient),+ usePipeline: async (_options, callback) => {+ const pipeline = valkey.pipeline() as RedisClientPipeline+ callback(pipeline)+ return pipeline.exec()+ },+ }+ })++ afterAll(async () => {+ await valkey.quit()+ })++ it('pair-claims the team email cap buckets without a cross-slot rejection', async () => {+ // Prove the backing store enforces cluster key-slot rules. Without this, swapping the+ // compose service for a non-cluster Valkey would make the claim below pass vacuously.+ await expect(valkey.mget('rate-limiter-test-key-a', 'rate-limiter-test-key-b')).rejects.toThrow('CROSSSLOT')++ // A fresh team id per run keeps the buckets cold, so a full grant is the only correct+ // outcome. The cluster container keeps data between local runs.+ const teamId = Math.floor(Math.random() * 1_000_000_000)+ const buckets = teamEmailCapBuckets(teamId, 50, 100)+ 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 })+ })+})