Trace IDs & Distributed Tracing
Langfuse allows you to bring your own trace IDs (e.g., messageId, traceId, correlationId) for
- distributed tracing
- and linking traces across services for lookups between services.
💡
By default, Langfuse assigns random IDs (uuid, cuid) to all logged events.
It is recommended to use your own domain specific IDs (e.g., messageId, traceId, correlationId) as it helps with downstream use cases like:
- deeplinking to the trace from your own ui or logs
- evaluating and adding custom metrics to the trace
- fetching the trace from the API
Data Model
Trace IDs in Langfuse:
- Must be unique within a project
- Are used to identify and group related observations
- Can be used for distributed tracing across services
- Support upsert operations (creating or updating based on ID)
Usage
When using the @observe()
decorator:
from langfuse.decorators import langfuse_context, observe
import uuid
@observe()
def process_user_request(user_id, request_data, **kwargs):
# Function logic here
pass
def main():
# Custom ID for tracking
custom_observation_id = "custom-" + str(uuid.uuid4())
# Pass id as kwarg
process_user_request(
user_id=user_id,
request_data=request_data,
langfuse_observation_id=custom_observation_id,
)
# Get current trace ID from context
trace_id = langfuse_context.get_current_trace_id()
observation_id = langfuse_context.get_current_observation_id()
When using the low-level SDK:
from langfuse import Langfuse
# Set custom trace ID during creation
trace = langfuse.trace(
id="my-custom-trace-id",
name="Rap Battle",
)
Best Practices
- Consistent ID Format: Use a consistent format for your trace IDs across your application.
- Unique IDs: Ensure trace IDs are unique within your project to avoid conflicts.
- Distributed Tracing: Use the same trace ID across different services to link related operations.
- Error Handling: Implement proper error handling when working with custom trace IDs.