LLM Observability in Practice
Langfuse is for this scene: the LLM service is live and users are complaining about output quality. Open the monitoring dashboard — CPU normal, memory normal, P99 latency within SLA. From an infrastructure perspective, the service looks perfectly healthy. This is the LLM observability gap: traditional APM tools can tell if the system is healthy, but not if the AI is.
Three Dimensions of LLM Observability
LLM observability differs from standard service monitoring. Three layers need watching simultaneously:
Operational Metrics
These overlap with traditional APM, but LLMs have unique metrics:
| Metric | Description | Alert Threshold (reference) |
|---|---|---|
latency_p99 |
End-to-end P99 latency | > 10s |
ttft (Time to First Token) |
Time to first token | > 3s |
tokens_per_second |
Generation speed | < 10 TPS |
input_tokens / output_tokens |
Token usage (directly drives cost) | over budget |
error_rate |
Grouped by error type | > 1% |
Quality Metrics
This is uniquely challenging for LLMs — how to quantify “is the answer good?”:
- Faithfulness: Is the answer grounded in retrieved context? (RAG scenarios)
- Relevance: Does the answer actually address the user’s question?
- Coherence: Is the answer internally consistent and logically clear?
- LLM-as-Judge score: Use another LLM to score output — practical for batch evaluation
Business Metrics
Ultimately what matters: did users get what they wanted?
- Task completion rate (does the user need to follow up multiple times?)
- User satisfaction (explicit ratings or implicit behavioral signals)
- Conversation abandonment rate (users who quit mid-session)
Tool Selection
Choosing the right LLM observability tool saves a lot of reinventing the wheel:
Langfuse
Open source, self-hostable, with Python and JavaScript SDKs. Biggest advantage: native integration with LangChain and LlamaIndex — a few lines to instrument. Supports prompt version management and A/B test tracking. Best for teams that need full data sovereignty.
Helicone
Proxy-mode integration — change one line (the API base URL), zero code changes. Routes OpenAI requests through Helicone’s proxy to automatically log all prompts and responses. Best for quick integration without touching the codebase.
Phoenix by Arize
ML observability background, stronger analysis for embeddings and retrieval quality. Has built-in Hallucination Detector and QA evaluators. Best for deep RAG system evaluation.
OpenTelemetry
If OTel infrastructure already exists, use the standard protocol and build a pipeline. The community maintains packages like opentelemetry-instrumentation-openai. Flexible but more build work required.
In Practice: Tracing Prompts/Responses with Langfuse
The example below uses the Langfuse TypeScript OpenTelemetry SDK (@langfuse/otel) (LANGFUSE_PUBLIC_KEY, LANGFUSE_SECRET_KEY, and LANGFUSE_BASE_URL read from the environment). To guarantee that no raw PII ever leaves the process, attach a synchronous global mask callback directly on LangfuseSpanProcessor (see Langfuse Masking):
import { NodeSDK } from "@opentelemetry/sdk-node";
import { LangfuseSpanProcessor } from "@langfuse/otel";
const EMAIL_RE = /\b[\w.+-]+@[\w-]+\.[\w.-]+\b/g;
function maskPii(data: unknown): unknown {
if (typeof data === "string") {
return data.replace(EMAIL_RE, "[REDACTED_EMAIL]");
}
if (Array.isArray(data)) {
return data.map(maskPii);
}
if (data && typeof data === "object") {
return Object.fromEntries(
Object.entries(data as Record<string, unknown>).map(([k, v]) => [k, maskPii(v)]),
);
}
return data;
}
const langfuseProcessor = new LangfuseSpanProcessor({
publicKey: process.env.LANGFUSE_PUBLIC_KEY,
secretKey: process.env.LANGFUSE_SECRET_KEY,
baseUrl: process.env.LANGFUSE_BASE_URL,
mask: ({ data }) => maskPii(data),
});
const sdk = new NodeSDK({
spanProcessors: [langfuseProcessor],
});
sdk.start();
// Flush explicitly before short-lived processes exit
process.on("beforeExit", async () => {
await langfuseProcessor.forceFlush();
});Every trace, child generation, token count, and latency span exported through OpenTelemetry passes through maskPii before export. Keep full payload capture gated behind explicit sampling and short TTLs, separate from security audit logs.
Key Metrics and Alerting
Set alerts in tiers:
P1 (immediate response):
- Error rate > 5% (grouped by
error_type:context_length_exceeded,rate_limit,content_filter) - P99 latency > 30s
P2 (respond within 1 hour):
- P95 latency > 10s
- Daily token consumption exceeds 80% of budget
- Faithfulness score below 0.75 for more than 1 consecutive hour
Trend monitoring (daily review):
- Average input/output token length trend (sudden increase may indicate prompt leakage or attack)
- Quality score week-over-week change
- New error types appearing
Prometheus alerting rules (sharing metric names with Prometheus + Grafana Monitoring for LLM Services, aggregating numerator and denominator explicitly by service and model to avoid label-matching bugs):
# prometheus-rules.yml
groups:
- name: llm_alerts
rules:
- alert: LLMHighErrorRate
expr: >
sum by (service, model) (rate(llm_http_requests_total{code=~"5..|429"}[5m]))
/ clamp_min(sum by (service, model) (rate(llm_http_requests_total[5m])), 1e-6) > 0.05
and sum by (service, model) (rate(llm_http_requests_total[5m])) > 0.1
for: 2m
labels:
severity: critical
annotations:
summary: "LLM error rate {{ $value | humanizePercentage }}"
- alert: LLMHighLatency
expr: >
histogram_quantile(
0.99,
sum by (le, service, model) (rate(llm_request_duration_seconds_bucket[5m]))
) > 30
for: 5m
labels:
severity: warningData Storage and Querying
LLM trace data can be high-volume — storage strategy matters:
Storage Options
- ClickHouse: high write throughput, columnar storage, ideal for querying large trace datasets. Langfuse’s self-hosted version uses ClickHouse.
- PostgreSQL: adequate for smaller volumes (< 1M requests/day), more flexible querying.
- S3 + Athena: cold data archiving, lowest cost, higher query latency.
Sampling Strategy
No need to store every request — sample by importance:
interface TraceContext {
error?: boolean;
hasFeedback?: boolean;
qualityScore?: number;
}
function shouldTrace(ctx: TraceContext): boolean {
if (ctx.error) return true; // Error requests: always record
if (ctx.hasFeedback) return true; // Requests with feedback: always record
if ((ctx.qualityScore ?? 1.0) < 0.6) return true; // Low quality score: always record
return Math.random() < 0.1; // Normal requests: 10% sample
}
const RETENTION_POLICY = {
fullFidelityDays: 90, // last 90 days at full detail
compressedDays: 365, // 90–365 days: key fields only
archiveDays: 730, // 1–2 years: cold storage
} as const;