Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
expire on add
Thiago Araujo da Silvaba1f4149685d
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.mdindex 2a14cd31fc..d28cc2e3b5 100644--- a/backend/CLAUDE.md+++ b/backend/CLAUDE.md@@ -428,9 +428,14 @@ Draining is at-least-once: a shard is trimmed (`XTRIM MINID`) only after the Pos- **Count**, on the write path — `MAXLEN ~` 100k entries per shard.- **Age**, at the top of every cron run — each shard is trimmed to a 30-minute retention window before it is read. This trim sits *outside* the drain's error scope deliberately: a publish path that throws on every tick still has to age entries out, or the shard parks at its `MAXLEN` cap with nothing bounding how long buffered analytics sits in Redis. It is why a broken drain costs 30 minutes of product analytics instead of unbounded Redis memory.-Shards are reached only by iterating `POSTHOG_AGGREGATED_EVENTS` × the 30 buckets, so a shard stops being trimmed the moment it leaves that product: removing an event type from the list, lowering the bucket count, or rolling back past this layout all orphan live shards. **The cron therefore refreshes a 1-hour `EXPIRE` on every shard it visits**, which is what reaps those orphans. Two properties make that safe to rely on:+Shards are reached only by iterating `POSTHOG_AGGREGATED_EVENTS` × the 30 buckets, so a shard stops being trimmed the moment it leaves that product: removing an event type from the list, lowering the bucket count, or rolling back past this layout all orphan live shards. **Every shard therefore carries a 1-hour `EXPIRE`**, which is what reaps those orphans. It is set two ways, and both are needed:-- **The TTL must stay above the retention window.** `XADD` neither clears nor refreshes a key's TTL, so on a shard that is still being written the expiry is a second, coarser deadline racing the age trim. At 1 hour against 30 minutes the age trim always wins, and the TTL only ever fires on a shard the cron no longer visits. Shortening it toward the retention window, or lengthening the cron's 10-minute interval past it, would start deleting shards out from under live writers.+- **On the write path**, in the same `MULTI` as the `XADD`, so a shard has an age bound from the moment it is created. Relying on the cron alone leaves a window where a freshly created shard has no TTL at all — and an instance whose cron never runs (a rollback, an event type dropped from the list, telemetry disabled on the reader side) would keep that shard forever.+- **On every cron run**, refreshed on each shard it visits, so a shard the drain is still working keeps its deadline pushed out.++Two properties make the TTL safe to rely on:++- **It must stay above the retention window.** On a shard that is still being written the expiry is a second, coarser deadline racing the age trim. At 1 hour against 30 minutes the age trim always wins, and the TTL only ever fires on a shard that has gone quiet and that the cron no longer visits. Shortening it toward the retention window, or lengthening the cron's 10-minute interval past it, would start deleting shards out from under live writers.- **It reaps, it does not migrate.** An orphaned shard's buffered entries are dropped, not drained. To hand an event type off cleanly, leave it in `POSTHOG_AGGREGATED_EVENTS` for one release so the cron empties it first.Nothing reads the pre-stream `telemetry-event-*` keys, so a deploy that changes this layout drops whatever is still buffered. That is acceptable for product analytics, and it is the reason there is no migration path to maintain.diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.tsindex de93917fc5..82df95222c 100644--- a/backend/src/keystore/keystore.ts+++ b/backend/src/keystore/keystore.ts@@ -278,7 +278,13 @@ export type TKeyStoreFactory = {listRemove: (key: string, count: number, value: string) => Promise<number>;listLength: (key: string) => Promise<number>;// stream operations- streamAdd: (key: string, id: string, fieldValue: Record<string, string>, maxLen?: number) => Promise<string | null>;+ streamAdd: (+ key: string,+ id: string,+ fieldValue: Record<string, string>,+ maxLen?: number,+ expiryInSeconds?: number+ ) => Promise<string | null>;streamRange: (key: string, start: string, end: string, count?: number) => Promise<[string, string[]][]>;streamTrim: (key: string, minId: string, inclusive?: boolean) => Promise<number>;streamCollect: (@@ -526,12 +532,31 @@ export const keyStoreFactory = (const listLength = async (key: string) => pickPrimaryOrSecondaryRedis(primaryRedis, redisReadReplicas).llen(key);// Stream operations- const streamAdd = async (key: string, id: string, fieldValue: Record<string, string>, maxLen = 1_000_000) => {+ const streamAdd = async (+ key: string,+ id: string,+ fieldValue: Record<string, string>,+ maxLen = 1_000_000,+ expiryInSeconds?: number+ ) => {const args: string[] = [];for (const [field, value] of Object.entries(fieldValue)) {args.push(field, value);}- return primaryRedis.xadd(key, "MAXLEN", "~", maxLen, id, ...args);++ if (!expiryInSeconds) {+ return primaryRedis.xadd(key, "MAXLEN", "~", maxLen, id, ...args);+ }++ const results = await primaryRedis+ .multi()+ .xadd(key, "MAXLEN", "~", maxLen, id, ...args)+ .expire(key, expiryInSeconds)+ .exec();++ const [addError, entryId] = results?.[0] ?? [null, null];+ if (addError) throw addError;+ return (entryId as string | null) ?? null;};const streamRange = async (key: string, start: string, end: string, count?: number) => {diff --git a/backend/src/services/telemetry/telemetry-service.test.ts b/backend/src/services/telemetry/telemetry-service.test.tsindex 44ee8f99b4..6d73372279 100644--- a/backend/src/services/telemetry/telemetry-service.test.ts+++ b/backend/src/services/telemetry/telemetry-service.test.ts@@ -72,7 +72,13 @@ const createHarness = () => {setItemWithExpiryNX: vi.fn<() => Promise<"OK" | null>>(async () => null),setExpiry: vi.fn<(key: string, expiryInSeconds: number) => Promise<number>>(async () => 1),streamAdd: vi.fn<- (key: string, id: string, fieldValue: Record<string, string>, maxLen?: number) => Promise<string | null>+ (+ key: string,+ id: string,+ fieldValue: Record<string, string>,+ maxLen?: number,+ expiryInSeconds?: number+ ) => Promise<string | null>>(async () => "1-0"),streamCollect: vi.fn<(key: string) => Promise<{ entries: [string, string[]][]; lastId: string | null }>>(async () => ({ entries: [], lastId: null })@@ -101,12 +107,15 @@ describe("telemetry aggregated event storage", () => {await telemetryService.sendPostHogEvents(pulledEvent() as never);expect(keyStore.streamAdd).toHaveBeenCalledTimes(1);- const [key, id, fields, maxLen] = keyStore.streamAdd.mock.calls[0];+ const [key, id, fields, maxLen, expiryInSeconds] = keyStore.streamAdd.mock.calls[0];expect(key).toBe(`telemetry-agg-stream:${PostHogEventTypes.SecretPulled}:${telemetryService.getBucketForDistinctId("user-1")}`);expect(id).toBe("*");expect(maxLen).toBeGreaterThan(0);+ // The shard has to carry an age bound from its very first append: nothing else gives it one+ // until the aggregation cron next visits the key, and that visit may never come.+ expect(expiryInSeconds).toBe(KEY_TTL_SECONDS);expect(JSON.parse(fields.data)).toMatchObject({distinctId: "user-1",event: PostHogEventTypes.SecretPulled,diff --git a/backend/src/services/telemetry/telemetry-service.ts b/backend/src/services/telemetry/telemetry-service.tsindex 1483b1a78d..6805dfcf76 100644--- a/backend/src/services/telemetry/telemetry-service.ts+++ b/backend/src/services/telemetry/telemetry-service.ts@@ -335,7 +335,8 @@ To opt into telemetry, you can set "TELEMETRY_ENABLED=true" within the environme...(resolvedOrgName ? { organizationName: resolvedOrgName } : {})})},- TELEMETRY_EVENT_STREAM_MAX_ENTRIES+ TELEMETRY_EVENT_STREAM_MAX_ENTRIES,+ TELEMETRY_EVENT_STREAM_KEY_TTL_SECONDS);} else {// Skip groupIdentify entirely when the event is marked anonymous.