Deploy Langfuse on Docker: Trace LLMs, Monitor Costs, and Evaluate Output Quality

AI tutorial - IT technology blog
AI tutorial - IT technology blog

The Production Blind Spot in LLM Applications

Prototyping an LLM feature takes hours. You test a prompt against OpenAI or Anthropic in an interactive notebook, get crisp responses, and ship to staging. Then real traffic hits your endpoints.

A customer submits an edge-case support inquiry, waiting 18 seconds before receiving an outright hallucination. At month’s end, your API invoice spikes by 40%. Standard APM dashboards like Datadog or Prometheus display normal HTTP 200 statuses with ambiguous latency spikes.

They tell you nothing about the cognitive pipeline. Did a vector search dump 12,000 junk tokens into the context window? Did prompt version 1.2 break formatting? Which single tenant burned $68 in API credits on a looping agent?

Standard infrastructure tools monitor servers, memory, and ingress. They cannot inspect context assembly, reasoning chains, or model expenditures. Without specialized tracing, debugging production LLM pipelines is pure guesswork.

Core Concepts: How Langfuse Bridges the Observability Gap

Langfuse is an open-source engineering platform built to inspect, trace, and score LLM operations. Three core abstractions form the backbone of your daily debugging workflow.

1. Traces, Spans, and Generations

Langfuse structures runtime telemetry into an intuitive call hierarchy:

  • Trace: The root object capturing the complete lifecycle of a request, such as a RAG query or an autonomous agent run.
  • Span: An individual operational step within a trace, like executing an embedding query, querying Milvus, or parsing JSON.
  • Generation: A dedicated span type for model inferences. It logs input prompts, parameters like temperature and max tokens, raw completions, latency, and exact token counts.

2. Automated Token and Cost Tracking

Every commercial provider prices input and output tokens differently. Langfuse maintains an active internal price catalog covering OpenAI, Anthropic, Mistral, and Bedrock models. When an application reports token counts, Langfuse calculates cost per request down to four decimal places. You can immediately aggregate spend by customer ID, feature flag, or git commit.

3. Production Evaluations (Scores)

Telemetry without grading gives an incomplete picture. Langfuse lets you bind numerical and categorical scores directly to any trace. You can ingest end-user signals like thumbs-up buttons, trigger automated LLM-as-a-judge pipelines for semantic drift, or assign failing traces to internal review queues.

Hands-On Practice: Deploying Langfuse with Docker and Python

We’ll spin up a lightweight self-hosted Langfuse stack on Docker Compose and stream traces from a Python service.

Step 1: Set Up Docker Compose

While enterprise multi-node Langfuse clusters incorporate ClickHouse and Redis for massive event throughput, a lean single-instance deployment runs reliably on PostgreSQL alone. Create an isolated directory and generate the deployment configuration:

mkdir -p langfuse-docker && cd langfuse-docker
nano docker-compose.yml

Add the following service definitions:

version: "3.9"

services:
  langfuse-server:
    image: ghcr.io/langfuse/langfuse:2
    depends_on:
      db:
        condition: service_healthy
    ports:
      - "3000:3000"
    environment:
      - DATABASE_URL=postgresql://langfuse:langfuse_password@db:5432/langfuse
      - NEXTAUTH_URL=http://localhost:3000
      - NEXTAUTH_SECRET=4a8f9c2d1e0b5a7f3c6e9d2a1b4c7e0f5a8b1c4d7e0f3a6b9c2d5e8a1b4c7e0
      - SALT=9b1c4e7a0d3f6b8c2e5a7d0f3b6c9e1a4d7f0b3c6e9a2d5f8b1c4e7a0d3f6b8
      - TELEMETRY_ENABLED=false
    restart: unless-stopped

  db:
    image: postgres:16-alpine
    environment:
      - POSTGRES_USER=langfuse
      - POSTGRES_PASSWORD=langfuse_password
      - POSTGRES_DB=langfuse
    volumes:
      - pgdata:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U langfuse"]
      interval: 5s
      timeout: 5s
      retries: 5
    restart: unless-stopped

volumes:
  pgdata:

Step 2: Start the Stack and Generate API Keys

Boot the services in the background:

docker compose up -d

Confirm that both containers are healthy:

docker compose ps

Navigate to http://localhost:3000 in your browser. Register your initial administrator credentials. Next, generate project tokens:

  1. Create a project named Production-Customer-Support.
  2. Open Settings > API Keys.
  3. Click Create new API keys, then save your Secret Key (sk-lf-...), Public Key (pk-lf-...), and host address.

Step 3: Instrument an LLM Application in Python

Clear telemetry helps your team isolate bad model outputs in minutes rather than days. Install the official SDK alongside the OpenAI client library:

pip install langfuse openai

Save the following script as monitor_app.py to wrap a multi-step retrieval and inference flow inside an observable trace:

import os
from langfuse import Langfuse
from openai import OpenAI

# Configure Langfuse credentials
os.environ["LANGFUSE_PUBLIC_KEY"] = "pk-lf-your-public-key"
os.environ["LANGFUSE_SECRET_KEY"] = "sk-lf-your-secret-key"
os.environ["LANGFUSE_HOST"] = "http://localhost:3000"

# Configure model provider
os.environ["OPENAI_API_KEY"] = "sk-your-openai-key"

langfuse = Langfuse()
openai_client = OpenAI()

def run_support_pipeline(user_query: str, user_id: str):
    # 1. Initialize root trace for the request
    trace = langfuse.trace(
        name="Customer-Support-RAG",
        user_id=user_id,
        metadata={"environment": "production", "version": "1.0.4"}
    )

    # 2. Track knowledge base retrieval step
    retrieval_span = trace.span(
        name="Knowledge-Base-Retrieval",
        input={"search_term": user_query}
    )
    retrieved_context = "Billing policy: Enterprise refunds are processed within 5 business days."
    retrieval_span.end(output={"documents_found": 1, "content": retrieved_context})

    # 3. Track model generation
    prompt_messages = [
        {"role": "system", "content": f"Context: {retrieved_context}"},
        {"role": "user", "content": user_query}
    ]

    generation = trace.generation(
        name="Answer-Generation",
        model="gpt-4o-mini",
        model_parameters={"temperature": 0.2},
        input=prompt_messages
    )

    completion = openai_client.chat.completions.create(
        model="gpt-4o-mini",
        temperature=0.2,
        messages=prompt_messages
    )

    reply = completion.choices[0].message.content
    usage = completion.usage

    # 4. Attach usage metrics and close the generation span
    generation.end(
        output=reply,
        usage={
            "prompt_tokens": usage.prompt_tokens,
            "completion_tokens": usage.completion_tokens,
            "total_tokens": usage.total_tokens
        }
    )

    # 5. Log factual grounding score
    trace.score(
        name="factual_accuracy",
        value=1.0,
        comment="Output perfectly matches corporate refund policy context."
    )

    # Flush events to Langfuse server before returning
    langfuse.flush()
    return reply

if __name__ == "__main__":
    response = run_support_pipeline(
        user_query="How long does an enterprise refund take?",
        user_id="usr_9812"
    )
    print(f"Model Response: {response}")

Step 4: Inspecting Results in the Dashboard

Execute the pipeline:

python monitor_app.py

Return to http://localhost:3000 to inspect the captured execution telemetry:

  1. Open Tracing > Traces and select Customer-Support-RAG.
  2. Examine the waterfall chart. It breaks down execution duration, showing exactly how many milliseconds the retrieval span took compared to the model completion.
  3. Inspect the metadata pane. You will see prompt tokens (42), completion tokens (14), exact dollar cost ($0.000015), and attached evaluation scores.

Wrapping Up

AI engineering requires the same operational vigilance as distributed backend microservices. Running Langfuse locally on Docker grants complete data sovereignty, granular visibility into token budgets, and auditable traces for every prompt version. Instrument your critical user flows first, monitor unit economics, and use automated scoring to catch degradations before customers do.

Share: