Skip to content

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

feat: backup redis queues to postgres (#4943)

Max Deichmanncf29c6b7e447
diff --git a/packages/shared/prisma/generated/types.ts b/packages/shared/prisma/generated/types.ts
index 359651d4cd..99443630bf 100644
--- a/packages/shared/prisma/generated/types.ts
+++ b/packages/shared/prisma/generated/types.ts
@@ -479,6 +479,13 @@ export type Prompt = {
tags: Generated<string[]>;
labels: Generated<string[]>;
};
+export type QueueBackUp = {
+ id: string;
+ project_id: string | null;
+ queue_name: string;
+ content: unknown;
+ created_at: Generated<Timestamp>;
+};
export type Score = {
id: string;
timestamp: Generated<Timestamp>;
@@ -628,6 +635,7 @@ export type DB = {
project_memberships: ProjectMembership;
projects: Project;
prompts: Prompt;
+ queue_backups: QueueBackUp;
score_configs: ScoreConfig;
scores: Score;
Session: Session;
diff --git a/packages/shared/prisma/migrations/20250108220721_add_queue_backup_table/migration.sql b/packages/shared/prisma/migrations/20250108220721_add_queue_backup_table/migration.sql
new file mode 100644
index 0000000000..0269726cdf
--- /dev/null
+++ b/packages/shared/prisma/migrations/20250108220721_add_queue_backup_table/migration.sql
@@ -0,0 +1,13 @@
+-- CreateTable
+CREATE TABLE "queue_backups" (
+ "id" TEXT NOT NULL,
+ "project_id" TEXT,
+ "queue_name" TEXT NOT NULL,
+ "content" JSONB NOT NULL,
+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+
+ CONSTRAINT "queue_backups_pkey" PRIMARY KEY ("id")
+);
+
+-- AddForeignKey
+ALTER TABLE "traces" ADD CONSTRAINT "traces_session_id_project_id_fkey" FOREIGN KEY ("session_id", "project_id") REFERENCES "trace_sessions"("id", "project_id") ON DELETE RESTRICT ON UPDATE CASCADE;
diff --git a/packages/shared/prisma/schema.prisma b/packages/shared/prisma/schema.prisma
index 8333d58335..b696aa2fc9 100644
--- a/packages/shared/prisma/schema.prisma
+++ b/packages/shared/prisma/schema.prisma
@@ -1017,3 +1017,14 @@ model ObservationMedia {
@@index([projectId, observationId])
@@map("observation_media")
}
+
+model QueueBackUp {
+ id String @id @default(cuid())
+ projectId String? @map("project_id")
+ queueName String @map("queue_name")
+ content Json
+
+ createdAt DateTime @default(now()) @map("created_at")
+
+ @@map("queue_backups")
+}
diff --git a/web/src/pages/api/admin/bullmq/index.ts b/web/src/pages/api/admin/bullmq/index.ts
index badca9c191..6526b0a2d8 100644
--- a/web/src/pages/api/admin/bullmq/index.ts
+++ b/web/src/pages/api/admin/bullmq/index.ts
@@ -2,11 +2,22 @@ import { type NextApiRequest, type NextApiResponse } from "next";
import { z } from "zod";
import { logger, QueueName, getQueue } from "@langfuse/shared/src/server";
import { env } from "@/src/env.mjs";
+import { prisma } from "@langfuse/shared/src/db";
/*
This API route is used by Langfuse Cloud to retry failed bullmq jobs.
*/
+const BullStatus = z.enum([
+ "completed",
+ "failed",
+ "active",
+ "delayed",
+ "prioritized",
+ "paused",
+ "wait",
+]);
+
const ManageBullBody = z.discriminatedUnion("action", [
z.object({
action: z.literal("retry"),
@@ -15,15 +26,18 @@ const ManageBullBody = z.discriminatedUnion("action", [
z.object({
action: z.literal("remove"),
queueNames: z.array(z.string()),
- bullStatus: z.enum([
- "completed",
- "failed",
- "active",
- "delayed",
- "prioritized",
- "paused",
- "wait",
- ]),
+ bullStatus: BullStatus,
+ }),
+ z.object({
+ action: z.literal("backup"),
+ queueName: z.string(),
+ bullStatus: BullStatus,
+ numberOfEvents: z.number(),
+ }),
+ z.object({
+ action: z.literal("restore"),
+ queueName: z.string(),
+ numberOfEvents: z.number(),
}),
]);
@@ -162,6 +176,21 @@ export default async function handler(
return res.status(200).json({ message: "Retried all jobs" });
}
+ if (req.method === "POST" && body.data.action === "backup") {
+ await backUpEvents(
+ body.data.queueName as QueueName,
+ body.data.numberOfEvents,
+ body.data.bullStatus,
+ );
+ }
+
+ if (req.method === "POST" && body.data.action === "restore") {
+ await restoreEvents(
+ body.data.queueName as QueueName,
+ body.data.numberOfEvents,
+ );
+ }
+
// return not implemented error
res.status(404).json({ error: "Action does not exist" });
} catch (e) {
@@ -169,3 +198,69 @@ export default async function handler(
res.status(500).json({ error: e });
}
}
+
+const backUpEvents = async (
+ queueName: QueueName,
+ numberOfEvents: number,
+ bullStatus: z.infer<typeof BullStatus>,
+) => {
+ const queue = getQueue(queueName);
+ let processedEvents = 0;
+ const batchSize = 1000;
+
+ while (processedEvents < numberOfEvents) {
+ const remainingEvents = numberOfEvents - processedEvents;
+ const currentBatchSize = Math.min(batchSize, remainingEvents);
+
+ const events = await queue?.getJobs(
+ [bullStatus],
+ 0,
+ currentBatchSize,
+ true,
+ );
+
+ if (!events || events.length === 0) {
+ break;
+ }
+
+ await prisma.queueBackUp.createMany({
+ data: events.map((event) => ({
+ queueName,
+ content: event,
+ projectId: event.data.projectId ?? undefined,
+ createdAt: new Date(),
+ })),
+ });
+
+ // remove events from the queue but might throw in case if the job is already processing
+ await Promise.all(
+ events.map(async (event) => {
+ try {
+ await event.remove();
+ } catch (error) {
+ logger.error(`Failed to remove event ${event.id}:`, error);
+ }
+ }),
+ );
+
+ processedEvents += events.length;
+ }
+};
+
+const restoreEvents = async (queueName: QueueName, numberOfEvents: number) => {
+ const queue = getQueue(queueName);
+
+ const queueBackUp = await prisma.queueBackUp.findMany({
+ where: {
+ queueName,
+ },
+ orderBy: {
+ createdAt: "desc",
+ },
+ take: numberOfEvents,
+ });
+
+ await queue?.addBulk(
+ queueBackUp.map((event) => ({ name: queueName, data: event.content })),
+ );
+};