Agent skill

Langfuse Reference Architecture

by jeremylongshore in jeremylongshore/tons-of-skills-marketplace

Production-grade Langfuse architecture patterns and best practices.

MITAuto-check passedAI & LLM Engineering

Install Langfuse Reference Architecture

skills CLI
$ npx skills add jeremylongshore/tons-of-skills-marketplace --skill langfuse-reference-architecture -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install jeremylongshore/tons-of-skills-marketplace langfuse-reference-architecture --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/jeremylongshore/tons-of-skills-marketplace.git skills-src && mkdir -p .claude/skills && cp -r skills-src/skills/.curated/langfuse-reference-architecture .claude/skills/langfuse-reference-architecture && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
langfuse-reference-architecture
GitHub stars
2.8k
Token cost
~2.6k tokens
SKILL.md length
321 words
Files
2 (incl. references)
Skills in repo
3,342
Repo updated
First seen
Licence
MIT

At a glance

Production-grade Langfuse architecture patterns and best practices.

  • Designing LLM observability infrastructure
  • SKILL.md covers Overview, Prerequisites, Architecture Tiers and Instructions, plus 5 more sections
  • Instructions only: no scripts, shell commands, URLs or credentials in SKILL.md
  • Planning Langfuse deployment

What it does

Langfuse Reference Architecture is an agent skill from jeremylongshore/tons-of-skills-marketplace. 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".

Its SKILL.md is about 2.6k tokens, which your agent loads only when the skill is triggered. The skill folder holds 2 other files, including reference files (for example `references/implementation.md`). Compatibility notes: Designed for Claude Code

It sits in AI & LLM Engineering, covering LLM observability. It works with Langfuse and OpenTelemetry. The repository describes itself as: Model-agnostic agent-skills platform with a harness-free canonical layer, verified adapters, and the ccpi package manager. Explore at tonsofskills.com. The licence is MIT.

When your agent uses it

  • Designing LLM observability infrastructure
  • Planning Langfuse deployment
  • Implementing enterprise-grade tracing architecture
  • With phrases like langfuse architecture

Example prompts

  • “langfuse architecture”
  • “langfuse design”
  • “langfuse infrastructure”
  • “/langfuse-reference-architecture”

Requirements

  • Node.js
  • Compatibility (from SKILL.md): Designed for Claude Code
  • Pre-approved tools (allowed-tools): Read, Write, Edit

What it can do on your machine

Read from SKILL.md and the folder at commit cfae287. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves these tools, so the agent can use them without asking each time:

    • Read
    • Write
    • Edit

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    No scripts in the folder and no shell commands in SKILL.md (its code samples are typescript).

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    Links to these hosts (documentation or services it may open):

    • langfuse.com
    • opentelemetry.io

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names no API keys, tokens, secrets or passwords.

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

  • Compatibility

    Designed for Claude Code

    From compatibility in the SKILL.md frontmatter.

Context cost

Langfuse Reference Architecture loads about 2.6k tokens when it runs, and up to ~3.8k if it reads all its reference files. Until then it costs about 95 tokens; SKILL.md has 321 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~95
When it runs · the whole SKILL.md, loaded when a task matches
~2.6k
With references · SKILL.md plus every file in references/, read only if the agent opens them
~3.8k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from jeremylongshore/tons-of-skills-marketplace at commit cfae287, republished under its MIT licence (© jeremylongshore). 321 words, ~2,614 tokens.

Download SKILL.mdSave it as .claude/skills/langfuse-reference-architecture/SKILL.md (or your agent's skills folder). This skill also uses 1 other file; get the full folder from GitHub.
name
langfuse-reference-architecture
description
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".
allowed-tools
Read, Write, Edit
compatibility
Designed for Claude Code
version
1.17.0
license
MIT
author
Jeremy Longshore <jeremy@intentsolutions.io>
tags
saas, langfuse, deployment, observability, llm

Langfuse Reference Architecture

Overview

Production-grade architecture patterns for Langfuse LLM observability: singleton SDK, context propagation with AsyncLocalStorage, cross-service trace correlation, multi-environment configurations, and scale strategies.

Prerequisites

  • Understanding of distributed systems and async patterns
  • Node.js 18+ with OpenTelemetry SDK
  • For v4+: @langfuse/tracing, @langfuse/otel, @opentelemetry/sdk-node

Architecture Tiers

TierScaleArchitectureLangfuse Host
Starter< 100K traces/dayDirect SDK, CloudLangfuse Cloud
Growth100K-1M traces/daySingleton + batchingCloud or Self-hosted
Enterprise1M+ traces/dayQueue-buffered + samplingSelf-hosted (HA)

Instructions

Pattern 1: Singleton SDK with Context Propagation
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);
}
Pattern 2: Express Middleware for Automatic Tracing
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());
Pattern 3: Cross-Service Trace Correlation

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);
  });
});
Pattern 4: Multi-Environment Configuration
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
  },
};

// Pass the selected environment from the application's configuration boundary.
// Keeping configuration resolution outside tracing makes this module deterministic
// and straightforward to test.
export function getTracingConfig(env: Environment = "development") {
  return configs[env] || configs.development;
}
Pattern 5: Graceful Degradation

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;
}

Architecture Decision Matrix

DecisionStarterGrowthEnterprise
Langfuse hostCloudCloud or Self-hostedSelf-hosted (HA)
SDK versionv4+v4+v4+ with custom processor
Sampling100%50-100%5-20% + error always
Context propagationNot neededAsyncLocalStorageOTel + HTTP headers
Queue bufferSDK internalSDK internalExternal (SQS/Kafka)
FailoverNoneLog-and-continueCircuit breaker

Error Handling

IssueCauseSolution
Multiple SDK instancesNo singletonCentralize in tracing.ts module
Lost traces on deployNo SIGTERM handlerRegister shutdown handler
Cross-service trace gapsNo context propagationInject OTel traceparent header
Scale bottleneckDirect SDK at high volumeAdd queue buffer or increase sampling

Output

Produce an architecture decision record identifying the selected deployment tier, tracing boundary, context-propagation method, failure mode, retention owner, and rollback path. Include the tested revision and state whether the evidence comes from a local, staging, or production-like environment.

Examples

A growth-stage service can keep the SDK's internal queue and add AsyncLocalStorage propagation, then test that a request and downstream worker share the trace context. An enterprise deployment can put a queue between the application and self-hosted Langfuse, trip the circuit breaker during an export failure drill, and prove application traffic continues while telemetry recovers.

Resources

© jeremylongshore, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

SKILL.md and 1 other file (references) in skills/.curated/langfuse-reference-architecture of jeremylongshore/tons-of-skills-marketplace.

  • SKILL.md
  • references/implementation.md

Open the folder on GitHubat commit cfae287

Compare with similar skills

Langfuse Reference Architecture next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Langfuse Reference Architecture compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Langfuse Reference Architecture this skilljeremylongshore/tons-of-skills-marketplace2.8k—~2.6kAutomated safety check: PassMIT
Agentsop Observability Setupagentsope/SkillAlchemy436—~4.4kAutomated safety check: PassMIT
Olore Langfuse Latestolorehq/olore104—~1.2kAutomated safety check: PassMIT
Telemetry AnalyzerIBM/ibm-watsonx-orchestrate-adk178—~10kAutomated safety check: NotesMIT
Ak Dev New Tracing Provideryaalalabs/agent-kernel192—~3.5kAutomated safety check: PassApache-2.0
Backend Dev Guidelineslangfuse/langfuse36k—~1.9kAutomated safety check: PassCustom licence

Similar skills

  • Agentsop Observability Setup

    agentsope/SkillAlchemy

    Enhancement-overlay skill — the DECISION + WIRING layer for LM observability that the single-backend skills [[langsmith]], [[phoenix]], [[mlflow]] do NOT cover.

    436 GitHub stars~4.4k tokensUpdated yesterday
    AI & LLM EngineeringAuto-check passed
  • Local Langfuse documentation reference (latest). An agent skill from olorehq/olore.

    104 GitHub stars~1.2k tokensUpdated today
    AI & LLM EngineeringAuto-check passed
  • Telemetry Analyzer

    IBM/ibm-watsonx-orchestrate-adk

    Official

    A skill your agent uses when the user wants to analyze agent telemetry traces to find bugs and get fix recommendations — walks through exporting traces from a local or remote watsonx Orchestrate…

    178 GitHub stars~10k tokensUpdated 3 days ago
    DevelopmentAuto-check: notes
  • Ak Dev New Tracing Provider

    yaalalabs/agent-kernel

    Step-by-step guide for adding a new observability/tracing provider to Agent Kernel.

    192 GitHub stars~3.5k tokensUpdated yesterday
    DevOps & CloudAuto-check passed
  • Backend Dev Guidelines

    langfuse/langfuse

    Build or review Langfuse backend code. An agent skill from langfuse/langfuse.

    36k GitHub stars~1.9k tokensUpdated today
    Backend & APIsAuto-check passed
  • Ag2 Telemetry

    ag2ai/build-with-ag2

    Add OpenTelemetry traces to an AG2 beta Agent via TelemetryMiddleware (autogen.beta.middleware.builtin).

    252 GitHub stars~1.9k tokensUpdated 1 mo ago
    DevOps & CloudAuto-check passed

More from jeremylongshore/tons-of-skills-marketplace

All 3,342 skills in this repo
  • Performing Security Code Review

    jeremylongshore/tons-of-skills-marketplace

    Execute this skill enables AI assistant to conduct a security-focused code review using the security-agent plugin.

    2.8k GitHub starsUsed in 2 repos~1.3k tokens
    Auto-check: notes
  • Adapting Transfer Learning Models

    jeremylongshore/tons-of-skills-marketplace

    Build this skill automates the adaptation of pre-trained machine learning models using transfer learning techniques.

    2.8k GitHub stars~1.1k tokensUpdated today
    Auto-check passed
  • Agent Context Loader

    jeremylongshore/tons-of-skills-marketplace

    Execute proactive auto-loading: automatically detects and loads agents.md files.

    2.8k GitHub stars~1.1k tokensUpdated today
    Auto-check passed
  • Aggregating Performance Metrics

    jeremylongshore/tons-of-skills-marketplace

    Aggregate and centralize performance metrics from applications, systems, databases, caches, and services.

    2.8k GitHub stars~1.2k tokensUpdated today
    Auto-check passed
  • Analyzing Capacity Planning

    jeremylongshore/tons-of-skills-marketplace

    Execute this skill enables AI assistant to analyze capacity requirements and plan for future growth.

    2.8k GitHub stars~947 tokensUpdated today
    Auto-check passed
  • Analyzing Database Indexes

    jeremylongshore/tons-of-skills-marketplace

    Process use when you need to work with database indexing. An agent skill from jeremylongshore/tons-of-skills-marketplace.

    2.8k GitHub stars~2k tokensUpdated today
    Auto-check passed

Questions about Langfuse Reference Architecture

What does Langfuse Reference Architecture do?

Production-grade Langfuse architecture patterns and best practices. Langfuse Reference Architecture is an agent skill from jeremylongshore/tons-of-skills-marketplace. Production-grade Langfuse architecture patterns and best practices.

When should I use Langfuse Reference Architecture?

Langfuse Reference Architecture fits situations like: designing LLM observability infrastructure; planning Langfuse deployment; implementing enterprise-grade tracing architecture; with phrases like langfuse architecture.

How do I install Langfuse Reference Architecture in Claude Code?

Run `npx skills add jeremylongshore/tons-of-skills-marketplace --skill langfuse-reference-architecture -a claude-code`. Or copy the skill folder (skills/.curated/langfuse-reference-architecture in jeremylongshore/tons-of-skills-marketplace) into .claude/skills/langfuse-reference-architecture in your project. Claude Code loads it when a task matches its description.

How do I install Langfuse Reference Architecture in Codex?

Run `npx skills add jeremylongshore/tons-of-skills-marketplace --skill langfuse-reference-architecture -a codex`. Or copy the skill folder (skills/.curated/langfuse-reference-architecture in jeremylongshore/tons-of-skills-marketplace) into .agents/skills/langfuse-reference-architecture in your project. Codex loads it when a task matches its description.

Can I use Langfuse Reference Architecture in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add jeremylongshore/tons-of-skills-marketplace --skill langfuse-reference-architecture -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/langfuse-reference-architecture, .gemini/skills/langfuse-reference-architecture, .github/skills/langfuse-reference-architecture and .opencode/skills/langfuse-reference-architecture in your project.

What does Langfuse Reference Architecture need to run?

SKILL.md names no scripts, command-line tools or credentials: Langfuse Reference Architecture is instructions for the agent only. Our summary lists: Node.js. Its frontmatter pre-approves these tools: Read, Write, Edit. Compatibility (from SKILL.md): Designed for Claude Code.

Does Langfuse Reference Architecture access the network?

SKILL.md names 2 domains. As links in the text: langfuse.com and opentelemetry.io. This is read from the text; nothing was executed.

Is Langfuse Reference Architecture safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does Langfuse Reference Architecture use?

Langfuse Reference Architecture is published under the MIT licence (declared in SKILL.md). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Langfuse Reference Architecture use?

About 2.6k tokens (SKILL.md is roughly 10k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full. Its references folder adds about 1.2k tokens, read only when the agent opens those files.

What are the alternatives to Langfuse Reference Architecture?

Skills that share tags, products or a category with Langfuse Reference Architecture: Agentsop Observability Setup (agentsope/SkillAlchemy, 436 stars), Olore Langfuse Latest (olorehq/olore, 104 stars), Telemetry Analyzer (IBM/ibm-watsonx-orchestrate-adk, 178 stars) and Ak Dev New Tracing Provider (yaalalabs/agent-kernel, 192 stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Langfuse Reference Architecture?

jeremylongshore (a GitHub user) maintains it in jeremylongshore/tons-of-skills-marketplace, which has 2,827 GitHub stars. The repository holds 3,342 skills in this directory. The repository was last updated on October 10, 2026.

Source: jeremylongshore/tons-of-skills-marketplace on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.