Install any skill in seconds. Free to start, no credit card required.
Get Started Free →Production-grade Langfuse architecture patterns and best practices. Use when designing LLM observability infrastructure, planning Langfuse deployment, or implementing enterprise-grade tracing architecture. Trigger with phrases like "langfuse architecture", "langfuse design", "langfuse infrastructure", "langfuse enterprise", "langfuse at scale".
.claude/skills/jeremylongshore-langfuse-reference-architecture/SKILL.md| Test case | Without → With | Effect | Δ tokens | Δ turns |
|---|---|---|---|---|
| case-01 | ✗→✓ | ▲ Improved | -18% | 0% |
| case-09 | ✗→✓ | ▲ Improved | 77% | 0% |
| case-13 | ✗→✓ | ▲ Improved | 48% | 0% |
| case-15 | ✗→✓ | ▲ Improved | 36% | 0% |
| case-23 | ✗→✓ | ▲ Improved | 26% | 0% |
Production-grade architecture patterns for Langfuse LLM observability: singleton SDK, context propagation with AsyncLocalStorage, cross-service trace correlation, multi-environment configurations, and scale strategies.
@langfuse/tracing, @langfuse/otel, @opentelemetry/sdk-node| Tier | Scale | Architecture | Langfuse Host | |------|-------|-------------|---------------| | Starter | < 100K traces/day | Direct SDK, Cloud | Langfuse Cloud | | Growth | 100K-1M traces/day | Singleton + batching | Cloud or Self-hosted | | Enterprise | 1M+ traces/day | Queue-buffered + sampling | Self-hosted (HA) |
typescript// src/lib/tracing.ts -- Single module for all tracing import { LangfuseClient } from "@langfuse/client"; import { LangfuseSpanProcessor } from "@langfuse/otel"; import { NodeSDK } from "@opentelemetry/sdk-node"; import { AsyncLocalStorage } from "async_hooks"; // Singleton OTel SDK let sdk: NodeSDK | null = null; export function initTracing() { if (sdk) return sdk; sdk = new NodeSDK({ spanProcessors: [ new LangfuseSpanProcessor({ exportIntervalMillis: 5000, maxExportBatchSize: 50, }), ], }); sdk.start(); // Graceful shutdown for (const signal of ["SIGTERM", "SIGINT"]) { process.on(signal, async () => { console.log(`Received ${signal}, flushing traces...`); await sdk?.shutdown(); process.exit(0); }); } return sdk; } // Singleton client for non-tracing operations let client: LangfuseClient | null = null; export function getLangfuseClient(): LangfuseClient { if (!client) client = new LangfuseClient(); return client; } // Request context for user/session tracking interface RequestContext { userId?: string; sessionId?: string; requestId: string; } const requestStore = new AsyncLocalStorage<RequestContext>(); export function getRequestContext(): RequestContext | undefined { return requestStore.getStore(); } export function runWithContext<T>(ctx: RequestContext, fn: () => T): T { return requestStore.run(ctx, fn); }
typescript// src/middleware/tracing.ts import { startActiveObservation, updateActiveObservation } from "@langfuse/tracing"; import { runWithContext, getRequestContext } from "../lib/tracing"; import { randomUUID } from "crypto"; import type { Request, Response, NextFunction } from "express"; export function langfuseMiddleware() { return (req: Request, res: Response, next: NextFunction) => { const ctx = { requestId: req.headers["x-request-id"]?.toString() || randomUUID(), userId: req.headers["x-user-id"]?.toString(), sessionId: req.headers["x-session-id"]?.toString(), }; runWithContext(ctx, () => { startActiveObservation(`${req.method} ${req.path}`, async () => { updateActiveObservation({ input: { method: req.method, path: req.path, query: req.query, }, metadata: { userId: ctx.userId, sessionId: ctx.sessionId, requestId: ctx.requestId, }, }); // Capture response const originalEnd = res.end.bind(res); res.end = function (...args: any[]) { updateActiveObservation({ output: { statusCode: res.statusCode }, }); return originalEnd(...args); } as any; next(); }).catch(next); }); }; } // Usage import express from "express"; import { initTracing } from "./lib/tracing"; import { langfuseMiddleware } from "./middleware/tracing"; initTracing(); const app = express(); app.use(langfuseMiddleware());
For microservices, propagate trace context via HTTP headers:
typescript// Service A: Inject trace context into outbound requests import { context, propagation } from "@opentelemetry/api"; async function callServiceB(data: any) { const headers: Record<string, string> = {}; // OTel propagation injects traceparent header automatically propagation.inject(context.active(), headers); const response = await fetch("https://service-b.internal/api/process", { method: "POST", headers: { "Content-Type": "application/json", ...headers, // Includes traceparent, tracestate }, body: JSON.stringify(data), }); return response.json(); }
typescript// Service B: Extract and continue trace context import { context, propagation } from "@opentelemetry/api"; import { startActiveObservation, updateActiveObservation } from "@langfuse/tracing"; app.post("/api/process", async (req, res) => { // OTel automatically extracts context from incoming headers // when using standard HTTP instrumentation. // Any startActiveObservation call will be a child of the extracted trace. await startActiveObservation("service-b-process", async () => { updateActiveObservation({ input: req.body }); const result = await processData(req.body); updateActiveObservation({ output: result }); res.json(result); }); });
typescript// src/config/langfuse.ts type Environment = "development" | "staging" | "production"; const configs: Record<Environment, { exportIntervalMillis: number; maxExportBatchSize: number; sampleRate: number; }> = { development: { exportIntervalMillis: 1000, // Immediate visibility maxExportBatchSize: 1, sampleRate: 1.0, // Trace everything }, staging: { exportIntervalMillis: 5000, maxExportBatchSize: 25, sampleRate: 0.5, // 50% sampling }, production: { exportIntervalMillis: 10000, maxExportBatchSize: 100, sampleRate: 0.1, // 10% sampling }, }; export function getTracingConfig() { const env = (process.env.NODE_ENV || "development") as Environment; return configs[env] || configs.development; }
When Langfuse is unavailable, the app must keep running:
typescript// The v4+ SDK with OTel handles this gracefully: // - Failed exports are logged but don't throw // - Events are buffered in the queue // - Queue drops oldest events when maxQueueSize is exceeded // // For additional safety at the application level: import { observe, updateActiveObservation } from "@langfuse/tracing"; let tracingHealthy = true; let consecutiveFailures = 0; const MAX_FAILURES = 10; export function safeTrace<T extends (...args: any[]) => Promise<any>>( name: string, fn: T ): T { return (async (...args: Parameters<T>) => { if (!tracingHealthy) { return fn(...args); // Circuit breaker open } try { const result = await observe({ name }, async () => { updateActiveObservation({ input: args }); const r = await fn(...args); updateActiveObservation({ output: r }); return r; })(); consecutiveFailures = 0; return result; } catch (error) { consecutiveFailures++; if (consecutiveFailures >= MAX_FAILURES) { tracingHealthy = false; console.error("Langfuse tracing disabled (circuit breaker open)"); // Re-enable after 5 minutes setTimeout(() => { tracingHealthy = true; consecutiveFailures = 0; }, 300000); } return fn(...args); } }) as T; }
| Decision | Starter | Growth | Enterprise | |----------|---------|--------|------------| | Langfuse host | Cloud | Cloud or Self-hosted | Self-hosted (HA) | | SDK version | v4+ | v4+ | v4+ with custom processor | | Sampling | 100% | 50-100% | 5-20% + error always | | Context propagation | Not needed | AsyncLocalStorage | OTel + HTTP headers | | Queue buffer | SDK internal | SDK internal | External (SQS/Kafka) | | Failover | None | Log-and-continue | Circuit breaker |
| Issue | Cause | Solution | |-------|-------|----------| | Multiple SDK instances | No singleton | Centralize in tracing.ts module | | Lost traces on deploy | No SIGTERM handler | Register shutdown handler | | Cross-service trace gaps | No context propagation | Inject OTel traceparent header | | Scale bottleneck | Direct SDK at high volume | Add queue buffer or increase sampling |
| Case | Status | Duration (ms) | Turns | Tokens | Tool calls | ||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Without | With | Δ | Without | With | Δ | Without | With | Δ | Without | With | Δ | ||
case-01 | fail→pass | 35,189 | 18,327 | -48% | 1 | 1 | 0% | 6,318 | 5,205 | -18% | 0 | 0 | — |
case-02 | fail→fail | 39,919 | 46,670 | +17% | 1 | 1 | 0% | 7,159 | 10,634 | +49% | 0 | 0 | — |
case-03 | fail→fail | 24,186 | 18,237 | -25% | 1 | 1 | 0% | 4,232 | 5,151 | +22% | 0 | 0 | — |
case-04 | pass→pass | 21,452 | 22,609 | +5% | 1 | 1 | 0% | 3,033 | 5,943 | +96% | 0 | 0 | — |
case-05 | pass→pass | 21,906 | 21,549 | -2% | 1 | 1 | 0% | 3,502 | 5,791 | +65% | 0 | 0 | — |
case-06 | pass→pass | 29,443 | 31,836 | +8% | 1 | 1 | 0% | 3,377 | 7,317 | +117% | 0 | 0 | — |
case-07 | fail→fail | 39,560 | 18,964 | -52% | 1 | 1 | 0% | 3,328 | 5,303 | +59% | 0 | 0 | — |
case-08 | pass→pass | 16,498 | 16,635 | +1% | 1 | 1 | 0% | 2,080 | 4,187 | +101% | 0 | 0 | — |
case-09 | fail→pass | 21,976 | 9,261 | -58% | 1 | 1 | 0% | 2,417 | 4,272 | +77% | 0 | 0 | — |
case-10 | fail→fail | 22,139 | 14,489 | -35% | 1 | 1 | 0% | 2,747 | 4,553 | +66% | 0 | 0 | — |
case-11 | fail→fail | 37,836 | 24,227 | -36% | 1 | 1 | 0% | 4,536 | 5,205 | +15% | 0 | 0 | — |
case-12 | fail→fail | 33,293 | 31,513 | -5% | 1 | 1 | 0% | 4,575 | 7,149 | +56% | 0 | 0 | — |
case-13 | fail→pass | 19,273 | 6,515 | -66% | 1 | 1 | 0% | 2,371 | 3,500 | +48% | 0 | 0 | — |
case-14 | fail→fail | 23,256 | 12,154 | -48% | 1 | 1 | 0% | 2,587 | 4,510 | +74% | 0 | 0 | — |
case-15 | fail→pass | 20,003 | 9,063 | -55% | 1 | 1 | 0% | 2,296 | 3,134 | +36% | 0 | 0 | — |
case-16 | fail→fail | 19,713 | 18,650 | -5% | 1 | 1 | 0% | 2,463 | 4,686 | +90% | 0 | 0 | — |
case-17 | pass→pass | 19,515 | 18,771 | -4% | 1 | 1 | 0% | 2,590 | 4,736 | +83% | 0 | 0 | — |
case-18 | pass→pass | 23,439 | 18,609 | -21% | 1 | 1 | 0% | 2,953 | 4,666 | +58% | 0 | 0 | — |
case-19 | pass→pass | 24,601 | 19,154 | -22% | 1 | 1 | 0% | 3,092 | 5,639 | +82% | 0 | 0 | — |
case-20 | fail→fail | 19,362 | 17,151 | -11% | 1 | 1 | 0% | 3,004 | 4,532 | +51% | 0 | 0 | — |
case-21 | pass→pass | 17,762 | 16,904 | -5% | 1 | 1 | 0% | 2,193 | 4,489 | +105% | 0 | 0 | — |
case-22 | fail→fail | 18,941 | 23,161 | +22% | 1 | 1 | 0% | 2,806 | 5,444 | +94% | 0 | 0 | — |
case-23 | fail→pass | 21,129 | 11,586 | -45% | 1 | 1 | 0% | 2,838 | 3,585 | +26% | 0 | 0 | — |
DecimalAI ran this skill against gemini-3.6-flash twice over the same eval suite — once with the skill loaded and once without — and compared the two runs case by case. 23 cases were attempted. The headline lift of +22 percentage points is the difference between those two pass rates over the 23 comparable cases.
Without the skill loaded, the model failed this case. With it loaded, the same prompt on the same model passed. This is one improved case from the latest verified run; every case, including any that regressed, is in the table above.
Other measured skills in the registry, with their headline benchmark lift.