Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

set TTL to stream key

Thiago Araujo da Silva7247e3a24a49
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.md
index 17d9486a73..7b61d97053 100644
--- a/backend/CLAUDE.md
+++ b/backend/CLAUDE.md
@@ -421,14 +421,19 @@ Separate from the OpenTelemetry metrics above. `src/services/telemetry/telemetry
- **Never discover buffered events by pattern.** The previous layout wrote one Redis key per event and the cron found them with `getKeysByPattern` per (event type, bucket), so each run cost `events × buckets` full keyspace walks — 240 walks over a ~440k-key keyspace, ~73s of Redis engine CPU every 10 minutes, and it grew every time an event was added to the aggregation list. The stream layout is read by key, so the cost tracks the number of pending events instead of the size of the keyspace. Adding an event type to `POSTHOG_AGGREGATED_EVENTS` must stay free of keyspace scans.
- **A `distinctId` must always hash to the same bucket.** Each shard is aggregated independently, so a `distinctId` split across shards produces one aggregated PostHog event per shard instead of one overall.
-Draining is at-least-once: a shard is trimmed (`XTRIM MINID`) only after its batch has been handed to the PostHog client, so a run that throws before that point retries the whole batch on the next tick. One run drains at most 50k entries per shard, so a backlog is worked off over several ticks instead of being pulled into the cron's memory at once.
+Draining is at-least-once: a shard is trimmed (`XTRIM MINID`) only after its batch has been handed to the PostHog client, so a run that throws before that point retries the whole batch on the next tick. One run drains at most 50k entries per shard, so a backlog is worked off over several ticks instead of being pulled into the cron's memory at once. That ceiling bounds the footprint of one shard; `BUCKET_CONCURRENCY` bounds how many of them are in flight, so the two multiply and both have to stay low. Raising either buys wall-clock the run does not need, since it is Redis-RTT-bound over 240 mostly-small shards and finishes well inside the cron's 8-minute handler timeout.
**Two independent bounds keep a shard from growing without limit, and both are load-bearing:**
- **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 stands in for the TTL the pre-stream per-event keys carried, and it is why a broken drain costs 30 minutes of product analytics instead of unbounded Redis memory.
+- **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 **removing an event type from that list orphans its shards** — nothing trims them and nothing expires them. Leave the event in the list for one release so the cron drains it, or delete `telemetry-agg-stream:<event>:*` by hand; the same applies to lowering the bucket count, and to rolling back past this layout. Nothing reads the pre-stream keys, so a deploy that changes this layout drops whatever is still buffered — acceptable for product analytics, and the reason there is no migration path to maintain.
+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:
+
+- **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.
+- **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.
### Database Configuration
diff --git a/backend/src/services/telemetry/telemetry-service.test.ts b/backend/src/services/telemetry/telemetry-service.test.ts
index 117864bb9e..b75b939e35 100644
--- a/backend/src/services/telemetry/telemetry-service.test.ts
+++ b/backend/src/services/telemetry/telemetry-service.test.ts
@@ -40,6 +40,7 @@ vi.mock("posthog-node", () => ({
import { POSTHOG_AGGREGATED_EVENTS, telemetryServiceFactory } from "./telemetry-service";
const RETENTION_MS = 30 * 60 * 1000;
+const KEY_TTL_SECONDS = 60 * 60;
const BUCKET_COUNT = 30;
const SHARD_COUNT = POSTHOG_AGGREGATED_EVENTS.length * BUCKET_COUNT;
@@ -68,6 +69,7 @@ const createHarness = () => {
const keyStore = {
incrementBy: vi.fn<(key: string, value: number) => Promise<number>>(async () => 1),
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>
>(async () => "1-0"),
@@ -244,6 +246,78 @@ describe("telemetry aggregated event storage", () => {
expect(retentionTrims(keyStore)).toHaveLength(SHARD_COUNT);
});
+ test("bounds how many shards it holds in memory at once", async () => {
+ const { keyStore, telemetryService } = createHarness();
+
+ // The per-shard collection ceiling only bounds the cron's footprint if the number of shards
+ // in flight is bounded too, and nothing else in the run observes that.
+ let inFlight = 0;
+ let peakInFlight = 0;
+ keyStore.streamCollect.mockImplementation(async () => {
+ inFlight += 1;
+ peakInFlight = Math.max(peakInFlight, inFlight);
+ await Promise.resolve();
+ inFlight -= 1;
+ return collectResult([pulledEvent()]);
+ });
+
+ await telemetryService.processAggregatedEvents();
+
+ expect(keyStore.streamCollect).toHaveBeenCalledTimes(SHARD_COUNT);
+ expect(peakInFlight).toBeGreaterThan(0);
+ expect(peakInFlight).toBeLessThanOrEqual(2);
+ });
+
+ test("refreshes the key expiry on every shard so an orphaned shard self-cleans", async () => {
+ const { keyStore, telemetryService } = createHarness();
+
+ await telemetryService.processAggregatedEvents();
+
+ const { calls } = keyStore.setExpiry.mock;
+ expect(calls).toHaveLength(SHARD_COUNT);
+ expect(new Set(calls.map(([key]) => key)).size).toBe(SHARD_COUNT);
+ // The TTL only ever reaps a shard this run no longer visits. On a shard that is still written,
+ // the age trim has to be what drops entries, so the TTL must outlive the retention window.
+ for (const [, ttlSeconds] of calls) {
+ expect(ttlSeconds).toBe(KEY_TTL_SECONDS);
+ expect(ttlSeconds * 1000).toBeGreaterThan(RETENTION_MS);
+ }
+ });
+
+ test("refreshes the key expiry even when publishing fails", async () => {
+ const { keyStore, telemetryService } = createHarness();
+
+ keyStore.streamCollect.mockResolvedValueOnce(collectResult([pulledEvent()]));
+ postHogClient.capture.mockImplementationOnce(() => {
+ throw new Error("posthog down");
+ });
+
+ await telemetryService.processAggregatedEvents();
+
+ expect(drainTrims(keyStore)).toHaveLength(0);
+ expect(keyStore.setExpiry).toHaveBeenCalledTimes(SHARD_COUNT);
+ });
+
+ test("drains a shard whose expiry refresh fails", async () => {
+ const { keyStore, telemetryService } = createHarness();
+ const bucketId = telemetryService.getBucketForDistinctId("user-1");
+ const streamKey = `telemetry-agg-stream:${PostHogEventTypes.SecretPulled}:${bucketId}`;
+
+ keyStore.setExpiry.mockImplementation(async (key) => {
+ if (key === streamKey) throw new Error("redis hiccup");
+ return 1;
+ });
+ keyStore.streamCollect.mockImplementation(async (key) =>
+ key === streamKey ? collectResult([pulledEvent()], "3-0") : { entries: [], lastId: null }
+ );
+
+ await telemetryService.processAggregatedEvents();
+
+ expect(postHogClient.capture).toHaveBeenCalledTimes(1);
+ expect(retentionTrims(keyStore)).toHaveLength(SHARD_COUNT);
+ expect(drainTrims(keyStore)).toEqual([[streamKey, "3-0", true]]);
+ });
+
test("drains a shard whose retention trim fails", async () => {
const { keyStore, telemetryService } = createHarness();
const bucketId = telemetryService.getBucketForDistinctId("user-1");
diff --git a/backend/src/services/telemetry/telemetry-service.ts b/backend/src/services/telemetry/telemetry-service.ts
index cefb65e437..7fcd530dc2 100644
--- a/backend/src/services/telemetry/telemetry-service.ts
+++ b/backend/src/services/telemetry/telemetry-service.ts
@@ -54,6 +54,7 @@ const TELEMETRY_EVENT_STREAM_BATCH_SIZE = 10_000;
const TELEMETRY_EVENT_STREAM_COLLECT_CEILING = 50_000;
const TELEMETRY_EVENT_STREAM_MAX_ENTRIES = 100_000;
const TELEMETRY_EVENT_STREAM_RETENTION_MS = 30 * 60 * 1000;
+const TELEMETRY_EVENT_STREAM_KEY_TTL_SECONDS = 60 * 60;
type AggregatedEventData = Record<string, unknown>;
type SingleEventData = {
@@ -68,7 +69,7 @@ export type TTelemetryServiceFactory = ReturnType<typeof telemetryServiceFactory
export type TTelemetryServiceFactoryDep = {
keyStore: Pick<
TKeyStoreFactory,
- "incrementBy" | "setItemWithExpiryNX" | "streamAdd" | "streamCollect" | "streamTrim"
+ "incrementBy" | "setItemWithExpiryNX" | "setExpiry" | "streamAdd" | "streamCollect" | "streamTrim"
>;
licenseService: Pick<TLicenseServiceFactory, "getInstanceType" | "getPlan">;
orgDAL: Pick<TOrgDALFactory, "findOrgById">;
@@ -466,9 +467,10 @@ To opt into telemetry, you can set "TELEMETRY_ENABLED=true" within the environme
return aggregatedData;
};
- const parseEventPayloads = (payloads: (string | null)[], context: string): SingleEventData[] => {
+ const parseEventPayloads = (entries: [string, string[]][], context: string): SingleEventData[] => {
const parsed: SingleEventData[] = [];
- for (const payload of payloads) {
+ for (const [, fields] of entries) {
+ const payload = fields[1];
if (payload) {
try {
parsed.push(JSON.parse(payload) as SingleEventData);
@@ -561,11 +563,37 @@ To opt into telemetry, you can set "TELEMETRY_ENABLED=true" within the environme
}
};
+ const collectShardEvents = async (streamKey: string, eventType: string, bucketId: string) => {
+ const { entries, lastId } = await keyStore.streamCollect(
+ streamKey,
+ TELEMETRY_EVENT_STREAM_BATCH_SIZE,
+ TELEMETRY_EVENT_STREAM_COLLECT_CEILING
+ );
+
+ if (entries.length >= TELEMETRY_EVENT_STREAM_COLLECT_CEILING) {
+ logger.warn(
+ `Telemetry aggregation hit the collection ceiling for bucket ${bucketId} of ${eventType} [collected=${entries.length}] [ceiling=${TELEMETRY_EVENT_STREAM_COLLECT_CEILING}] [maxLen=${TELEMETRY_EVENT_STREAM_MAX_ENTRIES}] — the shard is backing up; the excess is dropped once it ages past the retention window or the stream hits its MAXLEN cap`
+ );
+ }
+
+ return {
+ events: parseEventPayloads(entries, `event=${eventType} bucket=${bucketId}`),
+ collected: entries.length,
+ lastId
+ };
+ };
+
const processBucketEvents = async (eventType: string, bucketId: string, orgsIdentifyAttempted: Set<string>) => {
if (!postHog) return 0;
const streamKey = KeyStorePrefixes.TelemetryAggregatedEventStream(eventType, bucketId);
+ try {
+ await keyStore.setExpiry(streamKey, TELEMETRY_EVENT_STREAM_KEY_TTL_SECONDS);
+ } catch (error) {
+ logger.error(error, `Failed to refresh key expiry on bucket ${bucketId} for ${eventType}`);
+ }
+
try {
await keyStore.streamTrim(streamKey, `${Date.now() - TELEMETRY_EVENT_STREAM_RETENTION_MS}-0`);
} catch (error) {
@@ -573,24 +601,9 @@ To opt into telemetry, you can set "TELEMETRY_ENABLED=true" within the environme
}
try {
- const { entries, lastId } = await keyStore.streamCollect(
- streamKey,
- TELEMETRY_EVENT_STREAM_BATCH_SIZE,
- TELEMETRY_EVENT_STREAM_COLLECT_CEILING
- );
-
- if (entries.length === 0 || !lastId) return 0;
+ const { events, collected, lastId } = await collectShardEvents(streamKey, eventType, bucketId);
- if (entries.length >= TELEMETRY_EVENT_STREAM_COLLECT_CEILING) {
- logger.warn(
- `Telemetry aggregation hit the collection ceiling for bucket ${bucketId} of ${eventType} [collected=${entries.length}] [ceiling=${TELEMETRY_EVENT_STREAM_COLLECT_CEILING}] [maxLen=${TELEMETRY_EVENT_STREAM_MAX_ENTRIES}] — the shard is backing up; the excess is dropped once it ages past the retention window or the stream hits its MAXLEN cap`
- );
- }
-
- const events = parseEventPayloads(
- entries.map(([, fields]) => fields[1]),
- `event=${eventType} bucket=${bucketId}`
- );
+ if (collected === 0 || !lastId) return 0;
await publishAggregatedEvents(eventType, events, orgsIdentifyAttempted);
@@ -604,7 +617,7 @@ To opt into telemetry, you can set "TELEMETRY_ENABLED=true" within the environme
}
};
- const BUCKET_CONCURRENCY = 5;
+ const BUCKET_CONCURRENCY = 2;
const processAggregatedEvents = async () => {
if (!postHog) return;