DocsObservabilityFeaturesTrace IDs & Distributed Tracing

Trace IDs & Distributed Tracing

A trace ID is a unique identifier that follows a request as it flows through your system. In distributed systems, trace IDs enable you to correlate operations across multiple services and reconstruct the full request lifecycle.

By default, Langfuse assigns random 32 hexchar trace IDs and 16 hexchar observation IDs.

Creating and accessing Trace IDs

Use create_trace_id() to generate a trace ID. If a seed is provided, the ID is deterministic. Use the same seed to get the same ID. This is useful for correlating external IDs with Langfuse traces.

from langfuse import get_client, Langfuse
langfuse = get_client()
 
external_request_id = "req_12345"
deterministic_trace_id = langfuse.create_trace_id(seed=external_request_id)

Use get_current_trace_id() to get the current trace ID and get_current_observation_id to get the current observation ID.

You can also use observation.trace_id and observation.id to access the trace and observation IDs directly from a LangfuseSpan or LangfuseGeneration object.

from langfuse import get_client, Langfuse
langfuse = get_client()
 
with langfuse.start_as_current_observation(as_type="span", name="my-op") as current_op:
    trace_id = langfuse.get_current_trace_id()
    observation_id = langfuse.get_current_observation_id()
    print(trace_id, observation_id)

Setting a custom Trace ID

You can set a custom trace ID when wrapping your application code with the Langfuse SDK.

Using the Context Manager

from langfuse import get_client
 
langfuse = get_client()
 
# Use a predefined trace ID with trace_context parameter
with langfuse.start_as_current_observation(
    as_type="span",
    name="my-operation",
    trace_context={
        "trace_id": "abcdef1234567890abcdef1234567890",  # Must be 32 hex chars
        "parent_span_id": "fedcba0987654321"  # Optional, 16 hex chars
    }
) as observation:
    print(f"This observation has trace_id: {observation.trace_id}")
    # YOUR APPLICATION CODE HERE

Using the Decorator

from langfuse import observe
 
@observe()
def my_operation(input):
    # YOUR APPLICATION CODE HERE
    result = call_llm(input)
    return result
 
process_user_request(
    input="Hello",
    langfuse_trace_id="abcdef1234567890abcdef1234567890" # Must be 32 hex chars
)
Was this page helpful?