Experiments & A/B Testing
Experiments Are Powered by Feature Flags
In BillDog, an experiment is a feature flag with two or more variants and a conversion goal. The same evaluation engine that decides whether a flag is ON also assigns a user to a variant, so you reuse one targeting and bucketing model across simple rollouts and full A/B/n tests. The @billdog.io/ab-testing module (ABTest) fetches your assignments at init, serves them from a local cache, and emits exposure events for analysis.
1. Flag & Experiment Types
A FeatureFlagDefinition can model four common shapes. All four are evaluated by the same deterministic bucketing function, so behavior is consistent whether you ship a kill-switch or a four-arm experiment:
- Boolean — flag is simply ON or OFF.
getFeatureFlag(key)returnstrue/false. - Percentage rollout —
rollout_percentagecontrols what fraction of users see the flag ON (e.g.25→ 25% of users). - Multivariate — a
variants[]array (each with akeyandrollout_percentage) splits the ON bucket into named arms such ascontrol/v2/v3. - Targeted —
targeting_rules[]gate the flag to a subset of users by attribute. ALL rules must match before bucketing runs.
{
"key": "new_paywall_layout",
"active": true,
"rollout_percentage": 60,
"variants": [
{ "key": "control", "rollout_percentage": 30 },
{ "key": "compact", "rollout_percentage": 30 }
],
"targeting_rules": [
{ "attribute": "country", "operator": "equals", "value": "US" }
],
"payload": { "headline": "Upgrade today" }
}2. Reading a Flag or Variant In-App
The abTest singleton exposes synchronous accessors that read from the cache populated at init. Use getFeatureFlag for a boolean check, getFeatureFlagValue to read the chosen multivariate arm, and getFeatureFlagPayload to pull the variant's config. For goal-oriented experiments, getVariant resolves the assignment and getExperiments lists all active ones.
import { abTest } from '@billdog.io/ab-testing';
// Boolean: is this flag ON for the current user?
if (abTest.getFeatureFlag('new_paywall_layout')) {
showRedesignedPaywall();
}
// Multivariate: which arm was the user bucketed into?
const arm = abTest.getFeatureFlagValue('new_paywall_layout');
// → false (off) | true (on, boolean flag) | 'control' | 'compact'
// Pull the matched variant's payload (variant config or flag-level payload)
const payload = abTest.getFeatureFlagPayload('new_paywall_layout');
console.log(payload?.headline); // 'Upgrade today'Choose one bucketing key, then leave it alone
The userId is the bucketing key — it seeds the hash, so a different id is a different bucket. And setUserId re-fetches. Calling it with a new id partway through a session therefore re-buckets the same person: they can cross an experiment boundary and start seeing the other arm, and the exposures logged either side of the switch belong to different variants.
With BillDog Auth, bucket on the session token's sub claim — the user, the one who signed in — and use it from the first call. Do not bucket on cus, which is what they own rather than who they are. If you also want experiments for signed-out visitors, the two honest options are to enrol only after sign-in, or to bucket on an anonymous id and keep passing that same id after sign-in; swapping it for sub at sign-in is the case that moves people across arms. See Sessions & Tokens.
3. Local vs Server Evaluation
By default the client never decides bucketing itself. At init, ABTest POSTs to /experiment-config with the user_id and attributes; the server returns the resolved experiments and a feature_flags map. The client only reads that result. This keeps every platform — web, iOS, Android — in lockstep and prevents targeting logic from leaking to untrusted clients.
Server-Authoritative Evaluation
localEvaluation flag on ABTestConfig exists for trusted server/runtime hosts that pull definitions from POST /feature-flag-definitions (cached with a 5-minute TTL); when definitions are absent it falls back gracefully to the server-returned feature_flags map. For in-app clients, leave it off.When enabled in a server context, evaluateFlagLocally runs the identical algorithm on every platform: missing/inactive → false; all targeting_rules must match the attributes; then the rollout gate uses rollout_bucket = murmurhash3("flag:{key}:{userId}") % 100 and the flag is ON iff rollout_bucket < rollout_percentage. Multivariate arms are then picked by an independent hash — murmurhash3("flag-variant:{key}:{userId}") % 100, walked by cumulative rollout_percentage. The variant hash is deliberately separate from the rollout hash so a low rollout percentage can never starve the later arms.
// In-app client: server decides everything.
// No localEvaluation — assignments come from /experiment-config.
abTest.configure({
apiKey: 'bd_public_test_yourApiKey',
userId: 'user_9928',
attributes: { country: 'US', tier: 'premium' },
});
// Reads the server-resolved verdict from cache.
const enabled = abTest.getFeatureFlag('new_paywall_layout');4. Targeting Rules & Variants
targeting_rules gate enrollment by user attribute. Each rule has an attribute, an operator (equals, not_equals, contains, gt, lt), and a value. Every rule must match before bucketing runs. Once a user is in, variants divide the ON bucket into arms, and each arm can carry its own payload returned by getFeatureFlagPayload.
{
"key": "onboarding_flow_exp",
"active": true,
"rollout_percentage": 80,
"targeting_rules": [
{ "attribute": "tier", "operator": "equals", "value": "premium" },
{ "attribute": "signup_age_days", "operator": "lt", "value": 7 }
],
"variants": [
{ "key": "control", "rollout_percentage": 40 },
{ "key": "guided", "rollout_percentage": 40 }
],
"payload": { "show_checklist": true }
}Targeting on entitlement: read the token, not the customer record
tier above is a value you compute and pass. If you compute it from a customer's own materialised entitlements, it is incomplete for a member of a BillDog Auth organization. The organization has a customer record of its own, and a member's entitlements are the union of the personal and the organization ones — but the inherited half exists only in the session token's ent claim and is never written onto the member's own customer row. A paying seat therefore looks unentitled to anything that reads the customer record, and would be filtered out of an experiment it belongs in. Derive the attribute from ent, and check ent_truncated before treating that list as complete — it is capped at 64. See Sessions & Tokens.5. How Experiments Connect to the Rest of BillDog
Experiments are not an island — assignments flow into Analytics, Surveys, and Paywalls through the shared EventBus and the same flag-targeting model.
- Analytics (exposure events) — on assignment,
ABTestemitsab_variant_assignedon the EventBus with theexperiment_idandvariant_id. When BillDog serves the paywall (via the paywall/placement endpoints), the exposure and the purchase are tracked automatically — you do not need to calltrackImpressionortrackConversion. Call them manually only for custom, client-rendered experiments or non-paywall goals; both POST to/experiment-event. Either way your dashboards compute per-variant lift. Impression and conversion events for BillDog-served paywalls are experiment telemetry and are not counted toward your analytics event usage. - Surveys — a survey can be targeted by the same flag/attribute conditions, so you can show an NPS prompt only to a specific experiment arm and correlate sentiment with the variant.
- Paywalls — read
getFeatureFlagValue/getVariantto choose which paywall offering or layout to render, turning a flag into a live pricing/layout experiment.
import { abTest } from '@billdog.io/ab-testing';
// NOTE: only needed for CUSTOM, client-rendered experiments. When BillDog serves the
// paywall, the impression and the purchase are tracked automatically server-side —
// calling these as well would double-count that exposure.
// Log that the user was exposed to the variant (fire-and-forget)
await abTest.trackImpression('checkout_button_exp');
// Later, when the goal is hit, record the conversion (optionally with value)
await abTest.trackConversion('checkout_button_exp', 49.99, {
plan: 'yearly',
});
// 'ab_variant_assigned' is emitted automatically on the EventBus at init,
// so Analytics enriches downstream events with the variant the user saw.6. Automating the Experiment Lifecycle (Dashboard)
Everything above is the SDK / read side. The dashboard's Automation panel controls how an experiment is run — from “I decide everything” to “pick and ship the winner for me.” No SDK changes are needed: assignments keep resolving through the same server-authoritative path while the engine adjusts variant traffic underneath.
Automation mode
manual(default) — the engine never touches the experiment; you read results and ship a winner yourself.assisted— the engine computes a candidate winner and runs the kill-switch, but only surfaces them (a suggested winner + safety alerts). Nothing changes without your click.full_auto— the engine ships the winner and deprecates a tanking variant automatically once the gates below are met.
Winner criteria
A variant is eligible to win only when it clears both gates: a minimum relative improvementover control (min_improvement, default 5%) and a minimum confidence from the significance test (min_confidence, default 95% → z-test at α = 0.05), on the chosen metric (default conversion_rate).
Staged rollout & kill-switch
Rather than jump a winner straight to 100%, the engine ramps it none → 10% → 50% → 100%. Between stages a safety gate must pass — a dwell time must elapse AND each arm needs enough samples (min_sample_per_stage, default 100). At every stage the kill-switch watches for a conversion drop beyond max_conversion_drop (default 15%) vs. control, so a winner that tanks at 10% is rolled back before it reaches everyone. During a rollout the winner gets its stage weight, control gets the remainder, and all other variants get 0.
Ship the winner (one click)
In any mode you can promote a variant yourself. Ship winner sets that variant to 100% traffic and — when auto_deprecate_losers is on — drops the losers to 0% and marks them deprecated, then records the winning variant on the experiment. In full_auto the engine calls the same action automatically once the winner clears the criteria and the staged rollout completes.
Client apps need no changes
getVariant / getFeatureFlagValue and always receives the current server-resolved assignment — whether traffic is at 10% or the winner has shipped to 100%.Keep Reading
Was this page helpful?
Or rate this page: