Skip to content

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

chore: export core information tables to S3 daily (#4821)

Steffen Schmitz51595eb15d22
diff --git a/packages/shared/src/env.ts b/packages/shared/src/env.ts
index 0e0f6e50f0..09351df9d3 100644
--- a/packages/shared/src/env.ts
+++ b/packages/shared/src/env.ts
@@ -66,6 +66,10 @@ const EnvSchema = z.object({
.default("false"),
LANGFUSE_USE_AZURE_BLOB: z.enum(["true", "false"]).default("false"),
STRIPE_SECRET_KEY: z.string().optional(),
+
+ LANGFUSE_S3_CORE_DATA_EXPORT_IS_ENABLED: z
+ .enum(["true", "false"])
+ .default("false"),
});
export const env: z.infer<typeof EnvSchema> =
diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.ts
index f46b724003..82750156ab 100644
--- a/packages/shared/src/server/index.ts
+++ b/packages/shared/src/server/index.ts
@@ -32,6 +32,7 @@ export * from "./redis/legacyIngestion";
export * from "./redis/ingestionQueue";
export * from "./redis/postHogIntegrationQueue";
export * from "./redis/postHogIntegrationProcessingQueue";
+export * from "./redis/coreDataS3ExportQueue";
export * from "./redis/experimentCreateQueue";
export * from "./auth/types";
export * from "./ingestion/legacy/index";
diff --git a/packages/shared/src/server/queues.ts b/packages/shared/src/server/queues.ts
index 2475751fe3..6a696be96d 100644
--- a/packages/shared/src/server/queues.ts
+++ b/packages/shared/src/server/queues.ts
@@ -118,6 +118,7 @@ export enum QueueName {
ExperimentCreate = "experiment-create-queue",
PostHogIntegrationQueue = "posthog-integration-queue",
PostHogIntegrationProcessingQueue = "posthog-integration-processing-queue",
+ CoreDataS3ExportQueue = "core-data-s3-export-queue",
}
export enum QueueJobs {
@@ -134,6 +135,7 @@ export enum QueueJobs {
ExperimentCreateJob = "experiment-create-job",
PostHogIntegrationJob = "posthog-integration-job",
PostHogIntegrationProcessingJob = "posthog-integration-processing-job",
+ CoreDataS3ExportJob = "core-data-s3-export-job",
}
export type TQueueJobTypes = {
diff --git a/packages/shared/src/server/redis/coreDataS3ExportQueue.ts b/packages/shared/src/server/redis/coreDataS3ExportQueue.ts
new file mode 100644
index 0000000000..b0bcb83eb6
--- /dev/null
+++ b/packages/shared/src/server/redis/coreDataS3ExportQueue.ts
@@ -0,0 +1,60 @@
+import { Queue } from "bullmq";
+import { QueueName, QueueJobs } from "../queues";
+import { createNewRedisInstance, redisQueueRetryOptions } from "./redis";
+import { logger } from "../logger";
+import { env } from "../../env";
+
+export class CoreDataS3ExportQueue {
+ private static instance: Queue | null = null;
+
+ public static getInstance(): Queue | null {
+ if (env.LANGFUSE_S3_CORE_DATA_EXPORT_IS_ENABLED !== "true") {
+ return null;
+ }
+
+ if (CoreDataS3ExportQueue.instance) {
+ return CoreDataS3ExportQueue.instance;
+ }
+
+ const newRedis = createNewRedisInstance({
+ enableOfflineQueue: false,
+ ...redisQueueRetryOptions,
+ });
+
+ CoreDataS3ExportQueue.instance = newRedis
+ ? new Queue(QueueName.CoreDataS3ExportQueue, {
+ connection: newRedis,
+ defaultJobOptions: {
+ removeOnComplete: true,
+ removeOnFail: 100,
+ attempts: 5,
+ backoff: {
+ type: "exponential",
+ delay: 5000,
+ },
+ },
+ })
+ : null;
+
+ CoreDataS3ExportQueue.instance?.on("error", (err) => {
+ logger.error("CoreDataS3ExportQueue error", err);
+ });
+
+ if (CoreDataS3ExportQueue.instance) {
+ logger.debug("Scheduling jobs for CoreDataS3ExportQueue");
+ CoreDataS3ExportQueue.instance
+ .add(
+ QueueJobs.CoreDataS3ExportJob,
+ {},
+ {
+ repeat: { pattern: "30 4 * * *" }, // every day at 4:30am
+ },
+ )
+ .catch((err) => {
+ logger.error("Error adding CoreDataS3ExportJob schedule", err);
+ });
+ }
+
+ return CoreDataS3ExportQueue.instance;
+ }
+}
diff --git a/packages/shared/src/server/redis/getQueue.ts b/packages/shared/src/server/redis/getQueue.ts
index b7ae7f0006..7ae7b553b7 100644
--- a/packages/shared/src/server/redis/getQueue.ts
+++ b/packages/shared/src/server/redis/getQueue.ts
@@ -12,6 +12,7 @@ import { TraceDeleteQueue } from "./traceDelete";
import { ProjectDeleteQueue } from "./projectDelete";
import { PostHogIntegrationQueue } from "./postHogIntegrationQueue";
import { PostHogIntegrationProcessingQueue } from "./postHogIntegrationProcessingQueue";
+import { CoreDataS3ExportQueue } from "./coreDataS3ExportQueue";
export function getQueue(queueName: QueueName): Queue | null {
switch (queueName) {
@@ -41,6 +42,8 @@ export function getQueue(queueName: QueueName): Queue | null {
return PostHogIntegrationProcessingQueue.getInstance();
case QueueName.IngestionSecondaryQueue:
return SecondaryIngestionQueue.getInstance();
+ case QueueName.CoreDataS3ExportQueue:
+ return CoreDataS3ExportQueue.getInstance();
default:
const exhaustiveCheckDefault: never = queueName;
throw new Error(`Queue ${queueName} not found`);
diff --git a/worker/src/app.ts b/worker/src/app.ts
index 4a5df7b400..24f935f9e5 100644
--- a/worker/src/app.ts
+++ b/worker/src/app.ts
@@ -24,6 +24,7 @@ import {
QueueName,
logger,
PostHogIntegrationQueue,
+ CoreDataS3ExportQueue,
} from "@langfuse/shared/src/server";
import { env } from "./env";
import { ingestionQueueProcessorBuilder } from "./queues/ingestionQueue";
@@ -35,6 +36,7 @@ import {
postHogIntegrationProcessingProcessor,
postHogIntegrationProcessor,
} from "./queues/postHogIntegrationQueue";
+import { coreDataS3ExportProcessor } from "./queues/coreDataS3ExportQueue";
const app = express();
@@ -69,6 +71,15 @@ if (env.QUEUE_CONSUMER_TRACE_UPSERT_QUEUE_IS_ENABLED === "true") {
);
}
+if (env.LANGFUSE_S3_CORE_DATA_EXPORT_IS_ENABLED === "true") {
+ // Instantiate the queue to trigger scheduled jobs
+ CoreDataS3ExportQueue.getInstance();
+ WorkerManager.register(
+ QueueName.CoreDataS3ExportQueue,
+ coreDataS3ExportProcessor,
+ );
+}
+
if (env.QUEUE_CONSUMER_TRACE_DELETE_QUEUE_IS_ENABLED === "true") {
WorkerManager.register(QueueName.TraceDelete, traceDeleteProcessor, {
concurrency: env.LANGFUSE_TRACE_DELETE_CONCURRENCY,
diff --git a/worker/src/env.ts b/worker/src/env.ts
index 796cf09af5..4de594bca7 100644
--- a/worker/src/env.ts
+++ b/worker/src/env.ts
@@ -152,6 +152,20 @@ const EnvSchema = z.object({
LANGFUSE_POSTGRES_INGESTION_ENABLED: z
.enum(["true", "false"])
.default("false"),
+
+ // Core data S3 upload - only used internally
+ LANGFUSE_S3_CORE_DATA_EXPORT_IS_ENABLED: z
+ .enum(["true", "false"])
+ .default("false"),
+ LANGFUSE_S3_CORE_DATA_UPLOAD_BUCKET: z.string().optional(),
+ LANGFUSE_S3_CORE_DATA_UPLOAD_PREFIX: z.string().default(""),
+ LANGFUSE_S3_CORE_DATA_UPLOAD_REGION: z.string().optional(),
+ LANGFUSE_S3_CORE_DATA_UPLOAD_ENDPOINT: z.string().optional(),
+ LANGFUSE_S3_CORE_DATA_UPLOAD_ACCESS_KEY_ID: z.string().optional(),
+ LANGFUSE_S3_CORE_DATA_UPLOAD_SECRET_ACCESS_KEY: z.string().optional(),
+ LANGFUSE_S3_CORE_DATA_UPLOAD_FORCE_PATH_STYLE: z
+ .enum(["true", "false"])
+ .default("false"),
});
export const env: z.infer<typeof EnvSchema> =
diff --git a/worker/src/queues/coreDataS3ExportQueue.ts b/worker/src/queues/coreDataS3ExportQueue.ts
new file mode 100644
index 0000000000..574278f09e
--- /dev/null
+++ b/worker/src/queues/coreDataS3ExportQueue.ts
@@ -0,0 +1,131 @@
+import { Job, Processor } from "bullmq";
+import {
+ logger,
+ StorageService,
+ StorageServiceFactory,
+} from "@langfuse/shared/src/server";
+import { prisma } from "@langfuse/shared/src/db";
+import { env } from "../env";
+
+let s3StorageServiceClient: StorageService;
+
+const getS3StorageServiceClient = (bucketName: string): StorageService => {
+ if (!s3StorageServiceClient) {
+ s3StorageServiceClient = StorageServiceFactory.getInstance({
+ bucketName,
+ accessKeyId: env.LANGFUSE_S3_CORE_DATA_UPLOAD_ACCESS_KEY_ID,
+ secretAccessKey: env.LANGFUSE_S3_CORE_DATA_UPLOAD_SECRET_ACCESS_KEY,
+ endpoint: env.LANGFUSE_S3_CORE_DATA_UPLOAD_ENDPOINT,
+ region: env.LANGFUSE_S3_CORE_DATA_UPLOAD_REGION,
+ forcePathStyle:
+ env.LANGFUSE_S3_CORE_DATA_UPLOAD_FORCE_PATH_STYLE === "true",
+ });
+ }
+ return s3StorageServiceClient;
+};
+
+export const coreDataS3ExportProcessor: Processor = async (
+ job: Job,
+): Promise<void> => {
+ if (!env.LANGFUSE_S3_CORE_DATA_UPLOAD_BUCKET) {
+ logger.error("No bucket name provided for core data S3 export");
+ throw new Error(
+ "Must provide LANGFUSE_S3_CORE_DATA_UPLOAD_BUCKET to use core data S3 exports",
+ );
+ }
+
+ logger.info("Starting core data S3 export");
+
+ const s3Client = getS3StorageServiceClient(
+ env.LANGFUSE_S3_CORE_DATA_UPLOAD_BUCKET,
+ );
+
+ // Fetch table data
+ const [
+ projects,
+ users,
+ organizations,
+ orgMemberships,
+ projectMemberships,
+ prompts,
+ ] = await Promise.all([
+ prisma.project.findMany({
+ select: {
+ id: true,
+ name: true,
+ orgId: true,
+ createdAt: true,
+ updatedAt: true,
+ },
+ }),
+ prisma.user.findMany({
+ select: {
+ id: true,
+ name: true,
+ admin: true,
+ email: true,
+ featureFlags: true,
+ createdAt: true,
+ updatedAt: true,
+ },
+ }),
+ prisma.organization.findMany({
+ select: {
+ id: true,
+ name: true,
+ cloudConfig: true,
+ createdAt: true,
+ updatedAt: true,
+ },
+ }),
+ prisma.organizationMembership.findMany({
+ select: {
+ id: true,
+ role: true,
+ orgId: true,
+ userId: true,
+ createdAt: true,
+ updatedAt: true,
+ },
+ }),
+ prisma.projectMembership.findMany({
+ select: {
+ role: true,
+ projectId: true,
+ userId: true,
+ createdAt: true,
+ updatedAt: true,
+ },
+ }),
+ prisma.prompt.findMany({
+ select: {
+ id: true,
+ name: true,
+ projectId: true,
+ createdAt: true,
+ updatedAt: true,
+ },
+ }),
+ ]);
+
+ // Iterate through the tables and upload them to S3 as JSONLs
+ await Promise.all(
+ Object.entries({
+ projects,
+ users,
+ organizations,
+ orgMemberships,
+ projectMemberships,
+ prompts,
+ }).map(async ([key, value]) =>
+ s3Client.uploadFile({
+ fileName: `${env.LANGFUSE_S3_CORE_DATA_UPLOAD_PREFIX}${key}.jsonl`,
+ fileType: "application/x-ndjson",
+ data: value.map((item) => JSON.stringify(item)).join("\n"),
+ expiresInSeconds: 1, // not used as we only upload
+ }),
+ ),
+ );
+
+ logger.info("Finished core data S3 export");
+};