Langfuse SDK best practices, patterns, and idiomatic usage.
Use when learning Langfuse SDK patterns, implementing proper tracing,
or following best practices for LLM observability.
Trigger with phrases like "langfuse patterns", "langfuse best practices",
"langfuse SDK guide", "how to use langfuse", "langfuse idioms".
Production-quality patterns for the Langfuse SDK: singleton clients, the observe wrapper, startActiveObservation for nested traces, session tracking, graceful shutdown, and error-safe tracing.
Prerequisites
Completed langfuse-install-auth setup
Understanding of async/await patterns
For v4+: @langfuse/tracing, @langfuse/otel, @opentelemetry/sdk-node
Instructions
Pattern 1: Singleton Client with Graceful Shutdown
// src/lib/langfuse.ts -- single file, import everywhere
import { LangfuseClient } from "@langfuse/client";
import { LangfuseSpanProcessor } from "@langfuse/otel";
import { NodeSDK } from "@opentelemetry/sdk-node";
// Singleton client for prompts, datasets, scores
let client: LangfuseClient | null = null;
export function getLangfuseClient(): LangfuseClient {
if (!client) {
client = new LangfuseClient();
}
return client;
}
// One-time OTel setup (call at app entry point)
let sdk: NodeSDK | null = null;
export function initTracing(): NodeSDK {
if (!sdk) {
sdk = new NodeSDK({
spanProcessors: [new LangfuseSpanProcessor()],
});
sdk.start();
// Graceful shutdown on process exit
const shutdown = async () => {
await sdk?.shutdown();
process.exit(0);
};
process.on("SIGTERM", shutdown);
process.on("SIGINT", shutdown);
}
return sdk;
}
Legacy v3 singleton:
import { Langfuse } from "langfuse";
let instance: Langfuse | null = null;
export function getLangfuse(): Langfuse {
if (!instance) {
instance = new Langfuse({
flushAt: 15,
flushInterval: 10000,
});
process.on("beforeExit", () => instance?.shutdownAsync());
}
return instance;
}
Pattern 2: observe Wrapper for Existing Functions
The observe wrapper is the most ergonomic way to add tracing. It wraps any function and auto-creates a span.