: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(error-tracking): per-team project-wide rate limit (#57773)
Aleksander Błaszkiewicz432f4213b9fa
diff --git a/nodejs/src/common/services/keyed-rate-limiter.service.ts b/nodejs/src/common/services/keyed-rate-limiter.service.tsindex bc2889058dc3..ab8af3d5f81b 100644--- a/nodejs/src/common/services/keyed-rate-limiter.service.ts+++ b/nodejs/src/common/services/keyed-rate-limiter.service.ts@@ -20,10 +20,14 @@ export interface KeyedRateLimiterConfig {* production keys when sharing a Redis.*/name: string- /** Default bucket params used when a request doesn't specify its own. */- bucketSize: number- refillRate: number- ttlSeconds: number+ /**+ * Default bucket params used when a request doesn't specify its own.+ * Optional — callers that always supply per-request overrides can omit them.+ * `rateLimitArgs` throws if a request reaches Redis without either source.+ */+ bucketSize?: number+ refillRate?: number+ ttlSeconds?: number}export interface KeyedRateLimitRequest {@@ -63,14 +67,15 @@ export class KeyedRateLimiterService {private rateLimitArgs(req: KeyedRateLimitRequest): [string, number, number, number, number, number] {const nowSeconds = Math.round(Date.now() / 1000)- return [- `${this.keyPrefix}/${req.id}`,- nowSeconds,- req.cost,- req.bucketSize ?? this.config.bucketSize,- req.refillRate ?? this.config.refillRate,- req.ttlSeconds ?? this.config.ttlSeconds,- ]+ const bucketSize = req.bucketSize ?? this.config.bucketSize+ const refillRate = req.refillRate ?? this.config.refillRate+ const ttlSeconds = req.ttlSeconds ?? this.config.ttlSeconds+ if (bucketSize == null || refillRate == null || ttlSeconds == null) {+ throw new Error(+ `KeyedRateLimiterService(${this.config.name}): missing bucketSize/refillRate/ttlSeconds for ${req.id}`+ )+ }+ return [`${this.keyPrefix}/${req.id}`, nowSeconds, req.cost, bucketSize, refillRate, ttlSeconds]}public async rateLimitMany(requests: KeyedRateLimitRequest[]): Promise<[string, KeyedRateLimit][]> {@@ -78,6 +83,14 @@ export class KeyedRateLimiterService {return []}+ const bucketSizes = requests.map((req) => {+ const bucketSize = req.bucketSize ?? this.config.bucketSize+ if (bucketSize == null) {+ throw new Error(`KeyedRateLimiterService(${this.config.name}): missing bucketSize for ${req.id}`)+ }+ return bucketSize+ })+const res = await this.redis.usePipeline({ name: `keyed-rate-limiter:${this.config.name}`, failOpen: true },(pipeline) => {@@ -91,15 +104,12 @@ export class KeyedRateLimiterService {// failOpen swallowed an error — treat all as not rate limited so we// don't drop ingestion just because Redis blipped. Reflect each// request's own (potentially overridden) bucketSize in the response.- return requests.map((req) => [- req.id,- { tokens: req.bucketSize ?? this.config.bucketSize, isRateLimited: false },- ])+ return requests.map((req, i) => [req.id, { tokens: bucketSizes[i], isRateLimited: false }])}return requests.map((req, index) => {const [tokenRes] = getRedisPipelineResults(res, index, 1)- const tokensAfter = tokenRes[1]?.[1] ?? req.bucketSize ?? this.config.bucketSize+ const tokensAfter = tokenRes[1]?.[1] ?? bucketSizes[index]return [req.id,{diff --git a/nodejs/src/ingestion/error-tracking/config.ts b/nodejs/src/ingestion/error-tracking/config.tsindex 8c209cfdcefa..ca69a8984cfb 100644--- a/nodejs/src/ingestion/error-tracking/config.ts+++ b/nodejs/src/ingestion/error-tracking/config.ts@@ -45,10 +45,6 @@ export type ErrorTrackingConsumerConfig = {ERROR_TRACKING_RATE_LIMITER_REDIS_HOST: stringERROR_TRACKING_RATE_LIMITER_REDIS_PORT: numberERROR_TRACKING_RATE_LIMITER_REDIS_TLS: boolean- /** Token bucket capacity (events per key burst). */- ERROR_TRACKING_RATE_LIMITER_BUCKET_SIZE: number- /** Token bucket replenish rate (events per second). */- ERROR_TRACKING_RATE_LIMITER_REFILL_RATE: number/** TTL in seconds for the Redis bucket key. */ERROR_TRACKING_RATE_LIMITER_TTL_SECONDS: number@@ -78,8 +74,6 @@ export function getDefaultErrorTrackingConsumerConfig(): ErrorTrackingConsumerCoERROR_TRACKING_RATE_LIMITER_REDIS_HOST: '',ERROR_TRACKING_RATE_LIMITER_REDIS_PORT: 6379,ERROR_TRACKING_RATE_LIMITER_REDIS_TLS: false,- ERROR_TRACKING_RATE_LIMITER_BUCKET_SIZE: 100_000,- ERROR_TRACKING_RATE_LIMITER_REFILL_RATE: 1_000,ERROR_TRACKING_RATE_LIMITER_TTL_SECONDS: 86_400,INGESTION_PIPELINE: null,INGESTION_LANE: null,diff --git a/nodejs/src/ingestion/error-tracking/error-tracking-consumer.test.ts b/nodejs/src/ingestion/error-tracking/error-tracking-consumer.test.tsindex dd9efac9e795..97ed1c2cdf0d 100644--- a/nodejs/src/ingestion/error-tracking/error-tracking-consumer.test.ts+++ b/nodejs/src/ingestion/error-tracking/error-tracking-consumer.test.ts@@ -7,6 +7,7 @@ import { KafkaConsumer } from '~/kafka/consumer/consumer-v1'import { getFirstTeam, resetTestDatabase } from '~/tests/helpers/sql'import { Hub, PipelineEvent, Team } from '~/types'import { closeHub, createHub } from '~/utils/db/hub'+import { ErrorTrackingSettingsManager } from '~/utils/error-tracking-settings-manager'import { parseJSON } from '~/utils/json-parse'import { UUIDT } from '~/utils/utils'import { PersonRepository } from '~/worker/ingestion/persons/repositories/person-repository'@@ -161,8 +162,6 @@ describe('ErrorTrackingConsumer', () => {rateLimiterRedisHost: hub.ERROR_TRACKING_RATE_LIMITER_REDIS_HOST,rateLimiterRedisPort: hub.ERROR_TRACKING_RATE_LIMITER_REDIS_PORT,rateLimiterRedisTls: hub.ERROR_TRACKING_RATE_LIMITER_REDIS_TLS,- rateLimiterBucketSize: hub.ERROR_TRACKING_RATE_LIMITER_BUCKET_SIZE,- rateLimiterRefillRate: hub.ERROR_TRACKING_RATE_LIMITER_REFILL_RATE,rateLimiterTtlSeconds: hub.ERROR_TRACKING_RATE_LIMITER_TTL_SECONDS,fallbackRedisUrl: hub.REDIS_URL,rateLimiterRedisPoolMinSize: hub.REDIS_POOL_MIN_SIZE,@@ -200,6 +199,7 @@ describe('ErrorTrackingConsumer', () => {),}),teamManager: hub.teamManager,+ errorTrackingSettingsManager: new ErrorTrackingSettingsManager(hub.postgres),hogTransformer: mockHogTransformer,groupTypeManager: hub.groupTypeManager,redisPool: hub.redisPool,diff --git a/nodejs/src/ingestion/error-tracking/error-tracking-consumer.ts b/nodejs/src/ingestion/error-tracking/error-tracking-consumer.tsindex 1f65ea71550a..73bb5d6a2587 100644--- a/nodejs/src/ingestion/error-tracking/error-tracking-consumer.ts+++ b/nodejs/src/ingestion/error-tracking/error-tracking-consumer.ts@@ -8,6 +8,7 @@ import { AppMetricsAggregator } from '~/common/services/app-metrics-aggregator'import { KeyedRateLimiterService } from '~/common/services/keyed-rate-limiter.service'import { instrumentFn } from '~/common/tracing/tracing-utils'import { PluginEvent } from '~/plugin-scaffold'+import { ErrorTrackingSettingsManager } from '~/utils/error-tracking-settings-manager'import { TransformationResult } from '../../cdp/hog-transformations/hog-transformer.service'import { KafkaConsumerInterface, createKafkaConsumer } from '../../kafka/consumer'@@ -58,8 +59,6 @@ export interface ErrorTrackingConsumerOptions {rateLimiterRedisHost: stringrateLimiterRedisPort: numberrateLimiterRedisTls: boolean- rateLimiterBucketSize: number- rateLimiterRefillRate: numberrateLimiterTtlSeconds: number/** Fallback Redis URL when no dedicated host is configured. Required when rateLimiterEnabled. */fallbackRedisUrl?: string@@ -86,6 +85,8 @@ export interface ErrorTrackingHogTransformer {export interface ErrorTrackingConsumerDeps {outputs: ErrorTrackingOutputsteamManager: TeamManager+ /** Only required when the rate limiter is enabled; constructed alongside it. */+ errorTrackingSettingsManager?: ErrorTrackingSettingsManagerhogTransformer: ErrorTrackingHogTransformergroupTypeManager: GroupTypeManagerredisPool: GenericPool<Redis>@@ -195,8 +196,8 @@ export class ErrorTrackingConsumer {this.rateLimiter = new KeyedRateLimiterService({name: 'error-tracking-rate-limiter',- bucketSize: config.rateLimiterBucketSize,- refillRate: config.rateLimiterRefillRate,+ // bucketSize/refillRate are intentionally omitted — every request supplies+ // them via getBucketConfig (per-team), so service-level defaults are unused.ttlSeconds: config.rateLimiterTtlSeconds,},this.rateLimiterRedis@@ -261,6 +262,7 @@ export class ErrorTrackingConsumer {overflowRedirectService: this.overflowRedirectService,overflowLaneTTLRefreshService: this.overflowLaneTTLRefreshService,preCymbalRateLimiters: this.buildPreCymbalRateLimiterSpecs(),+ errorTrackingSettingsManager: this.rateLimiter ? this.deps.errorTrackingSettingsManager : undefined,topHog: this.topHog,})@@ -283,23 +285,27 @@ export class ErrorTrackingConsumer {rateLimiter: this.rateLimiter,appMetricsAggregator: this.rateLimiterAppMetricsAggregator,appSource: 'exceptions',- getKey: (input) => `${input.team.id}:exceptions:global`,+ // Skip rate limiting when the team hasn't opted in (no row or null value).+ // Returning null makes the rate-limiter step pass the input through as `ok()`.+ // The serializer enforces min_value=1, so a non-null value is always positive.+ getKey: (input) =>+ input.errorTrackingSettings?.projectRateLimitValue == null+ ? null+ : `${input.team.id}:exceptions:global`,getTeamId: (input) => input.team.id,reportingMode: this.config.rateLimiterReportingMode,dropReason: 'rate_limited:team_global',- // TODO: Read per-team bucket overrides from a Team Extension model- // (e.g. ErrorTrackingTeamSettings.rate_limit_bucket_size /- // .rate_limit_refill_rate). When those columns are nullable and unset,- // fall back to the env-configured defaults baked into `this.rateLimiter`.- // Wiring would look like:- // getBucketConfig: (input) => {- // const settings = (input as { team: TeamWithErrorTrackingSettings }).team- // .error_tracking_settings- // return {- // bucketSize: settings?.rate_limit_bucket_size ?? undefined,- // refillRate: settings?.rate_limit_refill_rate ?? undefined,- // }- // },+ getBucketConfig: (input) => {+ // User model: "N events per M minutes".+ // Token bucket: bucketSize=N (max burst), refillRate=N/(M*60) per second.+ const settings = input.errorTrackingSettings!+ const value = settings.projectRateLimitValue!+ const minutes = settings.projectRateLimitBucketSizeMinutes ?? 60+ return {+ bucketSize: value,+ refillRate: value / (minutes * 60),+ }+ },},// TODO: Per-exception-hash limit using a coarse pre-Cymbal fingerprint// (Cymbal's proper fingerprint is post-symbolication, so we accept adiff --git a/nodejs/src/ingestion/error-tracking/error-tracking-pipeline.ts b/nodejs/src/ingestion/error-tracking/error-tracking-pipeline.tsindex ef99f9df0ec8..e0db4c1517e8 100644--- a/nodejs/src/ingestion/error-tracking/error-tracking-pipeline.ts+++ b/nodejs/src/ingestion/error-tracking/error-tracking-pipeline.ts@@ -1,6 +1,7 @@import { Message } from 'node-rdkafka'import { PluginEvent } from '~/plugin-scaffold'+import { ErrorTrackingSettings, ErrorTrackingSettingsManager } from '~/utils/error-tracking-settings-manager'import { EventIngestionRestrictionManager } from '~/utils/event-ingestion-restrictions'import { PromiseScheduler } from '~/utils/promise-scheduler'import { TeamManager } from '~/utils/team-manager'@@ -41,6 +42,7 @@ import { createCymbalProcessingStep } from './cymbal-processing-step'import { CymbalClient } from './cymbal/client'import { ErrorTrackingHogTransformer } from './error-tracking-consumer'import { KeyedRateLimiterStepOptions, createKeyedRateLimiterStep } from './keyed-rate-limiter-step'+import { createLoadErrorTrackingSettingsStep } from './load-error-tracking-settings-step'import { createFetchPersonBatchStep } from './person-properties-step'import { createErrorTrackingPrepareEventStep } from './prepare-event-step'@@ -83,6 +85,11 @@ export interface ErrorTrackingPipelineConfig {* a `postCymbalRateLimiters` slot rather than reorder this one.*/preCymbalRateLimiters?: KeyedRateLimiterStepOptions<PreCymbalRateLimiterInput>[]+ /**+ * When provided, an error-tracking-settings load step runs before the rate limiter+ * chain so per-team overrides can be read synchronously from the input.+ */+ errorTrackingSettingsManager?: ErrorTrackingSettingsManager/** TopHog registry for metrics. */topHog: TopHogRegistry}@@ -94,6 +101,7 @@ export interface ErrorTrackingPipelineConfig {export interface PreCymbalRateLimiterInput {team: { id: number }event: PluginEvent+ errorTrackingSettings?: ErrorTrackingSettings | null}/**@@ -150,6 +158,7 @@ export function createErrorTrackingPipeline(overflowRedirectService,overflowLaneTTLRefreshService,preCymbalRateLimiters,+ errorTrackingSettingsManager,topHog,} = config@@ -184,6 +193,9 @@ export function createErrorTrackingPipeline(})),]))+ // Attach per-team error-tracking settings. No-op when the manager isn't wired+ // (rate limiter disabled) — keeps the type chain consistent regardless.+ .pipe(createLoadErrorTrackingSettingsStep(errorTrackingSettingsManager)))// Map team to context for handleIngestionWarnings, and carry// the Kafka message byte size through for Cymbal batch chunking.diff --git a/nodejs/src/ingestion/error-tracking/load-error-tracking-settings-step.test.ts b/nodejs/src/ingestion/error-tracking/load-error-tracking-settings-step.test.tsnew file mode 100644index 000000000000..9d242fa1311f--- /dev/null+++ b/nodejs/src/ingestion/error-tracking/load-error-tracking-settings-step.test.ts@@ -0,0 +1,55 @@+import { ErrorTrackingSettingsManager } from '~/utils/error-tracking-settings-manager'++import { isOkResult } from '../pipelines/results'+import { createLoadErrorTrackingSettingsStep } from './load-error-tracking-settings-step'++describe('createLoadErrorTrackingSettingsStep', () => {+ const buildManager = (+ settingsByTeam: Record<+ string,+ { projectRateLimitValue: number | null; projectRateLimitBucketSizeMinutes: number | null } | null+ >+ ): jest.Mocked<Pick<ErrorTrackingSettingsManager, 'getSettings'>> => ({+ getSettings: jest.fn((teamId: number) => Promise.resolve(settingsByTeam[String(teamId)] ?? null)),+ })++ it('attaches null when the team has no settings row', async () => {+ const manager = buildManager({ '1': null })+ const step = createLoadErrorTrackingSettingsStep(manager as unknown as ErrorTrackingSettingsManager)++ const result = await step({ team: { id: 1 } })++ expect(isOkResult(result)).toBe(true)+ if (isOkResult(result)) {+ expect(result.value.errorTrackingSettings).toBeNull()+ }+ })++ it('attaches the loaded settings', async () => {+ const manager = buildManager({+ '1': { projectRateLimitValue: 100, projectRateLimitBucketSizeMinutes: 5 },+ })+ const step = createLoadErrorTrackingSettingsStep(manager as unknown as ErrorTrackingSettingsManager)++ const result = await step({ team: { id: 1 } })++ expect(isOkResult(result)).toBe(true)+ if (isOkResult(result)) {+ expect(result.value.errorTrackingSettings).toEqual({+ projectRateLimitValue: 100,+ projectRateLimitBucketSizeMinutes: 5,+ })+ }+ })++ it('attaches null without calling the manager when no manager is provided', async () => {+ const step = createLoadErrorTrackingSettingsStep<{ team: { id: number } }>(undefined)++ const result = await step({ team: { id: 1 } })++ expect(isOkResult(result)).toBe(true)+ if (isOkResult(result)) {+ expect(result.value.errorTrackingSettings).toBeNull()+ }+ })+})diff --git a/nodejs/src/ingestion/error-tracking/load-error-tracking-settings-step.ts b/nodejs/src/ingestion/error-tracking/load-error-tracking-settings-step.tsnew file mode 100644index 000000000000..8adb78c95c93--- /dev/null+++ b/nodejs/src/ingestion/error-tracking/load-error-tracking-settings-step.ts@@ -0,0 +1,21 @@+import { ErrorTrackingSettings, ErrorTrackingSettingsManager } from '~/utils/error-tracking-settings-manager'++import { ok } from '../pipelines/results'+import { ProcessingStep } from '../pipelines/steps'++export interface LoadErrorTrackingSettingsInput {+ team: { id: number }+}++export type WithErrorTrackingSettings<T> = T & {+ errorTrackingSettings: ErrorTrackingSettings | null+}++export function createLoadErrorTrackingSettingsStep<T extends LoadErrorTrackingSettingsInput>(+ manager: ErrorTrackingSettingsManager | undefined+): ProcessingStep<T, WithErrorTrackingSettings<T>> {+ return async function loadErrorTrackingSettingsStep(input) {+ const errorTrackingSettings = manager ? await manager.getSettings(input.team.id) : null+ return ok({ ...input, errorTrackingSettings })+ }+}diff --git a/nodejs/src/servers/error-tracking-server.ts b/nodejs/src/servers/error-tracking-server.tsindex 822ea4e6042a..18cc3f9c50e1 100644--- a/nodejs/src/servers/error-tracking-server.ts+++ b/nodejs/src/servers/error-tracking-server.ts@@ -40,6 +40,7 @@ import { PluginServerService, RedisPool } from '../types'import { ServerCommands } from '../utils/commands'import { PostgresRouter } from '../utils/db/postgres'import { createRedisPoolFromConfig } from '../utils/db/redis'+import { ErrorTrackingSettingsManager } from '../utils/error-tracking-settings-manager'import { GeoIPService } from '../utils/geoip'import { logger } from '../utils/logger'import { PubSub } from '../utils/pubsub'@@ -143,6 +144,9 @@ export class ErrorTrackingServer implements NodeServer {await this.pubsub.start()const teamManager = new TeamManager(this.postgres)+ const errorTrackingSettingsManager = this.config.ERROR_TRACKING_RATE_LIMITER_ENABLED+ ? new ErrorTrackingSettingsManager(this.postgres)+ : undefined// 2. Services needed by ErrorTrackingConsumer and HogTransformerconst geoipService = new GeoIPService(this.config.MMDB_FILE_LOCATION)@@ -208,8 +212,6 @@ export class ErrorTrackingServer implements NodeServer {rateLimiterRedisHost: this.config.ERROR_TRACKING_RATE_LIMITER_REDIS_HOST,rateLimiterRedisPort: this.config.ERROR_TRACKING_RATE_LIMITER_REDIS_PORT,rateLimiterRedisTls: this.config.ERROR_TRACKING_RATE_LIMITER_REDIS_TLS,- rateLimiterBucketSize: this.config.ERROR_TRACKING_RATE_LIMITER_BUCKET_SIZE,- rateLimiterRefillRate: this.config.ERROR_TRACKING_RATE_LIMITER_REFILL_RATE,rateLimiterTtlSeconds: this.config.ERROR_TRACKING_RATE_LIMITER_TTL_SECONDS,fallbackRedisUrl: this.config.REDIS_URL,rateLimiterRedisPoolMinSize: this.config.REDIS_POOL_MIN_SIZE,@@ -218,6 +220,7 @@ export class ErrorTrackingServer implements NodeServer {{outputs,teamManager,+ errorTrackingSettingsManager,hogTransformer: createHogTransformerService(this.config, hogTransformerDeps),groupTypeManager: new GroupTypeManager(groupRepository, teamManager),redisPool: this.redisPool!,diff --git a/nodejs/src/utils/error-tracking-settings-manager.test.ts b/nodejs/src/utils/error-tracking-settings-manager.test.tsnew file mode 100644index 000000000000..31c152eb0380--- /dev/null+++ b/nodejs/src/utils/error-tracking-settings-manager.test.ts@@ -0,0 +1,96 @@+import { getFirstTeam, resetTestDatabase } from '../../tests/helpers/sql'+import { defaultConfig } from '../config/config'+import { Hub, Team } from '../types'+import { closeHub, createHub } from './db/hub'+import { PostgresRouter, PostgresUse } from './db/postgres'+import { ErrorTrackingSettingsManager } from './error-tracking-settings-manager'++describe('ErrorTrackingSettingsManager', () => {+ let hub: Hub+ let manager: ErrorTrackingSettingsManager+ let postgres: PostgresRouter+ let teamId: Team['id']+ let fetchSpy: jest.SpyInstance++ beforeEach(async () => {+ const now = Date.now()+ jest.spyOn(Date, 'now').mockImplementation(() => now)++ await resetTestDatabase()+ hub = await createHub()++ postgres = new PostgresRouter(defaultConfig)+ manager = new ErrorTrackingSettingsManager(postgres)+ const team = await getFirstTeam(hub.postgres)+ teamId = team.id+ fetchSpy = jest.spyOn(manager as any, 'fetchSettings')+ })++ afterEach(async () => {+ jest.restoreAllMocks()+ await postgres.end()+ await closeHub(hub)+ })++ const upsertSettings = async (+ targetTeamId: number,+ projectRateLimitValue: number | null,+ projectRateLimitBucketSizeMinutes: number | null+ ): Promise<void> => {+ await postgres.query(+ PostgresUse.COMMON_WRITE,+ `INSERT INTO posthog_errortrackingsettings+ (team_id, project_rate_limit_value, project_rate_limit_bucket_size_minutes,+ per_issue_rate_limit_value, per_issue_rate_limit_bucket_size_minutes)+ VALUES ($1, $2, $3, NULL, NULL)+ ON CONFLICT (team_id) DO UPDATE SET+ project_rate_limit_value = EXCLUDED.project_rate_limit_value,+ project_rate_limit_bucket_size_minutes = EXCLUDED.project_rate_limit_bucket_size_minutes`,+ [targetTeamId, projectRateLimitValue, projectRateLimitBucketSizeMinutes],+ 'upsert-test-error-tracking-settings'+ )+ }++ it('returns null when the team has no row', async () => {+ const result = await manager.getSettings(teamId)+ expect(result).toBeNull()+ })++ it('returns settings when the team has a row', async () => {+ await upsertSettings(teamId, 100, 5)++ const result = await manager.getSettings(teamId)+ expect(result).toEqual({+ projectRateLimitValue: 100,+ projectRateLimitBucketSizeMinutes: 5,+ })+ })++ it('returns null fields when row exists but values are unset', async () => {+ await upsertSettings(teamId, null, null)++ const result = await manager.getSettings(teamId)+ expect(result).toEqual({+ projectRateLimitValue: null,+ projectRateLimitBucketSizeMinutes: null,+ })+ })++ it('caches results across calls within the refresh window', async () => {+ await upsertSettings(teamId, 50, 15)++ await manager.getSettings(teamId)+ await manager.getSettings(teamId)+ await manager.getSettings(teamId)++ expect(fetchSpy).toHaveBeenCalledTimes(1)+ })++ it('coalesces concurrent lookups into a single fetch', async () => {+ await upsertSettings(teamId, 100, 5)++ await Promise.all([manager.getSettings(teamId), manager.getSettings(teamId), manager.getSettings(teamId)])++ expect(fetchSpy).toHaveBeenCalledTimes(1)+ })+})diff --git a/nodejs/src/utils/error-tracking-settings-manager.ts b/nodejs/src/utils/error-tracking-settings-manager.tsnew file mode 100644index 000000000000..99115cff2bfa--- /dev/null+++ b/nodejs/src/utils/error-tracking-settings-manager.ts@@ -0,0 +1,66 @@+import { PostgresRouter, PostgresUse } from './db/postgres'+import { LazyLoader } from './lazy-loader'++export interface ErrorTrackingSettings {+ projectRateLimitValue: number | null+ projectRateLimitBucketSizeMinutes: number | null+}++interface RawSettingsRow {+ team_id: number+ project_rate_limit_value: number | null+ project_rate_limit_bucket_size_minutes: number | null+}++export class ErrorTrackingSettingsManager {+ private lazyLoader: LazyLoader<ErrorTrackingSettings>++ constructor(private postgres: PostgresRouter) {+ this.lazyLoader = new LazyLoader({+ name: 'ErrorTrackingSettingsManager',+ refreshAgeMs: 2 * 60 * 1000,+ refreshJitterMs: 30 * 1000,+ loader: async (teamIds: string[]) => {+ return await this.fetchSettings(teamIds)+ },+ })+ }++ public async getSettings(teamId: number): Promise<ErrorTrackingSettings | null> {+ return await this.lazyLoader.get(String(teamId))+ }++ private async fetchSettings(teamIds: string[]): Promise<Record<string, ErrorTrackingSettings | null>> {+ const numericTeamIds = teamIds.map(Number).filter((id) => !isNaN(id) && id > 0)++ const result: Record<string, ErrorTrackingSettings | null> = {}+ for (const id of teamIds) {+ result[id] = null+ }++ if (numericTeamIds.length === 0) {+ return result+ }++ const queryResult = await this.postgres.query<RawSettingsRow>(+ PostgresUse.COMMON_READ,+ `SELECT+ team_id,+ project_rate_limit_value,+ project_rate_limit_bucket_size_minutes+ FROM posthog_errortrackingsettings+ WHERE team_id = ANY($1)`,+ [numericTeamIds],+ 'fetch-error-tracking-settings'+ )++ for (const row of queryResult.rows) {+ result[String(row.team_id)] = {+ projectRateLimitValue: row.project_rate_limit_value,+ projectRateLimitBucketSizeMinutes: row.project_rate_limit_bucket_size_minutes,+ }+ }++ return result+ }+}