Skip to content

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

feat: move batchProjectCleaner to use BullMQ (#11504)

Valery Meleshkin26ae2080d0c3
diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.ts
index 73e134382e..fdd82e192b 100644
--- a/packages/shared/src/server/index.ts
+++ b/packages/shared/src/server/index.ts
@@ -79,6 +79,7 @@ export * from "./redis/experimentCreateQueue";
export * from "./redis/dlqRetryQueue";
export * from "./redis/entityChangeQueue";
export * from "./redis/eventPropagationQueue";
+export * from "./redis/batchProjectCleanerQueue";
export * from "./redis/otelProjectTracking";
export * from "./redis/s3SlowdownTracking";
export * from "./auth/types";
diff --git a/packages/shared/src/server/queues.ts b/packages/shared/src/server/queues.ts
index 0e8610857a..d5eb9b9cea 100644
--- a/packages/shared/src/server/queues.ts
+++ b/packages/shared/src/server/queues.ts
@@ -197,6 +197,13 @@ export const DeadLetterRetryQueueEventSchema = z.object({
timestamp: z.date(),
});
+export const BatchProjectCleanerJobSchema = z.object({
+ table: z.enum(["traces", "observations", "scores", "events"]),
+});
+export type BatchProjectCleanerJobType = z.infer<
+ typeof BatchProjectCleanerJobSchema
+>;
+
export const NotificationEventSchema = z.discriminatedUnion("type", [
z.object({
type: z.literal("COMMENT_MENTION"),
@@ -312,6 +319,7 @@ export enum QueueName {
EntityChangeQueue = "entity-change-queue",
EventPropagationQueue = "event-propagation-queue",
NotificationQueue = "notification-queue",
+ BatchProjectCleanerQueue = "batch-project-cleaner-queue",
}
export enum QueueJobs {
@@ -347,6 +355,7 @@ export enum QueueJobs {
EntityChangeJob = "entity-change-job",
EventPropagationJob = "event-propagation-job",
NotificationJob = "notification-job",
+ BatchProjectCleanerJob = "batch-project-cleaner-job",
}
export type TQueueJobTypes = {
diff --git a/packages/shared/src/server/redis/batchProjectCleanerQueue.ts b/packages/shared/src/server/redis/batchProjectCleanerQueue.ts
new file mode 100644
index 0000000000..17b6950cee
--- /dev/null
+++ b/packages/shared/src/server/redis/batchProjectCleanerQueue.ts
@@ -0,0 +1,36 @@
+import { Queue } from "bullmq";
+import { QueueName } from "../queues";
+import {
+ createNewRedisInstance,
+ redisQueueRetryOptions,
+ getQueuePrefix,
+} from "./redis";
+import { logger } from "../logger";
+
+export class BatchProjectCleanerQueue {
+ private static instance: Queue | null = null;
+
+ public static getInstance(): Queue | null {
+ if (BatchProjectCleanerQueue.instance) {
+ return BatchProjectCleanerQueue.instance;
+ }
+
+ const newRedis = createNewRedisInstance({
+ enableOfflineQueue: false,
+ ...redisQueueRetryOptions,
+ });
+
+ BatchProjectCleanerQueue.instance = newRedis
+ ? new Queue(QueueName.BatchProjectCleanerQueue, {
+ connection: newRedis,
+ prefix: getQueuePrefix(QueueName.BatchProjectCleanerQueue),
+ })
+ : null;
+
+ BatchProjectCleanerQueue.instance?.on("error", (err) => {
+ logger.error("BatchProjectCleanerQueue error", err);
+ });
+
+ return BatchProjectCleanerQueue.instance;
+ }
+}
diff --git a/packages/shared/src/server/redis/getQueue.ts b/packages/shared/src/server/redis/getQueue.ts
index 249c6a0309..1e4b7876a4 100644
--- a/packages/shared/src/server/redis/getQueue.ts
+++ b/packages/shared/src/server/redis/getQueue.ts
@@ -29,6 +29,7 @@ import { EntityChangeQueue } from "./entityChangeQueue";
import { DatasetDeleteQueue } from "./datasetDelete";
import { EventPropagationQueue } from "./eventPropagationQueue";
import { NotificationQueue } from "./notificationQueue";
+import { BatchProjectCleanerQueue } from "./batchProjectCleanerQueue";
// IngestionQueue, OtelIngestionQueue, and TraceUpsert are sharded and require a sharding key
// Use IngestionQueue.getInstance({ shardName: queueName }) or TraceUpsertQueue.getInstance({ shardName: queueName }) directly instead
@@ -99,6 +100,8 @@ export function getQueue(
return EventPropagationQueue.getInstance();
case QueueName.NotificationQueue:
return NotificationQueue.getInstance();
+ case QueueName.BatchProjectCleanerQueue:
+ return BatchProjectCleanerQueue.getInstance();
default: {
const _exhaustiveCheckDefault: never = queueName;
throw new Error(`Queue ${queueName} not found`);
diff --git a/worker/src/__tests__/batchProjectCleaner.test.ts b/worker/src/__tests__/batchProjectCleaner.test.ts
index ae58c4f117..7037cca64f 100644
--- a/worker/src/__tests__/batchProjectCleaner.test.ts
+++ b/worker/src/__tests__/batchProjectCleaner.test.ts
@@ -1,19 +1,13 @@
-import { expect, describe, it, afterEach } from "vitest";
+import { expect, describe, it } from "vitest";
import { randomUUID } from "crypto";
-import {
- BatchProjectCleaner,
- BATCH_DELETION_TABLES,
- BATCH_PROJECT_CLEANER_LOCK_PREFIX,
-} from "../features/batch-project-cleaner";
+import { BatchProjectCleaner } 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,
@@ -28,33 +22,17 @@ async function getClickhouseCount(
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 () => {
+ it("should do nothing 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();
+ // Should complete without error
+ await BatchProjectCleaner.processBatch(TEST_TABLE);
});
- it("should return sleep interval when deleted project has no ClickHouse data", async () => {
+ it("should do nothing when deleted project has no ClickHouse data", async () => {
// Create and soft-delete a project
const { projectId } = await createOrgProjectAndApiKey();
await prisma.project.update({
@@ -62,16 +40,8 @@ describe("BatchProjectCleaner", () => {
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();
+ // Should complete without error
+ await BatchProjectCleaner.processBatch(TEST_TABLE);
});
it("should delete traces for soft-deleted project", async () => {
@@ -93,17 +63,11 @@ describe("BatchProjectCleaner", () => {
expect(countBefore).toBe(2);
// Run processBatch
- const cleaner = new BatchProjectCleaner(TEST_TABLE);
- const nextDelayMs = await cleaner.processBatch();
+ await BatchProjectCleaner.processBatch(TEST_TABLE);
// 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 () => {
@@ -131,8 +95,7 @@ describe("BatchProjectCleaner", () => {
expect(await getClickhouseCount(TEST_TABLE, activeProjectId)).toBe(3);
// Run processBatch
- const cleaner = new BatchProjectCleaner(TEST_TABLE);
- await cleaner.processBatch();
+ await BatchProjectCleaner.processBatch(TEST_TABLE);
// Verify only deleted project's traces were removed
expect(await getClickhouseCount(TEST_TABLE, deletedProjectId)).toBe(0);
@@ -161,67 +124,11 @@ describe("BatchProjectCleaner", () => {
]);
// Run processBatch
- const cleaner = new BatchProjectCleaner(TEST_TABLE);
- const nextDelayMs = await cleaner.processBatch();
+ await BatchProjectCleaner.processBatch(TEST_TABLE);
// 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/app.ts b/worker/src/app.ts
index 4f9b150f4c..764e2f1530 100644
--- a/worker/src/app.ts
+++ b/worker/src/app.ts
@@ -28,6 +28,7 @@ import {
PostHogIntegrationQueue,
MixpanelIntegrationQueue,
QueueName,
+ QueueJobs,
logger,
BlobStorageIntegrationQueue,
DeadLetterRetryQueue,
@@ -36,6 +37,7 @@ import {
TraceUpsertQueue,
CloudFreeTierUsageThresholdQueue,
EventPropagationQueue,
+ BatchProjectCleanerQueue,
} from "@langfuse/shared/src/server";
import { env } from "./env";
import { ingestionQueueProcessorBuilder } from "./queues/ingestionQueue";
@@ -73,10 +75,8 @@ 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";
+import { BATCH_DELETION_TABLES } from "./features/batch-project-cleaner";
+import { batchProjectCleanerProcessor } from "./queues/batchProjectCleanerQueue";
const app = express();
@@ -545,18 +545,30 @@ if (env.LANGFUSE_MUTATION_MONITOR_ENABLED === "true") {
}
// 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) {
- // Only start the events table cleaner if the events table experiment is enabled
- if (
- table !== "events" ||
- env.LANGFUSE_EXPERIMENT_INSERT_INTO_EVENTS_TABLE === "true"
- ) {
- const cleaner = new BatchProjectCleaner(table);
- batchProjectCleaners.push(cleaner);
- cleaner.start();
+ WorkerManager.register(
+ QueueName.BatchProjectCleanerQueue,
+ batchProjectCleanerProcessor,
+ );
+
+ // Schedule repeatable jobs for each table
+ const queue = BatchProjectCleanerQueue.getInstance();
+ if (queue) {
+ const tables = BATCH_DELETION_TABLES.filter(
+ (t) =>
+ t !== "events" ||
+ env.LANGFUSE_EXPERIMENT_INSERT_INTO_EVENTS_TABLE === "true",
+ );
+ for (const table of tables) {
+ queue
+ .upsertJobScheduler(
+ `batch-project-cleaner-${table}`,
+ { every: env.LANGFUSE_BATCH_PROJECT_CLEANER_SLEEP_ON_EMPTY_MS },
+ { name: QueueJobs.BatchProjectCleanerJob, data: { table } },
+ )
+ .catch((err) =>
+ logger.error(`Error scheduling batch-project-cleaner-${table}`, err),
+ );
}
}
}
diff --git a/worker/src/features/batch-project-cleaner/index.ts b/worker/src/features/batch-project-cleaner/index.ts
index 8418e24449..009024a8f6 100644
--- a/worker/src/features/batch-project-cleaner/index.ts
+++ b/worker/src/features/batch-project-cleaner/index.ts
@@ -7,8 +7,6 @@ import {
} 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",
@@ -19,9 +17,6 @@ export const BATCH_DELETION_TABLES = [
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;
@@ -30,112 +25,48 @@ interface ProjectCount {
/**
* 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.
+ * Each invocation processes one table (traces, observations, scores, events).
+ * BullMQ handles distributed locking to ensure only one worker processes
+ * a given table's job 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
+ * 1. Query PG for projects with deleted_at set
+ * 2. Query ClickHouse for counts per project
+ * 3. Execute DELETE
+ * 4. 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.
- },
- );
- }
-
+export class BatchProjectCleaner {
/**
- * Start the batch cleaner service
+ * Process a batch of deleted projects for a specific table.
*/
- 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();
- }
+ public static async processBatch(
+ tableName: BatchDeletionTable,
+ ): Promise<void> {
+ const instanceName = `BatchProjectCleaner(${tableName})`;
- /**
- * 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)
+ // Step 1: Query PG for deleted projects
let deletedProjects: Array<{ id: string }>;
try {
- deletedProjects = await this.getDeletedProjects();
+ deletedProjects = await BatchProjectCleaner.getDeletedProjects();
} catch (error) {
- logger.error(`${this.instanceName}: Failed to query deleted projects`, {
+ logger.error(`${instanceName}: Failed to query deleted projects`, {
error,
});
traceException(error);
- return env.LANGFUSE_BATCH_PROJECT_CLEANER_SLEEP_ON_EMPTY_MS;
+ return;
}
- // Step 2: Query ClickHouse for counts per project (no lock needed)
+ // Step 2: Query ClickHouse for counts per project
let initialCounts: Map<string, number>;
try {
- initialCounts = await this.getProjectCounts(
+ initialCounts = await BatchProjectCleaner.getProjectCounts(
+ tableName,
deletedProjects.map((p) => p.id),
);
} catch (error) {
- logger.error(
- `${this.instanceName}: Failed to query ClickHouse counts`,
- error,
- );
+ logger.error(`${instanceName}: Failed to query ClickHouse counts`, error);
traceException(error);
- return env.LANGFUSE_BATCH_PROJECT_CLEANER_SLEEP_ON_EMPTY_MS;
+ return;
}
// Filter to only projects that have data
@@ -145,91 +76,83 @@ export class BatchProjectCleaner extends PeriodicRunner {
if (projectIdsWithData.length === 0) {
logger.info(
- `${this.instanceName}: No data found for deleted projects in ${this.tableName}`,
+ `${instanceName}: No data found for deleted projects in ${tableName}`,
);
- return env.LANGFUSE_BATCH_PROJECT_CLEANER_SLEEP_ON_EMPTY_MS;
+ return;
}
- // Step 3 & 4: Execute DELETE under distributed lock
- const result = await this.lock.withLock(async () => {
- try {
- await this.executeDelete(projectIdsWithData);
+ // Step 3: Execute DELETE
+ try {
+ await BatchProjectCleaner.executeDelete(tableName, 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,
- });
+ const totalRows = Array.from(initialCounts.values()).reduce(
+ (sum, count) => sum + count,
+ 0,
+ );
+ logger.info(`${instanceName}: Batch deletion completed`, {
+ table: tableName,
+ projectsProcessed: projectIdsWithData.length,
+ totalRowsTargeted: totalRows,
+ });
+ } catch (deleteError) {
+ // Step 4: On failure, re-run count query to determine partial success
+ logger.warn(
+ `${instanceName}: DELETE failed, checking for partial success`,
+ deleteError,
+ );
+ traceException(deleteError);
- 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,
+ // Record DELETE failure metric
+ recordIncrement("langfuse.batch_project_cleaner.delete_failures", 1, {
+ table: tableName,
+ });
+
+ let finalCounts: Map<string, number> | undefined;
+ try {
+ finalCounts = await BatchProjectCleaner.getProjectCounts(
+ tableName,
+ projectIdsWithData,
);
- traceException(deleteError);
+ } catch (countError) {
+ // Can't determine partial success
+ logger.error(
+ `${instanceName}: Failed to re-query counts after DELETE failure`,
+ countError,
+ );
+ }
- // Record DELETE failure metric
- recordIncrement("langfuse.batch_project_cleaner.delete_failures", 1, {
- table: this.tableName,
+ // 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: tableName },
+ );
+ logger.warn(`${instanceName}: Partial deletion completed`, {
+ table: tableName,
+ incompleteProjectCount: incompleteProjects.length,
+ incompleteProjects: incompleteProjects.slice(0, 10), // Log first 10
+ error: (deleteError as Error).message,
});
-
- 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;
+ } else {
+ logger.info(
+ `${instanceName}: All projects cleaned successfully on re-check`,
+ );
}
- });
- if (result === null) {
- logger.info(
- `${this.instanceName}: Lock not acquired, another worker is processing`,
- );
- return env.LANGFUSE_BATCH_PROJECT_CLEANER_SLEEP_ON_EMPTY_MS;
+ // Re-throw so BullMQ marks job as failed
+ throw deleteError;
}
-
- return result;
}
- private async getDeletedProjects(): Promise<Array<{ id: string }>> {
+ private static async getDeletedProjects(): Promise<Array<{ id: string }>> {
return prisma.project.findMany({
select: { id: true },
where: {
@@ -239,7 +162,8 @@ export class BatchProjectCleaner extends PeriodicRunner {
});
}
- private async getProjectCounts(
+ private static async getProjectCounts(
+ tableName: BatchDeletionTable,
projectIds: string[],
): Promise<Map<string, number>> {
if (projectIds.length === 0) {
@@ -248,7 +172,7 @@ export class BatchProjectCleaner extends PeriodicRunner {
const query = `
SELECT project_id, count() as count
- FROM ${this.tableName}
+ FROM ${tableName}
WHERE project_id IN ({projectIds: Array(String)})
GROUP BY project_id
ORDER BY count DESC
@@ -259,7 +183,7 @@ export class BatchProjectCleaner extends PeriodicRunner {
params: { projectIds },
tags: {
feature: "batch-project-cleaner",
- table: this.tableName,
+ table: tableName,
operation: "count",
},
});
@@ -272,13 +196,16 @@ export class BatchProjectCleaner extends PeriodicRunner {
return counts;
}
- private async executeDelete(projectIds: string[]): Promise<void> {
+ private static async executeDelete(
+ tableName: BatchDeletionTable,
+ projectIds: string[],
+ ): Promise<void> {
if (projectIds.length === 0) {
return;
}
const query = `
- DELETE FROM ${this.tableName}
+ DELETE FROM ${tableName}
WHERE project_id IN ({projectIds: Array(String)})
`;
@@ -290,7 +217,7 @@ export class BatchProjectCleaner extends PeriodicRunner {
},
tags: {
feature: "batch-project-cleaner",
- table: this.tableName,
+ table: tableName,
operation: "delete",
},
});
diff --git a/worker/src/queues/batchProjectCleanerQueue.ts b/worker/src/queues/batchProjectCleanerQueue.ts
new file mode 100644
index 0000000000..da2c640248
--- /dev/null
+++ b/worker/src/queues/batchProjectCleanerQueue.ts
@@ -0,0 +1,23 @@
+import { Processor } from "bullmq";
+import {
+ logger,
+ QueueJobs,
+ BatchProjectCleanerJobType,
+} from "@langfuse/shared/src/server";
+import {
+ BatchProjectCleaner,
+ BatchDeletionTable,
+} from "../features/batch-project-cleaner";
+
+export const batchProjectCleanerProcessor: Processor = async (job) => {
+ if (job.name === QueueJobs.BatchProjectCleanerJob) {
+ const { table } = job.data as BatchProjectCleanerJobType;
+ logger.info(`Executing BatchProjectCleaner for ${table}`);
+ try {
+ await BatchProjectCleaner.processBatch(table as BatchDeletionTable);
+ } catch (error) {
+ logger.error(`Error executing BatchProjectCleaner for ${table}`, error);
+ throw error;
+ }
+ }
+};
diff --git a/worker/src/utils/RedisLock.ts b/worker/src/utils/RedisLock.ts
deleted file mode 100644
index e95eebd961..0000000000
--- a/worker/src/utils/RedisLock.ts
+++ /dev/null
@@ -1,179 +0,0 @@
-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 d45269554a..105d2efb42 100644
--- a/worker/src/utils/shutdown.ts
+++ b/worker/src/utils/shutdown.ts
@@ -10,7 +10,6 @@ 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...`);
@@ -23,11 +22,6 @@ 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();