Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat: add BatchProjectCleaner as an optimization when multiple project deletions are pending (#11476)

Valery Meleshkind2deef409af5
diff --git a/worker/src/__tests__/batchProjectCleaner.test.ts b/worker/src/__tests__/batchProjectCleaner.test.ts
new file mode 100644
index 0000000000..ae58c4f117
--- /dev/null
+++ b/worker/src/__tests__/batchProjectCleaner.test.ts
@@ -0,0 +1,227 @@
+import { expect, describe, it, afterEach } from "vitest";
+import { randomUUID } from "crypto";
+import {
+ BatchProjectCleaner,
+ BATCH_DELETION_TABLES,
+ BATCH_PROJECT_CLEANER_LOCK_PREFIX,
+} from "../features/batch-project-cleaner";
+import {
+ createOrgProjectAndApiKey,
+ createTracesCh,
+ createTrace,
+ queryClickhouse,
+ redis,
+} from "@langfuse/shared/src/server";
+import { prisma } from "@langfuse/shared/src/db";
+import { env } from "../env";
+
+async function getClickhouseCount(
+ table: string,
+ projectId: string,
+): Promise<number> {
+ const result = await queryClickhouse<{ count: number }>({
+ query: `SELECT count() as count FROM ${table} FINAL WHERE project_id = {projectId: String}`,
+ params: { projectId },
+ });
+ return Number(result[0]?.count ?? 0);
+}
+
+describe("BatchProjectCleaner", () => {
+ const TEST_TABLE = "traces" as const;
+ const TEST_LOCK_KEY = `${BATCH_PROJECT_CLEANER_LOCK_PREFIX}:${TEST_TABLE}`;
+
+ // Clean up Redis locks after each test
+ afterEach(async () => {
+ for (const table of BATCH_DELETION_TABLES) {
+ await redis?.del(`${BATCH_PROJECT_CLEANER_LOCK_PREFIX}:${table}`);
+ }
+ });
+
+ describe("processBatch", () => {
+ it("should return sleep interval when no deleted projects exist", async () => {
+ // Create an active project (not deleted)
+ await createOrgProjectAndApiKey();
+
+ const cleaner = new BatchProjectCleaner(TEST_TABLE);
+ const nextDelayMs = await cleaner.processBatch();
+
+ expect(nextDelayMs).toBe(
+ env.LANGFUSE_BATCH_PROJECT_CLEANER_SLEEP_ON_EMPTY_MS,
+ );
+
+ // Verify lock was not taken
+ const lockValue = await redis?.get(TEST_LOCK_KEY);
+ expect(lockValue).toBeNull();
+ });
+
+ it("should return sleep interval when deleted project has no ClickHouse data", async () => {
+ // Create and soft-delete a project
+ const { projectId } = await createOrgProjectAndApiKey();
+ await prisma.project.update({
+ where: { id: projectId },
+ data: { deletedAt: new Date() },
+ });
+
+ const cleaner = new BatchProjectCleaner(TEST_TABLE);
+ const nextDelayMs = await cleaner.processBatch();
+
+ expect(nextDelayMs).toBe(
+ env.LANGFUSE_BATCH_PROJECT_CLEANER_SLEEP_ON_EMPTY_MS,
+ );
+
+ // Verify lock was not taken
+ const lockValue = await redis?.get(TEST_LOCK_KEY);
+ expect(lockValue).toBeNull();
+ });
+
+ it("should delete traces for soft-deleted project", async () => {
+ // Create and soft-delete a project
+ const { projectId } = await createOrgProjectAndApiKey();
+ await prisma.project.update({
+ where: { id: projectId },
+ data: { deletedAt: new Date() },
+ });
+
+ // Insert test traces into ClickHouse
+ await createTracesCh([
+ createTrace({ id: randomUUID(), project_id: projectId }),
+ createTrace({ id: randomUUID(), project_id: projectId }),
+ ]);
+
+ // Verify traces exist before deletion
+ const countBefore = await getClickhouseCount(TEST_TABLE, projectId);
+ expect(countBefore).toBe(2);
+
+ // Run processBatch
+ const cleaner = new BatchProjectCleaner(TEST_TABLE);
+ const nextDelayMs = await cleaner.processBatch();
+
+ // Verify traces were deleted
+ const countAfter = await getClickhouseCount(TEST_TABLE, projectId);
+ expect(countAfter).toBe(0);
+
+ // Verify returned check interval (work was done)
+ expect(nextDelayMs).toBe(
+ env.LANGFUSE_BATCH_PROJECT_CLEANER_CHECK_INTERVAL_MS,
+ );
+ });
+
+ it("should not affect traces from active projects", async () => {
+ // Create two projects
+ const { projectId: deletedProjectId } = await createOrgProjectAndApiKey();
+ const { projectId: activeProjectId } = await createOrgProjectAndApiKey();
+
+ // Soft-delete only one project
+ await prisma.project.update({
+ where: { id: deletedProjectId },
+ data: { deletedAt: new Date() },
+ });
+
+ // Insert traces for both projects
+ await createTracesCh([
+ createTrace({ id: randomUUID(), project_id: deletedProjectId }),
+ createTrace({ id: randomUUID(), project_id: deletedProjectId }),
+ createTrace({ id: randomUUID(), project_id: activeProjectId }),
+ createTrace({ id: randomUUID(), project_id: activeProjectId }),
+ createTrace({ id: randomUUID(), project_id: activeProjectId }),
+ ]);
+
+ // Verify traces exist before deletion
+ expect(await getClickhouseCount(TEST_TABLE, deletedProjectId)).toBe(2);
+ expect(await getClickhouseCount(TEST_TABLE, activeProjectId)).toBe(3);
+
+ // Run processBatch
+ const cleaner = new BatchProjectCleaner(TEST_TABLE);
+ await cleaner.processBatch();
+
+ // Verify only deleted project's traces were removed
+ expect(await getClickhouseCount(TEST_TABLE, deletedProjectId)).toBe(0);
+ expect(await getClickhouseCount(TEST_TABLE, activeProjectId)).toBe(3);
+ });
+
+ it("should delete traces from multiple soft-deleted projects", async () => {
+ // Create and soft-delete two projects
+ const { projectId: projectId1 } = await createOrgProjectAndApiKey();
+ const { projectId: projectId2 } = await createOrgProjectAndApiKey();
+
+ await prisma.project.update({
+ where: { id: projectId1 },
+ data: { deletedAt: new Date() },
+ });
+ await prisma.project.update({
+ where: { id: projectId2 },
+ data: { deletedAt: new Date() },
+ });
+
+ // Insert traces for both projects
+ await createTracesCh([
+ createTrace({ id: randomUUID(), project_id: projectId1 }),
+ createTrace({ id: randomUUID(), project_id: projectId2 }),
+ createTrace({ id: randomUUID(), project_id: projectId2 }),
+ ]);
+
+ // Run processBatch
+ const cleaner = new BatchProjectCleaner(TEST_TABLE);
+ const nextDelayMs = await cleaner.processBatch();
+
+ // Verify both projects' traces were deleted
+ expect(await getClickhouseCount(TEST_TABLE, projectId1)).toBe(0);
+ expect(await getClickhouseCount(TEST_TABLE, projectId2)).toBe(0);
+ expect(nextDelayMs).toBe(
+ env.LANGFUSE_BATCH_PROJECT_CLEANER_CHECK_INTERVAL_MS,
+ );
+ });
+
+ it("should skip processing when lock is already held", async () => {
+ // Create and soft-delete a project
+ const { projectId } = await createOrgProjectAndApiKey();
+ await prisma.project.update({
+ where: { id: projectId },
+ data: { deletedAt: new Date() },
+ });
+
+ // Insert traces
+ await createTracesCh([
+ createTrace({ id: randomUUID(), project_id: projectId }),
+ ]);
+
+ // Acquire the lock manually
+ await redis?.set(TEST_LOCK_KEY, "locked", "EX", 3600, "NX");
+
+ // Run processBatch - should skip because lock is held
+ const cleaner = new BatchProjectCleaner(TEST_TABLE);
+ const nextDelayMs = await cleaner.processBatch();
+
+ // Verify traces were NOT deleted (lock blocked processing)
+ expect(await getClickhouseCount(TEST_TABLE, projectId)).toBe(1);
+ expect(nextDelayMs).toBe(
+ env.LANGFUSE_BATCH_PROJECT_CLEANER_SLEEP_ON_EMPTY_MS,
+ );
+ });
+
+ it("should release lock after processing completes", async () => {
+ // Create and soft-delete a project
+ const { projectId } = await createOrgProjectAndApiKey();
+ await prisma.project.update({
+ where: { id: projectId },
+ data: { deletedAt: new Date() },
+ });
+
+ // Insert traces
+ await createTracesCh([
+ createTrace({ id: randomUUID(), project_id: projectId }),
+ ]);
+
+ // Run processBatch
+ const cleaner = new BatchProjectCleaner(TEST_TABLE);
+ await cleaner.processBatch();
+
+ // Verify that traces were deleted, therefore processing occurred
+ expect(await getClickhouseCount(TEST_TABLE, projectId)).toBe(0);
+
+ // Verify lock was released
+ const lockValue = await redis?.get(TEST_LOCK_KEY);
+ expect(lockValue).toBeNull();
+ });
+ });
+});
diff --git a/worker/src/__tests__/mutationMonitor.test.ts b/worker/src/__tests__/mutationMonitor.test.ts
index d627428af2..0272c8ca1e 100644
--- a/worker/src/__tests__/mutationMonitor.test.ts
+++ b/worker/src/__tests__/mutationMonitor.test.ts
@@ -337,7 +337,6 @@ describe("MutationMonitor", () => {
// TraceDelete should be paused
expect(mockWorkers.get("trace-delete")?.pause).toHaveBeenCalled();
- expect(mockWorkers.get("project-delete")?.pause).toHaveBeenCalled();
expect(
mockWorkers.get("data-retention-processing-queue")?.pause,
).toHaveBeenCalled();
diff --git a/worker/src/__tests__/periodicRunner.test.ts b/worker/src/__tests__/periodicRunner.test.ts
new file mode 100644
index 0000000000..f0fcae1b52
--- /dev/null
+++ b/worker/src/__tests__/periodicRunner.test.ts
@@ -0,0 +1,139 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
+import { PeriodicRunner } from "../utils/PeriodicRunner";
+
+/**
+ * Helper to flush microtasks without advancing timers
+ *
+ * JavaScript has different "task queues" that execute code in a specific order:
+ * 1. Synchronous code runs first
+ * 2. Microtasks (like Promise callbacks) run next
+ * 3. Macrotasks (like setTimeout) run after microtasks
+ *
+ * When testing async code with fake timers, we often need to let microtasks
+ * complete WITHOUT advancing the timer (which would also trigger macrotasks).
+ *
+ * This function works by:
+ * - Creating a Promise that will resolve in the microtask queue
+ * - Using `queueMicrotask()` to schedule the Promise resolution
+ * - Awaiting that Promise, which pauses execution until all microtasks drain
+ *
+ * In these tests, we use it after calling `runner.start()` to ensure the
+ * initial async execution completes before we check the results or advance timers.
+ */
+const flushMicrotasks = () => new Promise((r) => queueMicrotask(r));
+
+// Test subclass that tracks execution
+class TestRunner extends PeriodicRunner {
+ public callCount = 0;
+ public shouldThrow = false;
+ public returnInterval: number | undefined = undefined;
+
+ protected get name(): string {
+ return "test-runner";
+ }
+
+ protected get defaultIntervalMs(): number {
+ return 1000;
+ }
+
+ protected async execute(): Promise<number | void> {
+ this.callCount++;
+ if (this.shouldThrow) {
+ this.shouldThrow = false; // Only throw once
+ throw new Error("Test error");
+ }
+ return this.returnInterval;
+ }
+}
+
+describe("PeriodicRunner", () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it("should call execute on start", async () => {
+ const runner = new TestRunner();
+
+ runner.start();
+ await flushMicrotasks();
+
+ expect(runner.callCount).toBe(1);
+ runner.stop();
+ });
+
+ it("should call execute repeatedly at default interval", async () => {
+ const runner = new TestRunner();
+
+ runner.start();
+ await flushMicrotasks(); // First execution
+
+ expect(runner.callCount).toBe(1);
+
+ await vi.advanceTimersByTimeAsync(1000); // Advance to trigger second execution
+
+ expect(runner.callCount).toBe(2);
+ runner.stop();
+ });
+
+ it("should use dynamic interval when execute returns a number", async () => {
+ const runner = new TestRunner();
+ runner.returnInterval = 500; // Return shorter interval
+
+ runner.start();
+ await flushMicrotasks(); // First execution
+
+ expect(runner.callCount).toBe(1);
+
+ // Should wait 500ms (not 1000ms) for next execution
+ await vi.advanceTimersByTimeAsync(499);
+ expect(runner.callCount).toBe(1); // Not yet
+
+ await vi.advanceTimersByTimeAsync(1);
+ expect(runner.callCount).toBe(2); // Now it fired
+
+ runner.stop();
+ });
+
+ it("should stop scheduling when stop is called", async () => {
+ const runner = new TestRunner();
+
+ runner.start();
+ await flushMicrotasks();
+ expect(runner.callCount).toBe(1);
+
+ runner.stop();
+
+ await vi.advanceTimersByTimeAsync(5000);
+
+ expect(runner.callCount).toBe(1); // No more executions
+ });
+
+ it("should continue scheduling after execute throws", async () => {
+ const runner = new TestRunner();
+ runner.shouldThrow = true;
+
+ runner.start();
+ await flushMicrotasks(); // First execution (throws)
+ expect(runner.callCount).toBe(1);
+
+ await vi.advanceTimersByTimeAsync(1000); // Second execution (succeeds)
+ expect(runner.callCount).toBe(2);
+
+ runner.stop();
+ });
+
+ it("should not start twice when start is called multiple times", async () => {
+ const runner = new TestRunner();
+
+ runner.start();
+ runner.start(); // Second call should be ignored
+ await flushMicrotasks();
+
+ expect(runner.callCount).toBe(1);
+ runner.stop();
+ });
+});
diff --git a/worker/src/app.ts b/worker/src/app.ts
index 15baffd0ae..3771a9b7b1 100644
--- a/worker/src/app.ts
+++ b/worker/src/app.ts
@@ -73,6 +73,10 @@ import { otelIngestionQueueProcessor } from "./queues/otelIngestionQueue";
import { eventPropagationProcessor } from "./queues/eventPropagationQueue";
import { notificationQueueProcessor } from "./queues/notificationQueue";
import { MutationMonitor } from "./features/mutation-monitoring/mutationMonitor";
+import {
+ BatchProjectCleaner,
+ BATCH_DELETION_TABLES,
+} from "./features/batch-project-cleaner";
const app = express();
@@ -540,6 +544,17 @@ if (env.LANGFUSE_MUTATION_MONITOR_ENABLED === "true") {
MutationMonitor.start();
}
+// Batch project cleaners for bulk deletion of ClickHouse data
+export const batchProjectCleaners: BatchProjectCleaner[] = [];
+
+if (env.LANGFUSE_BATCH_PROJECT_CLEANER_ENABLED === "true") {
+ for (const table of BATCH_DELETION_TABLES) {
+ const cleaner = new BatchProjectCleaner(table);
+ batchProjectCleaners.push(cleaner);
+ cleaner.start();
+ }
+}
+
process.on("SIGINT", () => onShutdown("SIGINT"));
process.on("SIGTERM", () => onShutdown("SIGTERM"));
diff --git a/worker/src/env.ts b/worker/src/env.ts
index 321c069e49..961f222c01 100644
--- a/worker/src/env.ts
+++ b/worker/src/env.ts
@@ -321,6 +321,27 @@ const EnvSchema = z.object({
.positive()
.default(1),
+ // Batch Project Cleaner configuration
+ LANGFUSE_BATCH_PROJECT_CLEANER_ENABLED: z
+ .enum(["true", "false"])
+ .default("false"),
+ LANGFUSE_BATCH_PROJECT_CLEANER_CHECK_INTERVAL_MS: z.coerce
+ .number()
+ .positive()
+ .default(60_000), // 1 minute between runs
+ LANGFUSE_BATCH_PROJECT_CLEANER_SLEEP_ON_EMPTY_MS: z.coerce
+ .number()
+ .positive()
+ .default(600_000), // 10 minutes if nothing to do
+ LANGFUSE_BATCH_PROJECT_CLEANER_PROJECT_LIMIT: z.coerce
+ .number()
+ .positive()
+ .default(1000), // Max projects per batch
+ LANGFUSE_BATCH_PROJECT_CLEANER_DELETE_TIMEOUT_MS: z.coerce
+ .number()
+ .positive()
+ .default(5_400_000), // 1.5 hours for DELETE operations
+
LANGFUSE_EXPERIMENT_BACKFILL_EXCLUDE_ATTRIBUTES_KEY: z
.enum(["true", "false"])
.default("false"),
diff --git a/worker/src/features/batch-project-cleaner/index.ts b/worker/src/features/batch-project-cleaner/index.ts
new file mode 100644
index 0000000000..8418e24449
--- /dev/null
+++ b/worker/src/features/batch-project-cleaner/index.ts
@@ -0,0 +1,298 @@
+import {
+ logger,
+ queryClickhouse,
+ commandClickhouse,
+ traceException,
+ recordIncrement,
+} from "@langfuse/shared/src/server";
+import { prisma } from "@langfuse/shared/src/db";
+import { env } from "../../env";
+import { PeriodicRunner } from "../../utils/PeriodicRunner";
+import { RedisLock } from "../../utils/RedisLock";
+
+export const BATCH_DELETION_TABLES = [
+ "traces",
+ "observations",
+ "scores",
+ "events",
+] as const;
+
+export type BatchDeletionTable = (typeof BATCH_DELETION_TABLES)[number];
+
+export const BATCH_PROJECT_CLEANER_LOCK_PREFIX =
+ "langfuse:batch-project-cleaner";
+
+interface ProjectCount {
+ project_id: string;
+ count: number;
+}
+
+/**
+ * BatchProjectCleaner handles bulk deletion of ClickHouse data for soft-deleted projects.
+ *
+ * Each instance processes one table (traces, observations, scores, events).
+ * Multiple workers coordinate via Redis distributed locking to ensure only one
+ * worker deletes from a given table at a time.
+ *
+ * Flow:
+ * 1. Query PG for projects with deleted_at set (no lock needed)
+ * 2. Query ClickHouse for counts per project (no lock needed)
+ * 3. Acquire Redis lock for DELETE only
+ * 4. Execute DELETE
+ * 5. On failure: re-run count query to determine partial success
+ */
+export class BatchProjectCleaner extends PeriodicRunner {
+ private readonly tableName: BatchDeletionTable;
+ private readonly instanceName: string;
+ private readonly lock: RedisLock;
+
+ protected get name(): string {
+ return this.instanceName;
+ }
+
+ protected get defaultIntervalMs(): number {
+ return env.LANGFUSE_BATCH_PROJECT_CLEANER_SLEEP_ON_EMPTY_MS;
+ }
+
+ constructor(tableName: BatchDeletionTable) {
+ super();
+ this.tableName = tableName;
+ this.instanceName = `BatchProjectCleaner(${tableName})`;
+
+ // TTL = DELETE timeout + 5 minutes buffer
+ const lockTtlSeconds =
+ Math.ceil(env.LANGFUSE_BATCH_PROJECT_CLEANER_DELETE_TIMEOUT_MS / 1000) +
+ 300;
+
+ // We use this lock as a performance optimization: avoiding
+ // multiple workers starting DELETE mutation for the same table
+ // simultaneously. If Redis is unavailable, we allow processing
+ // to avoid blocking progress as this does not compromise data integrity.
+ this.lock = new RedisLock(
+ `${BATCH_PROJECT_CLEANER_LOCK_PREFIX}:${tableName}`,
+ {
+ ttlSeconds: lockTtlSeconds,
+ name: this.instanceName,
+ onUnavailable: "proceed", // If lock is unavailable, proceed anyway.
+ },
+ );
+ }
+
+ /**
+ * Start the batch cleaner service
+ */
+ public override start(): void {
+ logger.info(`Starting ${this.instanceName}`, {
+ checkIntervalMs: env.LANGFUSE_BATCH_PROJECT_CLEANER_CHECK_INTERVAL_MS,
+ sleepOnEmptyMs: env.LANGFUSE_BATCH_PROJECT_CLEANER_SLEEP_ON_EMPTY_MS,
+ projectLimit: env.LANGFUSE_BATCH_PROJECT_CLEANER_PROJECT_LIMIT,
+ deleteTimeoutMs: env.LANGFUSE_BATCH_PROJECT_CLEANER_DELETE_TIMEOUT_MS,
+ });
+ super.start();
+ }
+
+ /**
+ * Stop the batch cleaner service
+ */
+ public override stop(): void {
+ super.stop();
+ logger.info(`${this.instanceName} stopped`);
+ }
+
+ /**
+ * Process a batch of deleted projects. Returns the delay until next run.
+ * Public wrapper for testing.
+ */
+ public async processBatch(): Promise<number> {
+ return this.execute();
+ }
+
+ /**
+ * Process a batch of deleted projects. Returns the delay until next run.
+ */
+ protected async execute(): Promise<number> {
+ // Step 1: Query PG for deleted projects (no lock needed)
+ let deletedProjects: Array<{ id: string }>;
+ try {
+ deletedProjects = await this.getDeletedProjects();
+ } catch (error) {
+ logger.error(`${this.instanceName}: Failed to query deleted projects`, {
+ error,
+ });
+ traceException(error);
+ return env.LANGFUSE_BATCH_PROJECT_CLEANER_SLEEP_ON_EMPTY_MS;
+ }
+
+ // Step 2: Query ClickHouse for counts per project (no lock needed)
+ let initialCounts: Map<string, number>;
+ try {
+ initialCounts = await this.getProjectCounts(
+ deletedProjects.map((p) => p.id),
+ );
+ } catch (error) {
+ logger.error(
+ `${this.instanceName}: Failed to query ClickHouse counts`,
+ error,
+ );
+ traceException(error);
+ return env.LANGFUSE_BATCH_PROJECT_CLEANER_SLEEP_ON_EMPTY_MS;
+ }
+
+ // Filter to only projects that have data
+ const projectIdsWithData = Array.from(initialCounts.entries())
+ .filter(([, count]) => count > 0)
+ .map(([projectId]) => projectId);
+
+ if (projectIdsWithData.length === 0) {
+ logger.info(
+ `${this.instanceName}: No data found for deleted projects in ${this.tableName}`,
+ );
+ return env.LANGFUSE_BATCH_PROJECT_CLEANER_SLEEP_ON_EMPTY_MS;
+ }
+
+ // Step 3 & 4: Execute DELETE under distributed lock
+ const result = await this.lock.withLock(async () => {
+ try {
+ await this.executeDelete(projectIdsWithData);
+
+ const totalRows = Array.from(initialCounts.values()).reduce(
+ (sum, count) => sum + count,
+ 0,
+ );
+ logger.info(`${this.instanceName}: Batch deletion completed`, {
+ table: this.tableName,
+ projectsProcessed: projectIdsWithData.length,
+ totalRowsTargeted: totalRows,
+ });
+
+ return env.LANGFUSE_BATCH_PROJECT_CLEANER_CHECK_INTERVAL_MS;
+ } catch (deleteError) {
+ // Step 5: On failure, re-run count query to determine partial success
+ logger.warn(
+ `${this.instanceName}: DELETE failed, checking for partial success`,
+ deleteError,
+ );
+ traceException(deleteError);
+
+ // Record DELETE failure metric
+ recordIncrement("langfuse.batch_project_cleaner.delete_failures", 1, {
+ table: this.tableName,
+ });
+
+ let finalCounts: Map<string, number> | undefined;
+ try {
+ finalCounts = await this.getProjectCounts(projectIdsWithData);
+ } catch (countError) {
+ // Can't determine partial success
+ logger.error(
+ `${this.instanceName}: Failed to re-query counts after DELETE failure`,
+ countError,
+ );
+ }
+
+ // Calculate projects that couldn't be fully cleaned
+ const incompleteProjects = finalCounts
+ ? projectIdsWithData.filter((projectId) => {
+ const finalCount = finalCounts.get(projectId) ?? 0;
+ return finalCount > 0;
+ })
+ : projectIdsWithData;
+
+ if (incompleteProjects.length > 0) {
+ recordIncrement(
+ "langfuse.batch_project_cleaner.incomplete_cleanups",
+ incompleteProjects.length,
+ { table: this.tableName },
+ );
+ logger.warn(`${this.instanceName}: Partial deletion completed`, {
+ table: this.tableName,
+ incompleteProjectCount: incompleteProjects.length,
+ incompleteProjects: incompleteProjects.slice(0, 10), // Log first 10
+ error: (deleteError as Error).message,
+ });
+ } else {
+ logger.info(
+ `${this.instanceName}: All projects cleaned successfully on re-check`,
+ );
+ }
+ return env.LANGFUSE_BATCH_PROJECT_CLEANER_CHECK_INTERVAL_MS;
+ }
+ });
+
+ if (result === null) {
+ logger.info(
+ `${this.instanceName}: Lock not acquired, another worker is processing`,
+ );
+ return env.LANGFUSE_BATCH_PROJECT_CLEANER_SLEEP_ON_EMPTY_MS;
+ }
+
+ return result;
+ }
+
+ private async getDeletedProjects(): Promise<Array<{ id: string }>> {
+ return prisma.project.findMany({
+ select: { id: true },
+ where: {
+ deletedAt: { not: null },
+ },
+ take: env.LANGFUSE_BATCH_PROJECT_CLEANER_PROJECT_LIMIT,
+ });
+ }
+
+ private async getProjectCounts(
+ projectIds: string[],
+ ): Promise<Map<string, number>> {
+ if (projectIds.length === 0) {
+ return new Map();
+ }
+
+ const query = `
+ SELECT project_id, count() as count
+ FROM ${this.tableName}
+ WHERE project_id IN ({projectIds: Array(String)})
+ GROUP BY project_id
+ ORDER BY count DESC
+ `;
+
+ const results = await queryClickhouse<ProjectCount>({
+ query,
+ params: { projectIds },
+ tags: {
+ feature: "batch-project-cleaner",
+ table: this.tableName,
+ operation: "count",
+ },
+ });
+
+ const counts = new Map<string, number>();
+ for (const row of results) {
+ counts.set(row.project_id, Number(row.count));
+ }
+
+ return counts;
+ }
+
+ private async executeDelete(projectIds: string[]): Promise<void> {
+ if (projectIds.length === 0) {
+ return;
+ }
+
+ const query = `
+ DELETE FROM ${this.tableName}
+ WHERE project_id IN ({projectIds: Array(String)})
+ `;
+
+ await commandClickhouse({
+ query,
+ params: { projectIds },
+ clickhouseConfigs: {
+ request_timeout: env.LANGFUSE_BATCH_PROJECT_CLEANER_DELETE_TIMEOUT_MS,
+ },
+ tags: {
+ feature: "batch-project-cleaner",
+ table: this.tableName,
+ operation: "delete",
+ },
+ });
+ }
+}
diff --git a/worker/src/features/mutation-monitoring/mutationMonitor.ts b/worker/src/features/mutation-monitoring/mutationMonitor.ts
index 974daf04ef..bd94823321 100644
--- a/worker/src/features/mutation-monitoring/mutationMonitor.ts
+++ b/worker/src/features/mutation-monitoring/mutationMonitor.ts
@@ -5,6 +5,7 @@ import {
} from "@langfuse/shared/src/server";
import { env } from "../../env";
import { WorkerManager } from "../../queues/workerManager";
+import { PeriodicRunner } from "../../utils/PeriodicRunner";
interface MutationCount {
database: string;
@@ -20,6 +21,23 @@ interface QueueDecision {
reason: string;
}
+/**
+ * Internal runner class that extends PeriodicRunner and delegates to MutationMonitor
+ */
+class MutationMonitorRunner extends PeriodicRunner {
+ protected get name(): string {
+ return "MutationMonitor";
+ }
+
+ protected get defaultIntervalMs(): number {
+ return env.LANGFUSE_MUTATION_MONITOR_CHECK_INTERVAL_MS;
+ }
+
+ protected async execute(): Promise<void> {
+ await MutationMonitor.checkMutations();
+ }
+}
+
/**
* MutationMonitor pauses and resumes queue processing
* based on how ClickHouse mutations progress.
@@ -38,9 +56,8 @@ interface QueueDecision {
* `- LANGFUSE_DELETION_MUTATIONS_SAFE_COUNT` once all tables for a queue are below this threshold, that queue is RESUMED.
*/
export class MutationMonitor {
- private static timeoutId: NodeJS.Timeout | null = null;
+ private static runner = new MutationMonitorRunner();
private static pausedQueues: Set<QueueName> = new Set();
- private static isRunning = false;
// Mapping of which ClickHouse tables each deletion queue affects
private static readonly QUEUE_TABLE_MAPPING: Partial<
@@ -49,13 +66,7 @@ export class MutationMonitor {
[QueueName.TraceDelete]: ["traces", "observations", "scores", "events"],
[QueueName.ScoreDelete]: ["scores"],
[QueueName.DatasetDelete]: ["dataset_run_items_rmt"],
- [QueueName.ProjectDelete]: [
- "traces",
- "observations",
- "scores",
- "dataset_run_items_rmt",
- "events",
- ],
+ [QueueName.ProjectDelete]: ["scores", "dataset_run_items_rmt"],
[QueueName.DataRetentionProcessingQueue]: [
"traces",
"observations",
@@ -72,70 +83,27 @@ export class MutationMonitor {
* Start the mutation monitoring service
*/
public static start(): void {
- if (this.isRunning) {
- logger.warn("Mutation monitor is already running");
- return;
- }
-
if (env.LANGFUSE_MUTATION_MONITOR_ENABLED !== "true") {
logger.info("Mutation monitor is disabled");
return;
}
- this.isRunning = true;
logger.info("Starting mutation monitor", {
checkIntervalMs: env.LANGFUSE_MUTATION_MONITOR_CHECK_INTERVAL_MS,
maxCount: env.LANGFUSE_DELETION_MUTATIONS_MAX_COUNT,
safeCount: env.LANGFUSE_DELETION_MUTATIONS_SAFE_COUNT,
});
-
- // Start the monitoring loop
- void this.checkMutationsAndScheduleNext();
+ this.runner.start();
}
/**
* Stop the mutation monitoring service
*/
public static stop(): void {
- if (!this.isRunning) {
- return;
- }
-
- this.isRunning = false;
- if (this.timeoutId !== null) {
- clearTimeout(this.timeoutId);
- this.timeoutId = null;
- }
+ this.runner.stop();
logger.info("Mutation monitor stopped");
}
- /**
- * Schedule the next mutation check after the specified interval
- */
- private static scheduleNextCheck(): void {
- if (!this.isRunning) {
- return;
- }
-
- this.timeoutId = setTimeout(() => {
- void this.checkMutationsAndScheduleNext();
- }, env.LANGFUSE_MUTATION_MONITOR_CHECK_INTERVAL_MS);
- }
-
- /**
- * Check mutations and schedule the next check (ensures sequential execution)
- */
- private static async checkMutationsAndScheduleNext(): Promise<void> {
- try {
- await this.checkMutations();
- } catch (error) {
- logger.error("Unexpected error in mutation monitoring loop", error);
- } finally {
- // Always schedule next check, even if current check failed
- this.scheduleNextCheck();
- }
- }
-
/**
* Decision function - determines which queues to pause/resume
*/
@@ -207,7 +175,7 @@ export class MutationMonitor {
/**
* Check ClickHouse mutations and pause/resume workers as needed
*/
- private static async checkMutations(): Promise<void> {
+ public static async checkMutations(): Promise<void> {
try {
const query = `
SELECT
@@ -360,10 +328,6 @@ export class MutationMonitor {
*/
public static resetState(): void {
this.pausedQueues.clear();
- this.isRunning = false;
- if (this.timeoutId !== null) {
- clearTimeout(this.timeoutId);
- this.timeoutId = null;
- }
+ this.runner.stop();
}
}
diff --git a/worker/src/utils/PeriodicRunner.ts b/worker/src/utils/PeriodicRunner.ts
new file mode 100644
index 0000000000..6dffcf1fa0
--- /dev/null
+++ b/worker/src/utils/PeriodicRunner.ts
@@ -0,0 +1,57 @@
+import { logger, traceException } from "@langfuse/shared/src/server";
+
+/**
+ * Abstract base class for periodic task execution.
+ *
+ * Subclasses implement `execute()` and provide config via abstract getters.
+ * The runner handles scheduling, error handling, and lifecycle management.
+ */
+export abstract class PeriodicRunner {
+ private timeoutId: NodeJS.Timeout | null = null;
+ private isRunning = false;
+
+ protected abstract get name(): string;
+ protected abstract get defaultIntervalMs(): number;
+ protected abstract execute(): Promise<number | void>;
+
+ public start(): void {
+ if (this.isRunning) {
+ return;
+ }
+ this.isRunning = true;
+ void this.runAndScheduleNext();
+ }
+
+ public stop(): void {
+ this.isRunning = false;
+ if (this.timeoutId !== null) {
+ clearTimeout(this.timeoutId);
+ this.timeoutId = null;
+ }
+ }
+
+ private async runAndScheduleNext(): Promise<void> {
+ let nextDelayMs = this.defaultIntervalMs;
+
+ try {
+ const result = await this.execute();
+ if (typeof result === "number") {
+ nextDelayMs = result;
+ }
+ } catch (error) {
+ logger.error(`Unexpected error in ${this.name}`, error);
+ traceException(error);
+ } finally {
+ this.scheduleNext(nextDelayMs);
+ }
+ }
+
+ private scheduleNext(delayMs: number): void {
+ if (!this.isRunning) {
+ return;
+ }
+ this.timeoutId = setTimeout(() => {
+ void this.runAndScheduleNext();
+ }, delayMs);
+ }
+}
diff --git a/worker/src/utils/RedisLock.ts b/worker/src/utils/RedisLock.ts
new file mode 100644
index 0000000000..e95eebd961
--- /dev/null
+++ b/worker/src/utils/RedisLock.ts
@@ -0,0 +1,179 @@
+import { randomUUID } from "crypto";
+import { logger, redis } from "@langfuse/shared/src/server";
+
+export type LockAcquireResult = "acquired" | "held_by_other" | "skipped";
+
+/**
+ * Behavior when Redis is unavailable or errors occur during lock acquisition.
+ * - "proceed": Allow processing without the lock (optimistic, for non-critical locks)
+ * - "fail": Treat as failure to acquire (pessimistic, for critical locks)
+ */
+export type OnUnavailableBehavior = "proceed" | "fail";
+
+/**
+ * Distributed lock implementation using Redis.
+ *
+ * Features:
+ * - Unique lock ownership via UUID to prevent accidental release of another worker's lock
+ * - Atomic release using Lua script for check-and-delete
+ * - Configurable behavior when Redis is unavailable
+ * - TTL-based expiration as safety net
+ *
+ * Usage:
+ * ```typescript
+ * // Optimistic: proceed without lock if Redis unavailable
+ * const lock = new RedisLock("my-lock-key", {
+ * ttlSeconds: 300,
+ * onUnavailable: "proceed",
+ * });
+ *
+ * // Pessimistic: fail if Redis unavailable
+ * const lock = new RedisLock("critical-lock", {
+ * ttlSeconds: 300,
+ * onUnavailable: "fail",
+ * });
+ *
+ * const result = await lock.withLock(async () => {
+ * // Critical section
+ * return someValue;
+ * });
+ *
+ * if (result === null) {
+ * // Lock was not acquired
+ * }
+ * ```
+ */
+export class RedisLock {
+ private readonly lockKey: string;
+ private readonly lockValue: string;
+ private readonly ttlSeconds: number;
+ private readonly name: string;
+ private readonly onUnavailable: OnUnavailableBehavior;
+
+ // Lua script for atomic check-and-delete (only delete if we own the lock)
+ private static readonly RELEASE_LOCK_SCRIPT = `
+ if redis.call("get", KEYS[1]) == ARGV[1] then
+ return redis.call("del", KEYS[1])
+ else
+ return 0
+ end
+ `;
+
+ constructor(
+ lockKey: string,
+ options: {
+ ttlSeconds: number;
+ /** Optional name for logging */
+ name?: string;
+ /** Behavior when Redis is unavailable. Default: "proceed" */
+ onUnavailable?: OnUnavailableBehavior;
+ },
+ ) {
+ this.lockKey = lockKey;
+ this.lockValue = randomUUID();
+ this.ttlSeconds = options.ttlSeconds;
+ this.name = options.name ?? lockKey;
+ this.onUnavailable = options.onUnavailable ?? "proceed";
+ }
+
+ /**
+ * Execute a callback under the distributed lock.
+ * Returns null if lock could not be acquired, otherwise returns the callback result.
+ */
+ public async withLock<T>(fn: () => Promise<T>): Promise<T | null> {
+ const lockResult = await this.acquire();
+
+ // Determine if we should proceed based on result and configuration
+ const shouldProceed =
+ lockResult === "acquired" ||
+ (lockResult === "skipped" && this.onUnavailable === "proceed");
+
+ if (!shouldProceed) {
+ return null;
+ }
+
+ try {
+ return await fn();
+ } finally {
+ // Only release if we actually acquired the lock (not if Redis was unavailable)
+ if (lockResult === "acquired") {
+ await this.release();
+ }
+ }
+ }
+
+ /**
+ * Attempt to acquire the distributed lock.
+ *
+ * Returns:
+ * - "acquired": lock acquired successfully
+ * - "held_by_other": lock is held by another worker
+ * - "skipped": Redis unavailable, proceeding without lock
+ */
+ public async acquire(): Promise<LockAcquireResult> {
+ if (!redis) {
+ logger.warn(`[${this.name}] Redis unavailable, allowing processing`);
+ return "skipped";
+ }
+
+ try {
+ const result = await redis.set(
+ this.lockKey,
+ this.lockValue,
+ "EX",
+ this.ttlSeconds,
+ "NX",
+ );
+ const acquired = result === "OK";
+
+ if (acquired) {
+ logger.debug(
+ `[${this.name}] Acquired lock with TTL ${this.ttlSeconds}s`,
+ );
+ return "acquired";
+ }
+
+ return "held_by_other";
+ } catch (error) {
+ logger.error(
+ `[${this.name}] Failed to acquire lock due to an error`,
+ error,
+ );
+ // On error, allow processing but don't claim to hold the lock
+ return "skipped";
+ }
+ }
+
+ /**
+ * Release the distributed lock if we own it.
+ * Uses a Lua script for atomic check-and-delete to prevent accidentally
+ * releasing a lock owned by another worker.
+ */
+ public async release(): Promise<boolean> {
+ if (!redis) {
+ return false;
+ }
+
+ try {
+ const result = await redis.eval(
+ RedisLock.RELEASE_LOCK_SCRIPT,
+ 1,
+ this.lockKey,
+ this.lockValue,
+ );
+ if (result === 1) {
+ logger.debug(`[${this.name}] Released lock`);
+ return true;
+ } else {
+ logger.warn(
+ `[${this.name}] Lock was not released (not owned or already expired)`,
+ );
+ return false;
+ }
+ } catch (error) {
+ // Log but don't throw - lock will expire via TTL anyway
+ logger.error(`[${this.name}] Failed to release lock`, error);
+ return false;
+ }
+ }
+}
diff --git a/worker/src/utils/shutdown.ts b/worker/src/utils/shutdown.ts
index 105d2efb42..d45269554a 100644
--- a/worker/src/utils/shutdown.ts
+++ b/worker/src/utils/shutdown.ts
@@ -10,6 +10,7 @@ import { WorkerManager } from "../queues/workerManager";
import { prisma } from "@langfuse/shared/src/db";
import { BackgroundMigrationManager } from "../backgroundMigrations/backgroundMigrationManager";
import { MutationMonitor } from "../features/mutation-monitoring/mutationMonitor";
+import { batchProjectCleaners } from "../app";
export const onShutdown: NodeJS.SignalsListener = async (signal) => {
logger.info(`Received ${signal}, closing server...`);
@@ -22,6 +23,11 @@ export const onShutdown: NodeJS.SignalsListener = async (signal) => {
// Stop mutation monitor
MutationMonitor.stop();
+ // Stop batch project cleaners
+ for (const cleaner of batchProjectCleaners) {
+ cleaner.stop();
+ }
+
// Shutdown workers (https://docs.bullmq.io/guide/going-to-production#gracefully-shut-down-workers)
await WorkerManager.closeWorkers();