LangfuseLangfuse Python SDK 4.15.4 · Python 3.10+
0%
1
Curious builder0 XP earned · 300 to level 2
0 daysFinish a lesson to begin
Badge collection0 of 6 unlocked
38 small wins to finish your pathNext lesson

Sampling and switching tracing off

sample_rate sends only a share of traces, decided per trace from its id. tracing_enabled=False sends nothing at all, and your code runs unchanged.

Masking decides what each trace contains. At high volume you may also decide how many traces to send, to keep costs and noise down. Langfuse samples in your process, before anything is sent.

Examplesampling.py
from langfuse import Langfuse

import local_langfuse

url = local_langfuse.start()
langfuse = Langfuse(public_key="pk-lf-local", secret_key="sk-lf-local", base_url=url, sample_rate=0.3)
Examplesampling.py, continued
kept = []
for number in range(1, 11):
    trace_id = langfuse.create_trace_id(seed=f"ticket-{number}")
    with langfuse.start_as_current_observation(name="support-ticket", trace_context={"trace_id": trace_id}):
        pass

langfuse.flush()
sent = {span["trace"] for span in local_langfuse.SPANS}
print([number for number in range(1, 11) if langfuse.create_trace_id(seed=f"ticket-{number}") in sent])
Example
python sampling.py

Only ticket 2 was sent, and it is ticket 2 on every run. A rate of 0.3 is a probability for each trace, not a quota, so ten traces can give one or five; over thousands it comes close to 30%. The SDK uses OpenTelemetry's ratio sampler, which decides from the trace id, so with seeded ids from lesson 12 the choice is repeatable. Sampling is per trace: a trace is sent whole or not at all, never with half its observations. LANGFUSE_SAMPLE_RATE sets the same thing from the environment.

Switching tracing off

Exampledisabled.py
from langfuse import Langfuse

import local_langfuse

url = local_langfuse.start()
langfuse = Langfuse(public_key="pk-lf-local", secret_key="sk-lf-local", base_url=url, tracing_enabled=False)

with langfuse.start_as_current_observation(name="support-ticket"):
    pass

langfuse.flush()
print(local_langfuse.REQUESTS)
Example
python disabled.py

No request reached the server. tracing_enabled=False, or LANGFUSE_TRACING_ENABLED=false, turns every observation into a no-op while the code around it runs as normal. It is the switch for tests that should not trace, or for a deployment that must not send data at all.

Try it yourself
  • Change the rate to 0.5 and list which tickets are sent.
  • Seed the ids with order-{number} instead and compare the list.
  • Pass sample_rate=1.5 and read the error.

Little by little, you're building something great.