Skip to content

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

remove dlq

Thiago Araujo da Silva5cf15a880b41
diff --git a/backend/src/db/migrations/20260522191822_audit-log-stream-outbox.ts b/backend/src/db/migrations/20260522191822_audit-log-stream-outbox.ts
index b546f5c1a4..8be98d654c 100644
--- a/backend/src/db/migrations/20260522191822_audit-log-stream-outbox.ts
+++ b/backend/src/db/migrations/20260522191822_audit-log-stream-outbox.ts
@@ -44,33 +44,9 @@ export async function up(knex: Knex): Promise<void> {
}
await createOnUpdateTrigger(knex, TableName.AuditLogStreamOutbox);
-
- if (!(await knex.schema.hasTable(TableName.AuditLogStreamOutboxDlq))) {
- await knex.schema.createTable(TableName.AuditLogStreamOutboxDlq, (t) => {
- t.bigIncrements("id").primary();
- t.bigInteger("originalAuditLogStreamOutboxId").notNullable();
- t.uuid("streamId").notNullable();
- t.uuid("orgId").notNullable();
- t.jsonb("payload").notNullable();
- t.integer("attempts").notNullable();
- t.text("lastError");
- t.timestamp("originalCreatedAt", { useTz: true }).notNullable();
- t.timestamp("failedAt", { useTz: true }).notNullable().defaultTo(knex.fn.now());
-
- t.foreign("streamId").references("id").inTable(TableName.AuditLogStream).onDelete("CASCADE");
- t.foreign("orgId").references("id").inTable(TableName.Organization).onDelete("CASCADE");
-
- // FK referencing columns: Postgres does not auto-index these, so cascade
- // deletes (stream/org removal) would otherwise seq-scan the DLQ.
- t.index(["streamId"]);
- t.index(["orgId"]);
- t.index(["failedAt"]);
- });
- }
}
export async function down(knex: Knex): Promise<void> {
await dropOnUpdateTrigger(knex, TableName.AuditLogStreamOutbox);
- await knex.schema.dropTableIfExists(TableName.AuditLogStreamOutboxDlq);
await knex.schema.dropTableIfExists(TableName.AuditLogStreamOutbox);
}
diff --git a/backend/src/db/schemas/audit-log-stream-outbox-dlq.ts b/backend/src/db/schemas/audit-log-stream-outbox-dlq.ts
deleted file mode 100644
index d9c0db63a9..0000000000
--- a/backend/src/db/schemas/audit-log-stream-outbox-dlq.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-// Code generated by automation script, DO NOT EDIT.
-// Automated by pulling database and generating zod schema
-// To update. Just run npm run generate:schema
-// Written by akhilmhdh.
-
-import { z } from "zod";
-
-import { TImmutableDBKeys } from "./models";
-
-export const AuditLogStreamOutboxDlqSchema = z.object({
- id: z.coerce.number(),
- originalAuditLogStreamOutboxId: z.coerce.number(),
- streamId: z.string().uuid(),
- orgId: z.string().uuid(),
- payload: z.unknown(),
- attempts: z.number(),
- lastError: z.string().nullable().optional(),
- originalCreatedAt: z.date(),
- failedAt: z.date()
-});
-
-export type TAuditLogStreamOutboxDlq = z.infer<typeof AuditLogStreamOutboxDlqSchema>;
-export type TAuditLogStreamOutboxDlqInsert = Omit<z.input<typeof AuditLogStreamOutboxDlqSchema>, TImmutableDBKeys>;
-export type TAuditLogStreamOutboxDlqUpdate = Partial<
- Omit<z.input<typeof AuditLogStreamOutboxDlqSchema>, TImmutableDBKeys>
->;
diff --git a/backend/src/db/schemas/index.ts b/backend/src/db/schemas/index.ts
index 8445b4aabb..7f931cb0a5 100644
--- a/backend/src/db/schemas/index.ts
+++ b/backend/src/db/schemas/index.ts
@@ -23,7 +23,6 @@ export * from "./approval-request-step-eligible-approvers";
export * from "./approval-request-steps";
export * from "./approval-requests";
export * from "./audit-log-stream-outbox";
-export * from "./audit-log-stream-outbox-dlq";
export * from "./audit-log-streams";
export * from "./audit-logs";
export * from "./auth-token-sessions";
diff --git a/backend/src/db/schemas/models.ts b/backend/src/db/schemas/models.ts
index d8517c4a79..0acc73ebcd 100644
--- a/backend/src/db/schemas/models.ts
+++ b/backend/src/db/schemas/models.ts
@@ -141,7 +141,6 @@ export enum TableName {
AuditLog = "audit_logs",
AuditLogStream = "audit_log_streams",
AuditLogStreamOutbox = "audit_log_stream_outbox",
- AuditLogStreamOutboxDlq = "audit_log_stream_outbox_dlq",
GitAppInstallSession = "git_app_install_sessions",
GitAppOrg = "git_app_org",
SecretScanningGitRisk = "secret_scanning_git_risks",
diff --git a/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-dal.ts b/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-dal.ts
index 48cbd368af..a0d5225d14 100644
--- a/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-dal.ts
+++ b/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-dal.ts
@@ -6,11 +6,7 @@ import { DatabaseError } from "@app/lib/errors";
import { chunkArray } from "@app/lib/fn";
import { logger } from "@app/lib/logger";
-import {
- AuditLogStreamOutboxStatus,
- TAuditLogStreamOutboxRow,
- TFailedStreamRow
-} from "./audit-log-stream-outbox-types";
+import { AuditLogStreamOutboxStatus, TAuditLogStreamOutboxRow } from "./audit-log-stream-outbox-types";
export type TAuditLogStreamOutboxDALFactory = ReturnType<typeof auditLogStreamOutboxDALFactory>;
@@ -114,53 +110,17 @@ export const auditLogStreamOutboxDALFactory = (db: TDbClient) => {
}
};
- // Move exhausted rows out of the hot table into the DLQ in one transaction —
- // copies the payload + audit history, then deletes the original rows so the
- // worker never picks them up again.
- const moveToDlq = async (rows: TAuditLogStreamOutboxRow[], errorMessage: string, tx?: Knex) => {
- if (rows.length === 0) return;
- try {
- const exec = async (trx: Knex) => {
- const dlqRows = rows.map((row) => ({
- originalAuditLogStreamOutboxId: row.id,
- streamId: row.streamId,
- orgId: row.orgId,
- payload: JSON.stringify(row.payload),
- attempts: row.attempts + 1,
- lastError: errorMessage,
- originalCreatedAt: row.createdAt
- }));
- await trx.batchInsert(TableName.AuditLogStreamOutboxDlq, dlqRows);
- await trx(TableName.AuditLogStreamOutbox)
- .whereIn(
- "id",
- rows.map((row) => row.id)
- )
- .del();
- };
-
- if (tx) {
- await exec(tx);
- } else {
- await db.transaction(exec);
- }
- } catch (error) {
- throw new DatabaseError({ error, name: "AuditLogStreamOutbox: moveToDlq" });
- }
- };
-
// Commit the outcome of a chunked delivery for a single claimed batch in one
// transaction:
- // - successIds: rows that reached the provider — flip to 'delivered' (kept
- // around as the dedup guard against a re-fanout from a
- // retried ingest tick; pruned later by the cleanup cron).
- // - retriable: rows whose chunk failed but can still retry — flip to 'retry'
- // with attempt+1.
- // - exhausted: rows whose chunk failed and used up MAX_ATTEMPTS — move to DLQ.
- // Failed rows arrive as TFailedStreamRow so each carries the errorMessage from
- // its own chunk (different chunks of one claim can fail with different errors).
- // Exhausted rows are grouped by errorMessage and moved to the DLQ one group at
- // a time so each DLQ row records what actually broke for it.
+ // - successIds: rows that reached the provider — flip to 'delivered' (kept
+ // around as the dedup guard against a re-fanout from a
+ // retried ingest tick; pruned later by the cleanup cron).
+ // - retriable: rows whose chunk failed but can still retry — flip to 'retry'
+ // with attempt+1.
+ // - exhaustedIds: rows whose chunk failed and used up MAX_ATTEMPTS — deleted
+ // (dropped). There is no DLQ; the caller logs + emits a metric
+ // for these before committing, so the event is gone once the
+ // row is removed.
//
// Folding all three outcomes into a single transaction means a crash between
// the writes can't leave the claim half-applied (e.g. some rows flipped to
@@ -170,10 +130,10 @@ export const auditLogStreamOutboxDALFactory = (db: TDbClient) => {
const commitDeliveryResult = async (input: {
successIds: number[];
retriable: { groups: { ids: number[]; nextRetryDelayMs: number }[] } | null;
- exhausted: TFailedStreamRow[];
+ exhaustedIds: number[];
}) => {
const retriableCount = input.retriable?.groups.reduce((n, g) => n + g.ids.length, 0) ?? 0;
- if (input.successIds.length === 0 && retriableCount === 0 && input.exhausted.length === 0) return;
+ if (input.successIds.length === 0 && retriableCount === 0 && input.exhaustedIds.length === 0) return;
try {
await db.transaction(async (tx) => {
if (input.successIds.length > 0) {
@@ -185,17 +145,8 @@ export const auditLogStreamOutboxDALFactory = (db: TDbClient) => {
await markBatchForRetry(group.ids, group.nextRetryDelayMs, tx);
}
}
- if (input.exhausted.length > 0) {
- const rowsByError = new Map<string, TAuditLogStreamOutboxRow[]>();
- for (const { row, errorMessage } of input.exhausted) {
- const existing = rowsByError.get(errorMessage);
- if (existing) existing.push(row);
- else rowsByError.set(errorMessage, [row]);
- }
- for (const [errorMessage, rows] of rowsByError) {
- // eslint-disable-next-line no-await-in-loop
- await moveToDlq(rows, errorMessage, tx);
- }
+ if (input.exhaustedIds.length > 0) {
+ await tx(TableName.AuditLogStreamOutbox).whereIn("id", input.exhaustedIds).del();
}
});
} catch (error) {
@@ -208,12 +159,12 @@ export const auditLogStreamOutboxDALFactory = (db: TDbClient) => {
// Treat a stale claim as a consumed attempt — a payload that crashes the worker
// is indistinguishable from one that fails delivery, and either way must respect
// MAX_ATTEMPTS so a poison pill can't loop forever. Rows that hit the cap are
- // moved to DLQ in the same transaction.
+ // dropped (deleted) in the same transaction; there is no DLQ. The caller logs +
+ // emits a metric for the dropped count.
const recoverStaleClaims = async (
thresholdMs: number,
maxAttempts: number
- ): Promise<{ retried: number; movedToDlq: number }> => {
- const errorMessage = "stale-claim-recovered: worker did not release lock before threshold";
+ ): Promise<{ retried: number; dropped: { streamId: string; orgId: string }[] }> => {
try {
return await db.transaction(async (tx) => {
const staleRows = await tx(TableName.AuditLogStreamOutbox)
@@ -223,7 +174,7 @@ export const auditLogStreamOutboxDALFactory = (db: TDbClient) => {
.skipLocked()
.select<TAuditLogStreamOutboxRow[]>("*");
- if (staleRows.length === 0) return { retried: 0, movedToDlq: 0 };
+ if (staleRows.length === 0) return { retried: 0, dropped: [] };
const exhausted: TAuditLogStreamOutboxRow[] = [];
const retriable: TAuditLogStreamOutboxRow[] = [];
@@ -250,10 +201,18 @@ export const auditLogStreamOutboxDALFactory = (db: TDbClient) => {
}
if (exhausted.length > 0) {
- await moveToDlq(exhausted, errorMessage, tx);
+ await tx(TableName.AuditLogStreamOutbox)
+ .whereIn(
+ "id",
+ exhausted.map((row) => row.id)
+ )
+ .del();
}
- return { retried: retriable.length, movedToDlq: exhausted.length };
+ return {
+ retried: retriable.length,
+ dropped: exhausted.map((row) => ({ streamId: row.streamId, orgId: row.orgId }))
+ };
});
} catch (error) {
throw new DatabaseError({ error, name: "AuditLogStreamOutbox: recoverStaleClaims" });
@@ -293,34 +252,6 @@ export const auditLogStreamOutboxDALFactory = (db: TDbClient) => {
}
};
- const deleteDlqOlderThan = async (retentionMs: number, batchSize = 10_000, maxBatches = 100): Promise<number> => {
- try {
- let total = 0;
- for (let i = 0; i < maxBatches; i += 1) {
- // eslint-disable-next-line no-await-in-loop
- const deleted = await db(TableName.AuditLogStreamOutboxDlq)
- .whereIn("id", function selectExpiredIds() {
- void this.from(TableName.AuditLogStreamOutboxDlq)
- .select("id")
- .whereRaw(`"failedAt" < NOW() - (? || ' milliseconds')::INTERVAL`, [retentionMs])
- .limit(batchSize);
- })
- .del();
-
- total += deleted;
- if (deleted < batchSize) break;
- if (i === maxBatches - 1) {
- logger.warn(
- `audit-log-stream-outbox: deleteDlqOlderThan hit the batch ceiling [maxBatches=${maxBatches}] [batchSize=${batchSize}] [deleted=${total}] — expired DLQ entries remain unpruned`
- );
- }
- }
- return total;
- } catch (error) {
- throw new DatabaseError({ error, name: "AuditLogStreamOutbox: deleteDlqOlderThan" });
- }
- };
-
const findStreamsWithOverdueRows = async (): Promise<{ streamId: string; orgId: string; provider: string }[]> => {
try {
return await db(`${TableName.AuditLogStreamOutbox} as o`)
@@ -341,7 +272,6 @@ export const auditLogStreamOutboxDALFactory = (db: TDbClient) => {
commitDeliveryResult,
recoverStaleClaims,
findStreamsWithOverdueRows,
- deleteDeliveredOlderThan,
- deleteDlqOlderThan
+ deleteDeliveredOlderThan
};
};
diff --git a/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-queue.ts b/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-queue.ts
index eb3d0c07a3..5c26c150dc 100644
--- a/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-queue.ts
+++ b/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-queue.ts
@@ -12,10 +12,10 @@ const OUTBOX_WORKER_CONCURRENCY = 5;
const STALE_CLAIM_SWEEPER_CRON = "*/5 * * * *";
const STALE_CLAIM_SWEEPER_RUN_HASH_TTL_S = 60 * 60;
-// Cleanup cadence. Runs every 15 min to prune both 'delivered' outbox rows and DLQ
-// entries past their respective retention windows. Tighter than the old hourly cadence
-// so deletes come in smaller, more frequent bursts (less autovacuum/bloat pressure) and
-// the outbox table tracks the now-shorter delivered retention closely.
+// Cleanup cadence. Runs every 15 min to prune 'delivered' outbox rows past their
+// retention window. Tighter than the old hourly cadence so deletes come in smaller,
+// more frequent bursts (less autovacuum/bloat pressure) and the outbox table tracks
+// the now-shorter delivered retention closely.
const CLEANUP_CRON = "*/15 * * * *";
// Per-fire hash dedup window — only needs to outlive a single run + retries, so 1h is
// ample for a 15-min cron (the hash id is keyed per scheduled fire, so this never gates
@@ -27,7 +27,7 @@ export type TAuditLogStreamOutboxQueueDep = {
cronJob: TCronJobFactory;
auditLogStreamOutboxService: Pick<
TAuditLogStreamOutboxServiceFactory,
- "drainStream" | "sweepStaleClaims" | "pruneDeliveredRows" | "pruneDlqEntries"
+ "drainStream" | "sweepStaleClaims" | "pruneDeliveredRows"
>;
};
@@ -68,14 +68,10 @@ export const auditLogStreamOutboxQueueFactory = ({
pattern: CLEANUP_CRON,
runHashTtlS: CLEANUP_RUN_HASH_TTL_S,
handler: async () => {
- const results = await Promise.allSettled([
- auditLogStreamOutboxService.pruneDeliveredRows(),
- auditLogStreamOutboxService.pruneDlqEntries()
- ]);
- for (const result of results) {
- if (result.status === "rejected") {
- logger.error(result.reason as Error, "audit-log-stream-outbox: cleanup prune failed");
- }
+ try {
+ await auditLogStreamOutboxService.pruneDeliveredRows();
+ } catch (error) {
+ logger.error(error as Error, "audit-log-stream-outbox: cleanup prune failed");
}
}
});
diff --git a/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-service.test.ts b/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-service.test.ts
index 0284d2edb1..bf0a05e174 100644
--- a/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-service.test.ts
+++ b/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-service.test.ts
@@ -2,11 +2,7 @@ import { beforeEach, describe, expect, test, vi } from "vitest";
import { LogProvider, StreamMode } from "../audit-log-stream/audit-log-stream-enums";
import { auditLogStreamOutboxServiceFactory } from "./audit-log-stream-outbox-service";
-import {
- AuditLogStreamOutboxStatus,
- TAuditLogStreamOutboxRow,
- TFailedStreamRow
-} from "./audit-log-stream-outbox-types";
+import { AuditLogStreamOutboxStatus, TAuditLogStreamOutboxRow } from "./audit-log-stream-outbox-types";
const STREAM_ID = "stream-1";
const ORG_ID = "org-1";
@@ -68,10 +64,9 @@ const createService = () => {
batchInsert: vi.fn(async () => undefined),
claimBatchForStream: vi.fn<(...args: unknown[]) => Promise<TAuditLogStreamOutboxRow[]>>(async () => []),
commitDeliveryResult: vi.fn<(input: unknown) => Promise<void>>(async () => undefined),
- recoverStaleClaims: vi.fn(async () => ({ retried: 0, movedToDlq: 0 })),
+ recoverStaleClaims: vi.fn(async () => ({ retried: 0, dropped: [] })),
findStreamsWithOverdueRows: vi.fn(async () => []),
- deleteDeliveredOlderThan: vi.fn<(retentionMs: number) => Promise<number>>(async () => 0),
- deleteDlqOlderThan: vi.fn<(retentionMs: number) => Promise<number>>(async () => 0)
+ deleteDeliveredOlderThan: vi.fn<(retentionMs: number) => Promise<number>>(async () => 0)
};
const auditLogStreamDAL = {
@@ -115,17 +110,18 @@ describe("audit-log-stream-outbox-service drainStream failure handling", () => {
const call = auditLogStreamOutboxDAL.commitDeliveryResult.mock.calls[0][0] as {
successIds: number[];
retriable: { groups: { ids: number[]; nextRetryDelayMs: number }[] } | null;
- exhausted: TFailedStreamRow[];
+ exhaustedIds: number[];
};
expect(call.successIds).toEqual([]);
expect(call.retriable?.groups.flatMap((g) => g.ids)).toEqual([1]);
- expect(call.exhausted).toEqual([]);
+ expect(call.exhaustedIds).toEqual([]);
});
- test("routes rows that hit MAX_ATTEMPTS to DLQ instead of retry", async () => {
+ test("drops rows that hit MAX_ATTEMPTS instead of retrying them", async () => {
const { service, auditLogStreamOutboxDAL } = createService();
- // attempts=4 → attempts+1=5 hits MAX_ATTEMPTS so the row must go to DLQ.
+ // attempts=4 → attempts+1=5 hits MAX_ATTEMPTS so the row is dropped (no DLQ):
+ // its id lands in exhaustedIds for deletion and nothing is queued for retry.
auditLogStreamOutboxDAL.claimBatchForStream
.mockResolvedValueOnce([buildRow({ attempts: 4 })])
.mockResolvedValueOnce([]);
@@ -137,12 +133,11 @@ describe("audit-log-stream-outbox-service drainStream failure handling", () => {
const call = auditLogStreamOutboxDAL.commitDeliveryResult.mock.calls[0][0] as {
successIds: number[];
retriable: { groups: { ids: number[]; nextRetryDelayMs: number }[] } | null;
- exhausted: TFailedStreamRow[];
+ exhaustedIds: number[];
};
expect(call.successIds).toEqual([]);
expect(call.retriable).toBeNull();
- expect(call.exhausted).toHaveLength(1);
- expect(call.exhausted[0].errorMessage).toEqual(expect.stringContaining(FAILURE_MESSAGE));
+ expect(call.exhaustedIds).toEqual([1]);
});
test("commits delivered rows on the success path", async () => {
@@ -157,11 +152,11 @@ describe("audit-log-stream-outbox-service drainStream failure handling", () => {
const call = auditLogStreamOutboxDAL.commitDeliveryResult.mock.calls[0][0] as {
successIds: number[];
retriable: { groups: { ids: number[]; nextRetryDelayMs: number }[] } | null;
- exhausted: TFailedStreamRow[];
+ exhaustedIds: number[];
};
expect(call.successIds).toEqual([1]);
expect(call.retriable).toBeNull();
- expect(call.exhausted).toEqual([]);
+ expect(call.exhaustedIds).toEqual([]);
});
test("stops draining after the first failed batch — does not claim another batch", async () => {
@@ -193,11 +188,11 @@ describe("audit-log-stream-outbox-service drainStream failure handling", () => {
const call = auditLogStreamOutboxDAL.commitDeliveryResult.mock.calls[0][0] as {
successIds: number[];
retriable: { groups: { ids: number[]; nextRetryDelayMs: number }[] } | null;
- exhausted: TFailedStreamRow[];
+ exhaustedIds: number[];
};
expect(call.successIds).toEqual([1]);
expect(call.retriable?.groups.flatMap((g) => g.ids)).toEqual([2]);
- expect(call.exhausted).toEqual([]);
+ expect(call.exhaustedIds).toEqual([]);
});
test("per-attempt backoff: rows at different attempts retry in separate groups with distinct delays", async () => {
@@ -220,7 +215,7 @@ describe("audit-log-stream-outbox-service drainStream failure handling", () => {
const call = auditLogStreamOutboxDAL.commitDeliveryResult.mock.calls[0][0] as {
successIds: number[];
retriable: { groups: { ids: number[]; nextRetryDelayMs: number }[] } | null;
- exhausted: TFailedStreamRow[];
+ exhaustedIds: number[];
};
const groups = call.retriable?.groups ?? [];
expect(groups).toHaveLength(2);
@@ -268,11 +263,11 @@ describe("audit-log-stream-outbox-service drainStream single mode", () => {
const call = auditLogStreamOutboxDAL.commitDeliveryResult.mock.calls[0][0] as {
successIds: number[];
retriable: { groups: { ids: number[]; nextRetryDelayMs: number }[] } | null;
- exhausted: TFailedStreamRow[];
+ exhaustedIds: number[];
};
expect(call.successIds).toEqual([1, 2]);
expect(call.retriable).toBeNull();
- expect(call.exhausted).toEqual([]);
+ expect(call.exhaustedIds).toEqual([]);
});
test("retries only the row whose single-event send failed", async () => {
@@ -297,11 +292,11 @@ describe("audit-log-stream-outbox-service drainStream single mode", () => {
const call = auditLogStreamOutboxDAL.commitDeliveryResult.mock.calls[0][0] as {
successIds: number[];
retriable: { groups: { ids: number[]; nextRetryDelayMs: number }[] } | null;
- exhausted: TFailedStreamRow[];
+ exhaustedIds: number[];
};
expect(call.successIds).toEqual([1]);
expect(call.retriable?.groups.flatMap((g) => g.ids)).toEqual([2]);
- expect(call.exhausted).toEqual([]);
+ expect(call.exhaustedIds).toEqual([]);
});
});
@@ -311,7 +306,7 @@ describe("audit-log-stream-outbox-service enqueueForLogs batch fanout", () => {
batchInsert: vi.fn<(rows: unknown[]) => Promise<void>>(async () => undefined),
claimBatchForStream: vi.fn(async () => []),
commitDeliveryResult: vi.fn(async () => undefined),
- recoverStaleClaims: vi.fn(async () => ({ retried: 0, movedToDlq: 0 })),
+ recoverStaleClaims: vi.fn(async () => ({ retried: 0, dropped: [] })),
findStreamsWithOverdueRows: vi.fn(async () => []),
deleteDeliveredOlderThan: vi.fn<(retentionMs: number) => Promise<number>>(async () => 0)
};
@@ -411,18 +406,3 @@ describe("audit-log-stream-outbox-service pruneDeliveredRows", () => {
expect(retentionMs).toBeGreaterThanOrEqual(5 * 60_000);
});
});
-
-describe("audit-log-stream-outbox-service pruneDlqEntries", () => {
- test("delegates to DAL with the configured retention", async () => {
- const { service, auditLogStreamOutboxDAL } = createService();
- auditLogStreamOutboxDAL.deleteDlqOlderThan.mockResolvedValueOnce(7);
-
- await service.pruneDlqEntries();
-
- expect(auditLogStreamOutboxDAL.deleteDlqOlderThan).toHaveBeenCalledTimes(1);
- const [retentionMs] = auditLogStreamOutboxDAL.deleteDlqOlderThan.mock.calls[0];
- // DLQ retention should give operators a meaningful window (at least several hours)
- // to notice and triage a wedged provider.
- expect(retentionMs).toBeGreaterThanOrEqual(12 * 60 * 60_000);
- });
-});
diff --git a/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-service.ts b/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-service.ts
index 9e9970f653..6acdd372f6 100644
--- a/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-service.ts
+++ b/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-service.ts
@@ -2,7 +2,10 @@ import { TAuditLogs } from "@app/db/schemas";
import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";
import { chunkArray } from "@app/lib/fn";
import { logger } from "@app/lib/logger";
-import { auditLogStreamDeliveryDurationHistogram } from "@app/lib/telemetry/metrics";
+import {
+ auditLogStreamDeliveryDurationHistogram,
+ auditLogStreamDeliveryExhaustedCounter
+} from "@app/lib/telemetry/metrics";
import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
@@ -50,11 +53,6 @@ export const STALE_CLAIM_THRESHOLD_MS = 10 * 60_000;
// so the 'delivered' rows (the table's hottest section) don't pile up.
export const DELIVERED_RETENTION_MS = 15 * 60_000;
-// Retention for DLQ entries. Long enough for an operator to notice + triage a
-// wedged provider via dashboard, short enough that the table doesn't grow
-// without bound. Same cron prunes these alongside delivered rows.
-export const DLQ_RETENTION_MS = 12 * 60 * 60_000;
-
const computeBackoffMs = (attemptsAfterIncrement: number): number => {
const exponent = Math.min(attemptsAfterIncrement - 1, 10);
const base = BACKOFF_BASE_MS * 2 ** exponent;
@@ -75,7 +73,6 @@ export type TAuditLogStreamOutboxServiceFactory = {
drainStream: (data: TAuditLogStreamFlushJobData) => Promise<void>;
sweepStaleClaims: () => Promise<void>;
pruneDeliveredRows: () => Promise<void>;
- pruneDlqEntries: () => Promise<void>;
};
export const auditLogStreamOutboxServiceFactory = ({
@@ -279,17 +276,38 @@ export const auditLogStreamOutboxServiceFactory = ({
}
: null;
+ // There is no DLQ: once a row exhausts MAX_ATTEMPTS the event is dropped
+ // (deleted in commitDeliveryResult below). Surface it as an error log +
+ // metric so a wedged provider is observable. Group by error so a batch
+ // failing for one reason logs once rather than per-row.
+ if (exhausted.length > 0) {
+ const exhaustedCountByError = new Map<string, number>();
+ for (const { errorMessage } of exhausted) {
+ exhaustedCountByError.set(errorMessage, (exhaustedCountByError.get(errorMessage) ?? 0) + 1);
+ }
+ for (const [errorMessage, count] of exhaustedCountByError) {
+ logger.error(
+ `audit-log-stream-outbox: dropping events after exhausting retries [streamId=${streamId}] [orgId=${orgId}] [provider=${provider}] [count=${count}] [maxAttempts=${MAX_ATTEMPTS}]: ${errorMessage}`
+ );
+ }
+ auditLogStreamDeliveryExhaustedCounter.add(exhausted.length, {
+ "audit_log_stream.id": streamId,
+ "infisical.organization.id": orgId,
+ "audit_log_stream.provider": provider
+ });
+ }
+
// eslint-disable-next-line no-await-in-loop
await auditLogStreamOutboxDAL.commitDeliveryResult({
successIds: streamSuccess.map((row) => row.id),
retriable: retriableInput,
- exhausted
+ exhaustedIds: exhausted.map((failed) => failed.row.id)
});
if (streamFail.length > 0) {
// Each failed chunk is already logged with its error above; the rows are
- // committed to 'retry'/DLQ by commitDeliveryResult. Bail when this claim
- // saw any failure. The inner loop already attempted
+ // committed to 'retry' (or dropped if exhausted) by commitDeliveryResult.
+ // Bail when this claim saw any failure. The inner loop already attempted
// every chunk independently (so partial-success rows are committed
// above), but hopping straight to the next claim risks compounding load
// on a degraded endpoint — let backoff on the retriable rows govern
@@ -302,8 +320,8 @@ export const auditLogStreamOutboxServiceFactory = ({
// Stale-claim sweeper. Two responsibilities, both about preventing rows from
// getting stuck in the outbox:
// 1. Rows whose worker crashed mid-batch stay 'processing' forever and never
- // re-enter the drain query — flip them back to 'retry' (or DLQ if attempts
- // are exhausted).
+ // re-enter the drain query — flip them back to 'retry' (or drop them if
+ // attempts are exhausted).
// 2. Rows in 'pending'/'retry' whose nextRetryAt is now in the past but never
// got a follow-up flush job (drainStream bailed on a chunk failure and no
// new event arrived after backoff). For these, enqueue a flush via the
@@ -317,15 +335,33 @@ export const auditLogStreamOutboxServiceFactory = ({
// - claimBatchForStream's FOR UPDATE SKIP LOCKED + atomic flip to 'processing'
// so even concurrent workers claim disjoint rows.
const sweepStaleClaims = async () => {
- const { retried, movedToDlq } = await auditLogStreamOutboxDAL.recoverStaleClaims(
+ const { retried, dropped } = await auditLogStreamOutboxDAL.recoverStaleClaims(
STALE_CLAIM_THRESHOLD_MS,
MAX_ATTEMPTS
);
- if (retried > 0 || movedToDlq > 0) {
+ if (retried > 0 || dropped.length > 0) {
logger.warn(
- `audit-log-stream-outbox: recovered stale claims [retried=${retried}] [movedToDlq=${movedToDlq}] [thresholdMs=${STALE_CLAIM_THRESHOLD_MS}]`
+ `audit-log-stream-outbox: recovered stale claims [retried=${retried}] [dropped=${dropped.length}] [thresholdMs=${STALE_CLAIM_THRESHOLD_MS}]`
);
}
+ if (dropped.length > 0) {
+ // Stale claims that used up their attempts are dropped (no DLQ); count them
+ // alongside delivery-path exhaustions, keyed by the same stream/org dimensions.
+ // No provider attribute here — the row doesn't carry it and the sweep isn't tied
+ // to a specific delivery attempt.
+ const droppedByStream = new Map<string, { streamId: string; orgId: string; count: number }>();
+ for (const { streamId, orgId } of dropped) {
+ const entry = droppedByStream.get(streamId);
+ if (entry) entry.count += 1;
+ else droppedByStream.set(streamId, { streamId, orgId, count: 1 });
+ }
+ for (const { streamId, orgId, count } of droppedByStream.values()) {
+ auditLogStreamDeliveryExhaustedCounter.add(count, {
+ "audit_log_stream.id": streamId,
+ "infisical.organization.id": orgId
+ });
+ }
+ }
const overdueStreams = await auditLogStreamOutboxDAL.findStreamsWithOverdueRows();
if (overdueStreams.length === 0) return;
@@ -348,18 +384,10 @@ export const auditLogStreamOutboxServiceFactory = ({
}
};
- const pruneDlqEntries = async () => {
- const deleted = await auditLogStreamOutboxDAL.deleteDlqOlderThan(DLQ_RETENTION_MS);
- if (deleted > 0) {
- logger.info(`audit-log-stream-outbox: pruned dlq entries [deleted=${deleted}] [retentionMs=${DLQ_RETENTION_MS}]`);
- }
- };
-
return {
enqueueForLogs,
drainStream,
sweepStaleClaims,
- pruneDeliveredRows,
- pruneDlqEntries
+ pruneDeliveredRows
};
};
diff --git a/backend/src/lib/telemetry/instrumentation.ts b/backend/src/lib/telemetry/instrumentation.ts
index 857674296a..4c5a0d004e 100644
--- a/backend/src/lib/telemetry/instrumentation.ts
+++ b/backend/src/lib/telemetry/instrumentation.ts
@@ -50,6 +50,7 @@ const INFISICAL_CORE_METER_ATTRIBUTES = [
"audit_log.backend",
"audit_log.drop_reason",
"audit_log_stream.provider",
+ "audit_log_stream.id",
"scim.operation",
"sso.provider",
"sso.action",
diff --git a/backend/src/lib/telemetry/metrics.ts b/backend/src/lib/telemetry/metrics.ts
index ee6261172c..48b62fc419 100644
--- a/backend/src/lib/telemetry/metrics.ts
+++ b/backend/src/lib/telemetry/metrics.ts
@@ -310,6 +310,17 @@ export const auditLogStreamDeliveryDurationHistogram = infisicalCoreMeter.create
}
);
+// Wired in audit-log-stream-outbox-service.ts. Incremented when stream events are dropped after
+// exhausting all delivery retries (there is no DLQ — the events are gone). Operators should alert on this.
+export const auditLogStreamDeliveryExhaustedCounter = infisicalCoreMeter.createCounter(
+ "infisical.audit_log_stream.delivery.exhausted.count",
+ {
+ description:
+ "Audit log stream events dropped after exhausting all delivery retries, by stream and org. Operators should alert on this.",
+ unit: "{event}"
+ }
+);
+
// Permission cache metrics. Wired in lib/cache/with-cache.ts withCacheFingerprint().
export const permissionCacheLookupCounter = infisicalCoreMeter.createCounter(
"infisical.permission_cache.lookup.count",