AI Tooling
Langfuse: Tracing and Evaluating an LLM Application
A small LLM application traced with a self-hosted Langfuse, and every claim checked by reading the data back: what a trace contains, what tracing costs per request, what happens to your application and your traces when Langfuse is down, how evaluation scores are stored, and which masking hook actually masks.
On this page · 14 sections
Imagine the fleet-operations assistant has been running for a week. Drivers ask it about policies: how long a break must be, which extension to call when a van breaks down, what to do about a lost fuel card. One morning a supervisor forwards a screenshot: the assistant told a driver the wrong break rule.
Which request was it? What did retrieval return? What exactly did the model see, and what did it say? How long did it take, and how many tokens did it use? And has it happened before?
Without records, none of those questions has an answer. The demos in this series kept their own: the agent in “LangGraph in Practice: A Text-to-SQL Agent You Can Measure (opens in a new tab)” wrote a trace list into its state, and the evaluation read saved files. That works for a demo with one user. An application with many users needs the records kept somewhere you can search, compare, and score.
Langfuse is an open-source tool for exactly that: tracing what an LLM application does, request by request, and evaluating it. This article runs it on one machine, instruments the fleet assistant, and checks every claim by reading the stored data back through Langfuse’s API. That includes the claim that matters most when you add any tool to a production path: what happens to your application when the tool is down.
Try to Understand It This Way
Think of the flight recorder in an aircraft. It records what the instruments said, what the crew did, and when, continuously, without the crew doing anything. When something goes wrong, investigators replay the flight. Two properties matter as much as the recording itself. It must never interfere with flying the plane. And it must survive: a recorder that loses the last minute before an incident has failed at its one job.
A tracing tool is a flight recorder for each request. It records the steps (retrieval, the model call), their inputs and outputs, tokens, and timing, without the application’s code changing its behaviour. And the same two properties are the ones to test: does it stay out of the request’s way, and does the record survive when something goes wrong?
What Langfuse Records
The demo, 02-langfuse-tracing, answers drivers’ questions from ten short policy snippets. Retrieval picks the two snippets with the most words in common with the question; then a local model writes the answer. With Langfuse’s Python SDK, each request becomes a trace with three observations:
fleet-question (span: the whole request)
├── retrieve (retriever: the question in, the two snippets out)
└── generate (generation: the messages in, the answer out, model, parameters, tokens)
The SDK version used here (5.1.0) is built on OpenTelemetry, the open standard for traces. The application creates spans as it works; the SDK queues them in memory and a background thread sends them in batches to the Langfuse server.
The server, self-hosted with Docker, is six containers: the web application and API, a worker that processes incoming events, PostgreSQL, ClickHouse (where traces, observations, and scores are stored), Redis (a queue), and S3-compatible storage (every incoming batch is written there first). Shortly after start, the stack used about 2.5 GB of memory.
The exact setup
- Date and machine: 2026-11-16, Apple M4 Pro, macOS 26.6.2, Docker Desktop, on mains power.
- Langfuse server: 4.72.0, self-hosted from Langfuse’s own
docker-compose.ymlfor that version, trimmed, every image pinned by digest, withTELEMETRY_ENABLED=false. Listening only on 127.0.0.1. - SDK:
langfuse5.1.0 for Python (OpenTelemetry SDK 1.45.2), Python 3.12.13. - Model:
qwen2.5:3b(357c53fb659c…) through Ollama 0.40.16, temperature 0, seed 42,num_ctx4096; a fake model that answers instantly where the model would only add noise. - Reading back: every check reads the stored data through Langfuse’s public API, polling until the expected records appear (about a second for observations, about seven for scores).
- Runs: the trace and evaluation scripts ran twice, with identical results; the overhead measurement ran twice, with three rounds each.
Tokens are what you send
The demo sends Ollama’s own token counts with each generation. Read back, Langfuse had stored exactly those numbers (154 input and 32 output for the first question, and so on) and added a total. A request sent without token counts was stored with no usage and no cost. Langfuse 4.72.0 didn’t estimate anything for this model. That matches the documentation’s current wording: “If neither usage nor cost is submitted, no cost is calculated.”
So token and cost dashboards are only as complete as the instrumentation. If one code path forgets to report usage, its requests cost nothing in the charts.
What Tracing Costs Per Request
The demo timed the same request four ways, with a fake model so the model’s time doesn’t drown the difference, 500 requests per condition, three rounds, twice:
| Condition | Median per request |
|---|---|
| no Langfuse code | 65 µs |
| SDK present, tracing disabled | 92–93 µs |
| tracing on, spans created but discarded | 266–268 µs |
| tracing on, spans sent to Langfuse | 266–272 µs |
Tracing added about 0.2 milliseconds per request, for three spans. Nearly all of it is creating the spans: sending them cost no more than discarding them, because sending happens on the background thread. With the real model, at 250 to 300 milliseconds per request, the difference was smaller than the variation between rounds; it couldn’t be measured at all.
This matches the SDK overview’s claim of “Fully async requests, meaning Langfuse adds almost no latency.” The cost that does show up is flush(), which sends everything still queued and waits for it: about 100 milliseconds after 550 traces here.
When Langfuse Is Down
Here is where it gets interesting. The flight recorder’s first property: it must never interfere with flying. The demo sent 1,000 requests at 50 per second while Langfuse was unreachable in different ways, using local stand-ins for the failures:
| Scenario | Request errors | Median request time | flush() blocked for |
What the server received |
|---|---|---|---|---|
| Langfuse up | 0 | 1.56 ms | 0.05 s | all 1,000 traces |
| connection refused | 0 | 1.55 ms | 3.3 s | nothing |
| slow server (answers after 10 s) | 0 | 1.55 ms | 13.6 s | every span, once |
| server answering 503 | 0 | 1.56 ms | 3.1 s | every span, three times |
The first property held completely. No request raised an error, and no request got slower, in any scenario. The documentation promises it: “Cannot break your application: SDK errors are caught and logged.”
The cost moved to two places. The first is flush(): it blocked for 3 to 14 seconds while the SDK retried. If your code calls flush() at the end of every request, as some serverless setups do, an outage turns into slow requests after all.
The second is the data, and it’s less obvious. With the slow server, the SDK gave up waiting and counted every export as failed, but the server had received every span: a client-side failure doesn’t mean the data didn’t arrive. With 503 responses, the SDK retried, and the server received each span three times. Whether a real Langfuse server removes duplicates like these wasn’t tested; if your numbers look inflated after an incident, that’s a place to look.
The second property: does the record survive?
Then the real server. 1,200 requests at 20 per second; at 20 seconds, the demo stopped Langfuse’s web container, and at 40 seconds started it again (healthy again at 47 seconds).
Still no request errors. 780 of 1,200 traces arrived. The 420 that didn’t were exactly the requests sent between 20.2 and 41.2 seconds: everything during the outage, and none outside it. The SDK keeps its queue in memory, retries a batch within a deadline (5 seconds by default, from the installed source), and then drops it. Nothing is written to disk, and nothing is sent later.
For debugging, a gap of twenty seconds may be acceptable. For anything you’d use as a record (usage billing, an audit of what the model told users), it isn’t. The traces from an outage are exactly the ones an investigation would want.
Short-lived scripts
The documentation says short-lived applications “must explicitly call flush() before exiting”. The demo tested five ways a script can end, five traces each:
| How the script ended | Traces that arrived |
|---|---|
called flush() |
5/5 |
ended normally, no flush() |
5/5 |
| crashed with an uncaught exception | 5/5 |
| killed with SIGTERM | 0/5 |
os._exit() |
0/5 |
The SDK registers an exit handler that flushes, so a normal ending or a crash still delivered everything. A kill signal, which is how containers and job schedulers usually stop processes, delivered nothing. So the documentation’s advice stands, for a reason it doesn’t spell out: call flush() yourself, and handle SIGTERM if your process can be stopped from outside.
Evaluation: Scores on Traces
Tracing tells you what happened. Evaluation tells you whether it was good. Langfuse stores evaluations as scores attached to traces, so the record of a request and the judgement of it live together.
The demo uploads 14 questions with the key facts a good answer states (one question has no answer in the snippets; the expected “fact” is saying so) as a Langfuse dataset, then runs an experiment: the assistant answers each item, and three deterministic scores go on each item’s trace. The names say what they measure:
expected_facts_present_fraction: the share of the expected facts found in the answer.all_expected_facts_present: 1 if every one was found.source_retrieved: 1 if retrieval returned the snippet that holds the answer, which tells retrieval failures from generation failures.
In both runs, 13 of 14 answers contained every expected fact. The fourteenth, about the lost fuel card, contained one of its two, with the right snippet retrieved: a generation miss, not a retrieval one. All 43 scores (3 per item, plus one for the run) were read back, each on its own item’s trace. As with every check of this kind, “fact present” isn’t “correct”: an answer can contain the fact and still say something wrong.
What the experiment adds over a script with a print statement is the link. From a low score you can open the exact trace: the question, the two snippets retrieval returned, the messages the model saw, the answer. Then run the experiment again after a change and compare the runs side by side.
Masking: Which Hook Actually Masks
Traces store inputs and outputs, and inputs contain whatever users type. The demo’s test request reads: “Driver Jane (jane.doe@example.com, +44 20 7946 0958) lost her fuel card. What should she do?” (an example domain and a number from a range reserved for drama, both fictional). That email and phone number now sit in your tracing database.
The Python SDK has two masking hooks, and the masking documentation labels them: mask_otel_spans is “Recommended”, mask is “Legacy”. The demo used the same redaction function in each, and read back what was stored:
| Hook | Raw email or phone stored in |
|---|---|
| none | the input and metadata of all three observations |
mask (legacy) |
the metadata of all three observations |
mask_otel_spans (recommended) |
nowhere |
The legacy hook masked the inputs but missed the email in the trace’s metadata, which the application had set at the trace level. The documentation describes why: mask “applies only to data set through Langfuse SDK APIs such as start_observation() and update().” The recommended hook runs on every span the SDK exports, so it caught everything.
Two more things from the documentation are worth knowing before you rely on masking. If mask_otel_spans raises an exception, “Langfuse drops the whole export batch”: a bug in your masking function loses traces rather than leaking data, which is the safe direction. And the stored metadata also included OpenTelemetry’s own attributes on every observation, such as the SDK version and the project’s public key; harmless, but part of what you’re storing.
Self-Hosting Notes
- It’s six services. The Docker Compose guide is clear that this setup “lacks high-availability, scaling capabilities, and backup functionality”; production self-hosting means running PostgreSQL, ClickHouse, Redis, and object storage properly.
- Telemetry. The self-hosted server sends aggregated usage telemetry to Langfuse unless
TELEMETRY_ENABLED=false(telemetry page). The demo sets it. The page also lists an update check that isn’t configurable. - The SDK’s default destination. Without a base URL configured, the Python SDK sends traces to Langfuse Cloud. On a self-hosted setup, set
LANGFUSE_BASE_URLeverywhere, or traces with your users’ data go somewhere you didn’t intend. - Licence. The core is MIT-licensed; the licence page says “All core Langfuse features and APIs are available in Langfuse OSS (MIT licensed) without any limits”, and lists the enterprise features separately (server-side data masking among them).
What Breaks
- Traces during an outage. Lost: everything sent while the server was down, with no disk buffer and no later retry.
flush()during an outage. Blocks for seconds while the SDK retries.- Retries. A 503 delivered each span three times.
- Killed processes. SIGTERM and
os._exit()lose everything still queued. - Missing usage. A generation without token counts costs nothing in the dashboards.
- The legacy masking hook. Misses data set outside the observation APIs.
- The default base URL. Points at the cloud service.
Engineering Decisions
1. Treat tracing as best-effort, and design around it
It won’t break your requests, as measured, and it will lose records during outages, also as measured. That’s the right trade for debugging. If you need a durable record of every request (billing, audit, compliance), write it to your own durable store as well, and treat traces as the debugging view.
2. Never call flush() on the request path
Call it at shutdown, in a SIGTERM handler, and at the end of batch jobs and short-lived scripts.
3. Send usage from every generation
Langfuse records what you send. Make reporting token counts part of the code that calls the model, not an afterthought, and check a sample of traces for empty usage.
4. Use mask_otel_spans, and test it by reading back
Write a test that sends a request containing fake personal data and reads the stored trace back, as the demo does. A masking hook you haven’t tested against the stored data is a guess.
5. Attach evaluation to traces
The value of a low score is the trace behind it. Use dataset runs for comparisons before and after a change, and scores on production traces for the questions that matter.
6. Size the self-hosted stack honestly
Six services and about 2.5 GB of memory shortly after start, for one developer, before any real traffic. Compare that with the managed service, with your data’s sensitivity in mind.
When to Use Langfuse (and When Not To)
Langfuse fits when you need to see inside an LLM application across many requests: which step failed, what the model saw, what it cost, and how a change affected quality. Self-hosting fits when traces contain data that can’t leave your infrastructure, and you can run the six services. Its overhead per request was negligible here, and an outage never touched the application’s requests.
I’d add something else, not replace it with something else, when the records must be complete: an audit log is a different job from a tracing tool. And for a prototype with a few users, structured logs you already have may be enough until the questions outgrow them.
What to Take Away
- Tracing stayed out of the request’s way: about 0.2 ms per request, and no errors or slowdowns during any outage.
- The record didn’t survive the outage. Every trace sent while the server was down was lost.
flush()is where an outage shows up, and a kill signal loses the queue.- Langfuse stores what you send: no usage reported, no cost.
- Use the recommended masking hook, and verify it by reading back.
Think About These Use Cases
-
Billing by tokens: You charge customers by tokens used and read the numbers from traces. What happens to an invoice after a twenty-second Langfuse outage, and what would you change?
-
A serverless function: Each request runs in a function that is frozen or killed after it returns. Where do you flush, and what does that cost each request when Langfuse is slow?
-
Customer support transcripts: Support agents paste customer emails into the assistant. What do you mask, how do you prove it’s masked, and who can read the traces?
-
A regression after a prompt change: Your evaluation score drops from 13 of 14 to 11 of 14. Walk through how you’d use the experiment runs and traces to find out why.
-
Multi-step agents: A LangGraph agent makes five model calls per question. How would you structure its traces so that the step that went wrong is easy to find?
If you want to talk one of these through, take it to GPT along with this article. Ask GPT ↗️
Related Sources
- 02-langfuse-tracing: The companion demo: the self-hosted stack, the traced application, and the scripts for trace contents, overhead, outages, short-lived scripts, evaluation, and masking.
- Langfuse documentation: Including the Python SDK overview, masking, and token and cost tracking.
- Self-hosting Langfuse: The architecture, the Docker Compose setup, and the telemetry settings.
- langfuse/langfuse and langfuse/langfuse-python: The server and the Python SDK.
- OpenTelemetry: The tracing standard the SDK is built on, including the batch span processor whose defaults the SDK uses.
What’s Next?
Langfuse recorded what the fleet assistant did with its knowledge snippets. The next article in this AI Tooling track gives the assistant something more powerful than snippets: live tools, through a standard protocol. MCP: Giving a Model Your Own Tools and Data builds a tool server for the fleet and measures what the protocol standardises, what it leaves to you, and what an injected instruction does.