Best practices and idiomatic patterns for using the Langfuse SDK, covering singleton clients, trace lifecycle, nested spans, decorators, sessions, and scoring.
langfuse-install-auth setupCreate a single Langfuse instance reused everywhere. Register shutdownAsync() for clean exit.
Create trace at operation start. Update with output on success. Update with error level on failure. Never await flush in hot paths.
Use parent/child spans: validation span, retrieval span, generation for LLM calls. Always call .end().
Use @observe() for automatic span creation. Use @observe(as_type="generation") for LLM calls. Access context via langfuse_context.
Link traces across conversation turns using sessionId. Set userId for user-level analytics.
Score traces with numeric values (0-1) for accuracy, relevance, and user feedback.
See detailed implementation for advanced patterns.
| Pattern | Issue | Best Practice |
|---|---|---|
| Client creation | Multiple instances | Use singleton pattern |
| Trace updates | Missing outputs | Always update on success/error |
| Span nesting | Orphaned spans | Always call .end() in finally |
| Flush timing | Lost data | Use shutdownAsync() on exit |
Basic usage: Apply langfuse sdk patterns to a standard project setup with default configuration options.
Advanced scenario: Customize langfuse sdk patterns for production environments with multiple constraints and team-specific requirements.