Skip to content

@ogygia/flags

Experiments

Run A/B/n tests with weighted variants decided on the server, keep two experiments on one surface apart with layers, and send exposure events to your analytics in batches.

On this page

An experiment splits visitors between variants and measures which one does better. In ogygia the split is a flag with weighted variants, decided on the server, so each visitor’s variant is simply what renders, with no flicker and no client SDK. Counting what happened next is your analytics’ job: ogygia hands it one exposure event per decision.

import { flag } from '@ogygia/flags';

export const hero = flag('hero', { control: 50, bold: 50 });
import { decide, type ExposureEvent } from '@ogygia/flags';
import * as ogygia from 'ogygia/server';
import '$lib/flags';

decide({
  exposure: async (events: ExposureEvent[]) => {
    await fetch('https://analytics.example.com/v1/exposures', {
      method: 'POST',
      headers: { 'content-type': 'application/json' },
      body: JSON.stringify(events)
    });
  }
});

export const handle = ogygia.handle();

Variants

A record shape makes a weighted flag: each key is a variant, the first key is the control, and the values are ratios (Variants). Each identified visitor gets one variant, sticky across requests and servers. A visitor with no id gets the control and stays out of the split, so the split only ever changes for visitors you can recognize (Visitor identity).

Changing the weights moves only the visitors between a boundary’s old place and its new one: going from 50/50 to 60/40 moves a tenth of all visitors from bold to control, and nobody the other way. Adding, removing or reordering variants moves boundaries all along the range, and renaming the flag reshuffles everyone, so change those between experiments.

Branch on the variant with pick, as a value or, on the server router, as the page component itself:

import { hero } from '$lib/flags';
import type { PageServerLoad } from './$types';

export const load: PageServerLoad = (event) => ({
  headline: hero.pick(event, {
    control: 'Everything you need',
    bold: 'Everything. Today.'
  }),
  stamp: hero.stamp(event)
});

Layers

Suppose two experiments touch the hero section, a redesign and an autoplay video. If one visitor lands in both treatments and conversions move, you can’t tell which change caused it. Experiments on the same surface should never share a visitor.

Flags that share a layer string form a group. For each visitor, the layer makes one sticky decision before any member’s own rule runs: it hashes the layer name and the visitor’s id over the members’ names, sorted, to pick the visitor’s owner. Picture all traffic split into equal lanes, one per member. Reading a member then starts with one question: is this flag the owner for this visitor?

  • If it isn’t, it answers its control at once, and its targeting and weights never run for that visitor. That answer still sends an ordinary control exposure, so its control count includes visitors another member owns.
  • If it is, it carries on as if the layer didn’t exist, inside its own lane.

Mind the arithmetic. A member only experiments inside its own lane, so its real reach is its split divided by the number of members: a 50% variant in a two-member layer reaches 25% of all traffic, and adding a third member shrinks each lane to a third. Adding or removing a member reassigns lanes, so do it between experiments, not during one.

The lanes are worked out over the members registered when the flag is read. Members are sorted by name, so the order modules load in never changes a lane, but a member whose module hasn’t loaded at all isn’t counted. On plain SvelteKit, import all your flags in hooks.server.ts (Registration). Visitors with no id all hash into the same lane, so for them one member runs its own rule (its targeting, say) and every other member answers its control (#2310).

Some things outrank the layer. An override, carried claims and a source all come before the lane check, so ?og-exp=hero-redesign:bold shows QA the variant even for a visitor the other member owns, and a source that answers for a member bypasses the lane, which makes the vendor responsible for exclusion. Don’t run the same surface in both systems.

import { flag } from '@ogygia/flags';

export const heroRedesign = flag(
  'hero-redesign',
  { control: 50, bold: 50 },
  { layer: 'hero' }
);
export const heroVideo = flag(
  'hero-video',
  { control: 50, video: 50 },
  { layer: 'hero' }
);

Exposures

ogygia ships no metrics pipeline. It gives you the decision; counting conversions is your analytics’ job. The one connection is the exposure sink you set with decide({ exposure }). Since the decision happens during the render, a read is the exposure: the variant was rendered for that visitor.

Each event is { name, variant, sub, at }:

  • name and variant: the flag and what this visitor got;
  • sub: the signed-in visitor’s id from the context the flag was read with, or undefined (Sources and exposures);
  • at: the time in ms since the epoch, or 0 on the dev server.

A flag sends one event per request, on its first read, whatever decided it: the native rule, a source, an override or carried claims. So a QA session with ?og-exp sends events too, and a visitor who loads three pages sends three. Count unique visitors in your analytics. Events are sent from the server only; a browser never sends one.

Two kinds of control event aren’t a control arm (#2310). Below, “control” is the flag’s first variant: control in these examples, off for a boolean flag.

  • Out of a layer’s split. A layer member that doesn’t own the visitor answers its control and sends that as its variant, the same event a visitor in its control arm sends. Every visitor another member owns, its treatment included, lands in this member’s control count.
  • No id. A visitor with no id gets the control of every split, and each flag sends its control as the variant, with no sub.

The events can’t tell these apart from a real control arm today. What you can do: analyse on signed-in visitors only (events with a sub), which drops the no-id ones, though it also drops visitors keyed on a vid; and for a layer, drop from one member’s control each visitor another member of the same layer put in a treatment. A visitor another member owns and kept in its own control still can’t be told apart, so a layered experiment’s control arm stays mixed until the library marks these events.

Batching

Events go to the sink in batches, as an array. A batch is sent when it reaches batch.max events (25 by default), when its oldest event is batch.ms old (2,000 ms by default), or when the request that read the flags ends. batch: { max: 1 } sends each event on its own.

The response never waits for a send. One batch is sent at a time, in order, and events read during a send go in the next batch. When the platform offers waitUntil (serverless and edge platforms do), the send is handed to it, so the instance stays alive until it ends; otherwise it runs on in the server’s process.

Failures

A sink that throws or rejects never breaks a request. The batch is tried again, up to 3 times in all, after about 250 ms and then about 1 second, within 10 seconds. If it still fails, that batch is dropped and the server says flags_exposure_failed with the error, once, and not again until a send succeeds. To keep events through a longer outage, queue them inside your sink.

Without the flags() plugin, the request’s end doesn’t send the batch, so events wait for the size or age cap.

import { decide } from '@ogygia/flags';
import { analytics } from '$lib/server/analytics';

decide({
  exposure: (events) => analytics.track(events),
  batch: { max: 50, ms: 5_000 }
});

Stamps

For analytics that reads the page, or a log line, flag.stamp(c) returns name:variant (Stamps). Render it as data-og-exp on the part of the page the experiment changes.

<script lang="ts">
  import type { PageProps } from './$types';

  let { data }: PageProps = $props();
</script>

<section data-og-exp={data.stamp}>
  <h1>{data.headline}</h1>
</section>