A/B testing prompts with Langfuse labels

Run live prompt experiments in self-hosted Langfuse by labeling variants, splitting traffic in your application, and comparing latency, cost and scores per version.

On this page

How A/B testing prompts with Langfuse labels works for production teams

When a team changes prompts that reach real users, it needs evidence before a full rollout. Langfuse labels can mark prompt variants, and the application can split traffic between them, with metrics for each version compared inside Langfuse. Langfuse does not assign traffic itself. The split logic lives in your application code, which decides for each request which label to fetch, records that label on the trace, and sends the response to the user. Langfuse then records latency, cost and scores per prompt version, so the comparison depends on the application tagging each generation correctly.

That division of work shapes the design. Your team owns the bucketing rule: how requests or users are assigned to a variant, whether the assignment is sticky for a given user, and what share each variant receives. Those rules belong in version-controlled code with the same review as any other release change. Ask your engineers to confirm that the assignment is deterministic per user or session, so that a single user does not flip between variants mid-conversation, and that the variant identifier travels with every trace. Without that link, per-version dashboards will mix traffic from both variants and the results will not support a decision.

Plan the rollback path before the experiment starts. Moving a label back is the fastest way to stop serving a losing variant, but it only works if the application reads labels at request time or through a cache with a known refresh interval. Confirm with your platform team how long a label change can take to reach running services, and who holds the permission to move production labels. Protected labels and role design are covered in the sibling topics, so here the main check is simple: the person who ends the experiment should be able to do so without a code deployment.

Request flow for a labeled prompt experiment

The flow starts when an application request arrives. The application hashes a stable user identifier into a bucket and picks variant A or B, then fetches the prompt carrying that variant's label from self-hosted Langfuse. The model call runs, and the trace goes back to Langfuse tagged with the prompt version and any scores. Check that the bucket is stable across requests, that the trace records the prompt version, and that an analyst compares per-version metrics rather than per-label totals.

Labeled variant selection, trace capture and per-version comparison in self-hosted Langfuse.

Which experiment design fits which change

This table compares three ways to test a prompt change: a live label-based split, a dataset experiment run before release, and a shadow or offline comparison. Read each row against the kind of change you are making, and note that the main risk of the live split is exposing real users to an unproven version.

DesignWhen it fitsWhat it measuresMain risk
Live label splitWording tweaks where real traffic is needed to confirm the effectLatency, cost and scores per prompt version, tied to tracesUsers receive the unproven version, and small samples can mislead
Dataset experiment before releaseChanges to instructions, tool use or output format that can be checked against known casesScores on a fixed dataset for each candidate version, before any label movesThe dataset may not represent production inputs, so scores can look better than live results
Shadow or offline comparisonModel or parameter changes where a candidate can run beside production without affecting usersOutput differences and cost on copied or replayed inputsReplayed inputs may omit side effects, and extra model calls add spend
Staged label rolloutChanges with customer impact that need a limited first audiencePer-version metrics for a small share of traffic before a wider moveTraffic assignment logic in the application must be correct and consistent
Protected production label changeAny change that will reach customers after a passing testWhether the candidate met agreed thresholds before the label movesReview steps slow releases if reviewers lack clear criteria
Rollback by moving a labelRecovering quickly when a live variant degrades scores or latencySpeed of return to the previous versionRollback only works if the previous version and its label are recorded
Hypothetical example: tone changeIllustrative only: a support prompt rewritten for a friendlier toneDataset scores first, then a small live split to check handoff ratesScores may not capture user satisfaction, so live review is still needed

Setting up a labeled prompt experiment step by step

This sequence takes a team from a verified self-hosted Langfuse instance to a live prompt experiment that splits traffic by label, records which version produced each trace, and ends with a promote or roll back decision made by moving the production label.

  1. Confirm instance and SDK versions

    The platform engineer checks the self-hosted Langfuse version against the release notes and the SDK versions the application uses. Langfuse's upgrade guide says updates within a major version apply database migrations at startup, and the v3 to v4 guide lists ClickHouse 25.12 or later, PostgreSQL 15 or later and Redis 7.0 or later. Python SDK v5 and JS/TS SDK v6 need Langfuse v4.59.0 or later. Confirm these against your own deployment and the current release page before you change anything. The step is done when the server version, the SDK versions and the data store versions are written down and match. Verify by sending a test trace from each SDK and seeing it appear in the UI.

  2. Create baseline and candidate prompt versions

    The prompt owner creates the current production prompt as the baseline and a second version with a single, deliberate change as the candidate. Keeping one change per experiment makes the results attributable to that change. Store model settings and any tool definitions with the prompt version so both variants differ only where you intend. The step is done when both versions exist in the prompt library with distinct version IDs. Verify by fetching each version through the API or SDK and comparing the returned text and config to the intended difference.

  3. Assign experiment labels to each variant

    Attach an experiment label, such as a name that identifies the test, to the baseline and to the candidate. Keep the production label on the baseline so that users outside the experiment are unaffected. Protected labels, which restrict who can move them, are an Enterprise license feature, so confirm whether your instance has a key before relying on them for production labels. The step is done when each experiment label resolves to exactly one version. Verify by requesting each label and confirming it returns the version you expect, and that the production label still returns the baseline.

  4. Implement deterministic bucketing in the application

    The application developer assigns each request or user to a variant with a stable function, for example a hash of a user or session identifier modulo the traffic share. Deterministic bucketing means the same user receives the same variant across requests, which keeps conversations consistent and keeps comparisons clean. Record the assigned variant label in the request context so it can be attached to traces. Avoid random assignment per request, because a single user would then see both variants. The step is done when the bucketing function is unit tested with sample identifiers. Verify that repeated calls with one identifier always return the same variant and that the split across a sample population matches the intended share.

  5. Instrument traces and scores with the version

    The developer fetches the prompt by the bucket's label and links each generation to the prompt version that produced it, so cost, latency and scores can be grouped by version. Add the experiment label or variant name as trace metadata or tags, and attach user feedback or evaluation scores to the same trace. Confirm that the SDK or OpenTelemetry instrumentation you use sends traces to your instance's ingestion endpoint. The step is done when a test request produces a trace that shows the prompt name, the version and the experiment label. Verify by opening that trace in the UI and checking that the version shown matches the label you requested.

  6. Run the experiment and compare variants

    Route the agreed share of traffic to the candidate and let it run until enough traces exist for each variant to be compared. Use the Langfuse trace and prompt views to compare latency, token cost and scores per version, and filter by the experiment label to isolate results. Dataset experiments, which run prompts against a fixed set of inputs, should come first when you can build a representative dataset, because they are cheaper to repeat and do not expose users to a weaker prompt. The step is done when you have a written comparison with the metrics you agreed in advance. Verify that the traces counted per variant match the bucketing split and that no trace is missing its version.

  7. Promote or roll back by moving the production label

    Decide on the outcome against the criteria written before the test. To promote, move the production label to the candidate version; to roll back, leave or move the production label to the baseline. Because labels are pointers, the change takes effect without a code deployment, and the previous version remains available for another rollback. Record who made the change and why. The step is done when the production label resolves to the chosen version. Verify by fetching the production label from the application and confirming that new traces carry the expected version, and by removing the experiment label once the test ends.

When dataset experiments should come before live traffic

Run a dataset experiment before any live split when a change can break output shape, safety behavior or cost. Variants that alter structured output (a JSON schema, a tool call format, a classification label set), touch refusal or safety-sensitive wording, or move a request onto a more expensive model should be tested against a fixed dataset first. Live traffic is the wrong place to discover that a downstream parser fails on a missing key or that a model switch multiplied spend. Build the dataset from representative and edge-case inputs, run each variant as a dataset experiment, and gate promotion on the checks that matter for that change. The setup of datasets, evaluators and experiment runs is covered on the sibling Langfuse evaluations and datasets page, so this section only sets the decision rule.

A dataset run shows how a variant behaves on inputs you chose, scored by the evaluators you configured. It cannot show how real users phrase requests, which conversations continue across turns, how often a prompt is hit under production load, or whether a score you trust actually tracks user satisfaction. Those are the questions a live label split answers, which is why the two methods complement each other. Before you rely on a dataset result, confirm that the dataset reflects recent production inputs, that your evaluators have been checked against human judgment on a sample, and that cost and latency figures from the run are measured under conditions close enough to production to compare. Use the dataset run to decide which variant is allowed into the live split, then use the split to confirm the result holds in traffic.

Security and governance risks of changing production prompts mid-experiment

An A/B test on prompts changes what production users receive, so the people who move labels, the records they leave behind and the data flowing through traces matter as much as the statistics. The cards below cover the controls to decide on before the experiment starts and the license tier each one depends on.

Who may move experiment labels

Splitting traffic depends on labels such as production, staging or a candidate label, and anyone who can move a production label can change what every user receives mid-test. Decide which roles may create candidate labels, which may promote a variant to production, and who ends an experiment. Write these roles down before the test begins, and confirm how project-level roles are assigned in your self-hosted instance, since fine-grained role controls depend on your license tier.

License key docs

Protected labels need an Enterprise key

Protected prompt labels restrict who can move a label such as production, so only approved roles can change the variant users receive. In self-hosted Langfuse this feature requires an Enterprise license key. If you rely on it, confirm the license tier with your Langfuse contact before you design the approval flow, and plan a manual change review for the same labels on the open source tier.

License key docs

Audit logs for label changes

During a test you need to answer who moved a label, when, and from which version. Audit logs record these administrative actions, but they are an Enterprise license feature in self-hosted Langfuse. Without them, keep a dated change record in your change management system that links each label move to an experiment ID and an approver. Confirm which events the audit logs capture before you rely on them as evidence.

Personal data in traces

Experiment traces store full prompts, completions and user inputs, so personal data can end up in every variant's history. Two variants that differ only in wording still produce identical personal data exposure, and a losing variant may keep its traces long after the test ends. Set retention for experiment projects, define who can read raw traces, and check whether server-side masking is available on your tier before you enable tracing for live traffic.

Keeping assignment logic out of prompts

The code that decides which user gets which variant, along with any feature flags, sampling rates or customer lists, should live in application configuration, not inside prompt text. When assignment rules sit in the prompt, a prompt editor can change who sees which variant without review. Keep the split logic in version-controlled code, reference only the label name in the prompt, and log the assignment key with each trace.

Credentials stay out of prompts

Prompts are visible to everyone with read access to the project, and they are copied into traces and exports. API keys, connection strings or tool credentials placed in a variant are exposed to every reviewer and may persist in history after the test. Pass credentials through your secrets manager at runtime, scan prompt text for key patterns before publishing a label, and rotate any key that was ever pasted into a prompt.

Questions teams ask before running prompt A/B tests in Langfuse

How much effort does a first prompt A/B test take?

A first live experiment is mostly application work and agreement work, not Langfuse configuration. Effort is driven by how many call sites use the prompt, whether the application already reads prompts by label, whether traces already link generations to prompt versions, and how many people must agree on the success metrics before traffic is split. A team that already versions prompts and sends traces with prompt metadata can usually start sooner than one that hardcodes prompts in code. Ask any partner to split the estimate into instrumentation, traffic routing, analysis and the decision record, so you can see which part your own engineers can absorb.

Can our team run prompt A/B tests in Langfuse without outside help?

Yes, if your engineers can read prompts by label in application code and your analysts can query per-version latency, cost and scores. Langfuse core features, including prompt labels, tracing and scores, are available in the MIT-licensed open source version. Outside help is most useful for the first experiment, for designing the traffic split so it is stable per user or session, and for setting up the self-hosted infrastructure that stores the traces. Protected labels and some governance features need an Enterprise license key, so confirm which controls you need before you design the release process.

What do our engineers and analysts need to contribute?

Engineers own the routing logic, the fallback behavior when a prompt fetch fails, and the tagging that connects each generation to the prompt version and experiment arm. Analysts own the metric definitions, the comparison queries and the decision criteria. Product or domain owners must agree on what a better answer means, because automated scores only reflect what they were built to measure. Plan time for someone to review sampled outputs by hand, since a score that looks better can still hide worse answers for a segment of users.

How long should a prompt experiment run?

The duration should come from your own statistics, not from Langfuse. Decide the minimum effect size that matters, the metric you will judge on, the traffic each arm receives and the significance level before the test starts, then calculate how many generations each arm needs. Low-traffic features, high variance scores and weekday or seasonal patterns all lengthen the test. Langfuse shows the per-version data, but it does not decide when the result is conclusive. Record the stopping rule in writing so the test is not ended early because one arm looks ahead.

What does running prompt experiments cost on self-hosted infrastructure?

Costs fall into three groups. The first is infrastructure: Langfuse runs Web, Worker, PostgreSQL, ClickHouse, Redis or Valkey and S3-compatible blob storage in your environment, and the scaling guide lists minimum resources for each, with ClickHouse needing the most memory for larger deployments. The second is model spend, because variant traffic produces real generations with tokens. The third is people: setup, routing code, analysis and review. Infrastructure and model spend recur. Setup and analysis are largely one-time for each experiment type. Ask for each cost line separately in any quote, and confirm your expected trace volume before sizing ClickHouse.

Are prompt labels alone enough for statistically sound results?

No. Labels tell the application which prompt version to serve and let you compare versions in traces, but they do not randomize users, control for other changes or calculate significance. Statistically sound results need a stable, random assignment of users or sessions to arms, enough sample size, metrics that match the decision, and a check for confounders such as a model change or a traffic spike during one arm. Dataset experiments are a better first step when you can build representative test cases, because they compare versions offline before any user sees the change.

Should we run dataset experiments before a live A/B test?

In most cases, yes. Dataset experiments let you run candidate prompts against a fixed set of representative inputs and compare scores before exposing users to a change, which catches obvious regressions cheaply. Live A/B tests then answer questions the dataset cannot, such as real user behavior, latency under production load and cost at real traffic mix. Keep the dataset current with production failures, or the offline result will drift from what users see. Your evaluation scores need to be trustworthy before either approach gives a useful answer.

What a DeployOpen experiment setup includes

A fixed-scope engagement for prompt experiments produces a small set of working artifacts, and the scope and timelines for each are agreed in writing before work starts. The first deliverable is a review of the self-hosted Langfuse deployment and the SDK versions in your applications, since the label-based comparison depends on the trace and observation data your SDK sends and on how your instance stores it. The review also confirms which Langfuse features your team can use on its current license, because protected labels and some governance controls need an Enterprise license key, and the scope should say whether that is in or out.

The second deliverable is the label and bucketing design: the names of the candidate labels, which variant each traffic bucket receives, how the split is keyed (for example, a stable user or session identifier so one user does not switch variants mid-conversation), and how the application falls back to a known-good version when the prompt fetch fails. DeployOpen then implements the split in your application code and writes the query or dashboard that compares latency, cost and scores per prompt version, using the version link that Langfuse records on each generation. Your team should decide in advance which metrics count as a win and how many samples are required before a decision is made.

The third deliverable is a runbook for promotion and rollback. It names who may move a candidate label to production, the steps to shift traffic back by moving a label, the checks to run after each change, and the owner who signs off. Ask each partner to show how the runbook maps to the roles in your Langfuse instance and whether any label moves need the protected label feature. Ask for the written scope to state which of these items are included, what your team must provide (such as application access and a staging environment), and how retesting after handover is handled.

Official Langfuse documentation to read alongside this page

The four official pages below cover the platform decisions behind a live prompt experiment: where the traffic-splitting service runs, how it scales, how upgrades change the data model, and who can reach the experiment. Read them before you choose label names and a rollout plan, because each one sets limits that the experiment design has to respect.

Self-hosting overview

This page lists the components a self-hosted Langfuse instance runs, including the web and worker containers, PostgreSQL, ClickHouse, Redis or Valkey and S3-compatible blob storage. For A/B testing, check which component holds the label assignments and the scores you will compare, and which ones your application depends on at request time. Confirm whether your deployment method is suitable for the production traffic you expect. Confirm the component list against your chosen deployment method before you size anything.

Self-hosting docs

Scaling guide

The scaling guide describes when to add worker capacity and when heavy ingestion calls for separate ingestion and user interface deployments of langfuse-web. Experiments generate many generations and scores in a short window, so ingestion load during a test can differ from normal use. Check the minimum resources listed for each component, and plan ClickHouse memory for the volume of trace data your variant comparison will read.

ClickHouse memory
16 GiB
Scaling guide

Upgrade guide

Minor and patch updates within a major version apply database migrations at startup, while major upgrades follow dedicated migration guides that change infrastructure and the data model. Before you run a multi-week experiment, check whether a major upgrade is scheduled, because a change in the observation data model can alter how per-version latency and cost are queried. Confirm the Helm chart and SDK versions your application uses are compatible with the target release.

Upgrade guide

Authentication and SSO

This page explains how SSO providers are configured, whether password sign-in can be disabled, and how sign-in can be enforced for given email domains. For experiments, the question is who can move labels and read per-variant results. Check that the people who review experiment outcomes sign in through the identity provider your organization audits, and that password fallback accounts are restricted. Confirm which role controls apply on your license tier before you grant access.

SSO docs

How DeployOpen scopes, delivers and supports Langfuse experiments

DeployOpen approaches prompt A/B testing as a planned change to a self-hosted Langfuse instance inside your infrastructure. We agree the experiment design, the label and traffic-split logic, and the evidence your team needs before a variant is promoted, then build and document it so your engineers can run future experiments themselves.

How we scope

  • The written scope names the prompts, variants, labels and applications that the experiment covers
  • It defines which metrics decide a winner, such as scores, latency and cost per prompt version
  • Engagements are fixed-scope, with deliverables and timelines agreed in writing before work starts

How we build

  • We configure labels, the traffic split in your application and the trace tagging that links generations to each version
  • We test the split logic, fallback behavior and tracing in a non-production Langfuse environment first
  • Dataset experiments are added where offline comparison should come before any live traffic is exposed

How we hand over

  • You receive the experiment runbook, label naming conventions and a documented promotion and rollback procedure
  • Your team walks through the comparison dashboards and the criteria for ending an experiment
  • Access roles and who may move production labels are documented alongside the experiment design

How we support

  • Ongoing support, upgrades and continuous testing are available as retainers after handover
  • We can review experiment results and tune the split or metrics as your prompts and models change
  • Before any Langfuse upgrade that changes the data model, we plan the impact on existing experiment history

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.