---
title: "Run an A/B test"
description: "Define an experiment, branch on getExperiment() where the code changes, test each variant, start it, read the results and finish it with a winner."
canonical: "https://www.togohq.ai/docs/guides/experiments"
applies_to: "@togohq/sdk-browser 2.x"
updated: "2026-11-20T00:00:00Z"
---

# Run an A/B test

Define an experiment, branch on getExperiment() where the code changes, test each variant, start it, read the results and finish it with a winner.

An A/B test in Togo is an **experiment**: a `snake_case` name, two to ten variants, the id that
counts as one subject, and a participation rate. Your agent defines and runs it through the
[MCP tools](/docs/mcp), and your code asks the SDK which variant to show. Togo assigns the variant
deterministically, so never split traffic yourself with a random number or a cookie.

## Define it as a draft

Ask your agent to create it. It calls `create_experiment`:

```json
{
  "name": "checkout_cta",
  "hypothesis": "A one-click button raises completed checkouts.",
  "unit": "anonymous_id",
  "variants": [
    { "key": "control", "allocationBp": 5000 },
    { "key": "one_click", "allocationBp": 5000 }
  ],
  "baselineVariant": "control",
  "participationRateBp": 10000,
  "primaryMetric": "checkout_completed"
}
```

- **Choose the `unit` by when the id exists.** It is frozen once the experiment starts.

  | Unit           | Use when                                                                        |
  | -------------- | ------------------------------------------------------------------------------- |
  | `anonymous_id` | The flow runs before sign-in: most signup, pricing and checkout pages           |
  | `user_id`      | The user is signed in at the call, so `identify()` has already run              |
  | `device_id`    | The device is the subject; it survives `reset()`, where `anonymous_id` does not |

  Never "the user id when signed in, otherwise the anonymous id": one person would then be two
  subjects, and signing in could switch their variant.

- **The baseline is what everyone outside the test gets** — usually the current behaviour.
- **Allocations are basis points and total 10000.** They are frozen at start; participation is not.
- **Set a primary metric now**, before any result can tempt anyone to pick a different one. It may
  name an event that has no traffic yet.

The answer includes the `getExperiment()` snippet for this experiment and the next step.

## Branch on `getExperiment()` where the code changes

```ts
const result = await analytics.getExperiment('checkout_cta');

if (result.variant === 'one_click') {
  renderOneClickCheckout();
} else {
  renderCurrentCheckout();
}
```

- **Keep the `else`.** `variant` is `null` whenever there is no answer — the experiment is not
  started, the network failed, or consent is `pending` — and the `else` is what that visitor sees.
  The call always resolves within 800 ms and never rejects, so it cannot break the page.
- **Call it where the code branches**, never in a layout or a component mounted on every page. A
  participant's first call records them as entered, so calling it early counts people who never saw
  the change.
- **The SDK records the exposure for you.** It sends `$experiment_entered` once per participant, and
  every later event from that browser carries the variant, so any chart can split by it. Do not
  define or send `$experiment_entered` yourself.
- **To avoid waiting on the first call of a page**, list the name in `init()`; fetching ahead
  records nothing:

  ```ts
  const analytics = init({ writeKey: 'togo_pkl_…', experiments: ['checkout_cta'] });
  ```

On a server, pass the person on every call, as with `track()`:

```ts
const result = await analytics.getExperiment('checkout_cta', { userId: user.id });
```

The server records the exposure but does not mark later server events with the variant, and a
`device_id` experiment answers a server with its baseline. So judge the test by an event the
browser sends ([`@togohq/sdk-node`](/docs/reference/sdk-node#getexperimentname-person)).

## Test each variant with the test key

A draft is visible to test keys (`togo_pkt_…`) at once and to live keys not at all, so the code can
be tested before anyone else sees it.

1. Force a variant with `set_experiment_test_variant`. It applies to every test key in the project.
2. Run the flow, then `await analytics.flush()`.
3. Call `verify_tracking` with `filter.deviceId` and
   `expectExperiments: [{ name: 'checkout_cta', variant: 'one_click' }]`. It shows the variant each
   request got and the events that carried it.
4. Repeat for every variant, then clear the forced variant with `set_experiment_test_variant` and
   `variant: null`.

A test key asks on every call and records an entry once per variant per page load, so a test run
shows more requests and `$experiment_entered` events than production will. The `info` diagnostics
in the answer — such as [`experiment_draft`](/docs/reference/event-diagnostics#experiment_draft) —
explain each one; none of them is a fault.

## Start it, as the last step of the same task

Ask your agent to call `start_experiment`; it asks you to confirm once, because starting freezes
the unit, the variants, their allocation and the primary metric. Starting before the code is deployed is safe: an
experiment with no callers has no entries yet, and code deployed later picks it up.

Until it starts, production gets `not_found` and every visitor takes the `else`. When production
calls a draft, `list_experiments` marks it and the project's notification address gets one email.

## Raise participation as you gain confidence

`set_experiment_participation` is the one setting a running experiment can change. Raising it adds
new people and keeps everyone's variant; lowering it moves the people it removes to the baseline,
and `0` stops the test without finishing it.

## Read the results

`get_experiment_results` returns participants per variant, a sample-ratio check, and conversion
on the primary metric (or any event) per variant with its lift and a 95% interval. Results include
events after the next processing run, a few hours behind
([When your data shows up](/docs/concepts/data-freshness)).

- **A sample-ratio mismatch comes first.** It means the split the code produced is not the split you
  defined — often a call placed where only some variants reach it — and the comparison cannot be
  trusted until it is fixed.
- **Looking at an interval again and again overstates certainty.** Decide the length of the test up
  front and read the interval at the end.
- For any other event by variant, use `get_trend` with the breakdown `experiments.checkout_cta`.

The dashboard's **Experiments** page shows the same results.

## Finish it with a winner

`finish_experiment` takes the `winner`, which can be any variant; the baseline is how to abandon a
test. Every later `getExperiment()` call returns the winner with `status: 'finished'`, so the code
keeps working until you remove the branch. Finishing cannot be undone, and the name stays taken;
a winner chosen by mistake can be corrected on the dashboard.

## Check it works

Before you start the experiment, every variant has been forced, run and confirmed with
`verify_tracking` — [Check that events arrive](/docs/verify) covers the rest of a test run. After it
starts, `get_experiment` should show `active`, and `get_experiment_results` should show
participants in every variant once the next processing run has finished.
