Sub topic 8
Specifying Events and Metric Definitions for Engineering
A metric in an experiment brief is a name and a hope. Engineering needs the events that feed it, and data needs the exact formula. This chapter shows how to turn "checkout completion rate" into a specification that both teams can build and test.
This chapter assumes you know what a primary metric and a guardrail metric are, and that you have a hypothesis and randomization unit chosen. It also assumes you can read short Python and YAML.
Why a written spec matters
Most "the data looks wrong" arguments trace back to one of three gaps:
- Two teams defined the same metric differently, for example "completed" meant payment authorized for one and order confirmed for the other.
- An event fires at the wrong moment, twice, or not on every platform.
- The assignment was never logged, so nobody can tell which users saw which variant.
Fixing these after launch costs a restart, because data collected under a broken definition cannot be repaired reliably. A one-page spec written before the build is cheaper.
From metric to events
Work backward from each metric in the brief. Ask which user actions must be recorded to compute it, then which properties each record needs.
For the checkout autofill experiment, the metrics need these events:
| Metric | Role | Events needed |
|---|---|---|
| checkout_completion_rate | Primary | experiment_exposure, checkout_completed |
| payment_error_rate | Guardrail | checkout_started, payment_failed |
| page_load_time_p95 | Guardrail | page_performance (with a duration property) |
Every experiment needs the exposure event, even though no metric names it. It is the denominator and the record of who was in which variant.
Anatomy of an event spec
An event spec has a name, a trigger, an identity, a timestamp, and properties. Write the trigger as a plain sentence about when the client or server emits it.
| Field | What to specify | Example |
|---|---|---|
| name | snake_case, past tense, unique | checkout_completed |
| trigger | The exact moment it fires | Server confirms the order is created, not when the button is clicked |
| source | Client or server | Server |
| identity | The randomization unit | user_id (never only a device or session id) |
| event_id | A unique id per occurrence, so duplicates can be removed | UUID generated at emit time |
| timestamp | UTC, from one clock | Server time, ISO 8601 |
| properties | Fields needed for filters and segments | platform, order_value, currency |
Prefer server-side events for outcomes such as purchases. Client events can be lost to ad blockers, closed tabs, and flaky networks, and the loss can differ by variant. Use client events for things only the client knows, such as rendering time or a click on a form field.
The trigger sentence is the part teams most often skip. "When the user completes checkout" has at least three plausible meanings, so name the system state that proves it happened.
Writing the spec as a file
Keep the spec in the same repository or document as the brief. YAML works well because engineers can review it in a pull request.
events:
- name: experiment_exposure
trigger: >
The user is shown the checkout page and the address form is
rendered in the variant they were assigned. Fires once per user
per experiment per session.
source: client
required_properties:
- user_id
- experiment_key
- variant
- event_id
- timestamp_utc
- name: checkout_completed
trigger: >
The server creates the order and payment is authorized.
source: server
required_properties:
- user_id
- order_id
- order_value
- currency
- platform
- event_id
- timestamp_utc
- name: payment_failed
trigger: The payment provider returns a decline or error.
source: server
required_properties:
- user_id
- error_code
- event_id
- timestamp_utc
metrics:
- name: checkout_completion_rate
unit: user_id
numerator: >
Distinct users with at least one checkout_completed event
within 7 days after their first experiment_exposure.
denominator: >
Distinct users with at least one experiment_exposure for
checkout_address_autofill.
exclusions:
- internal test accounts
- users exposed to both variants
timezone: UTCNotice that the metric block states the unit, the window, and the exclusions. These are the choices that quietly change a result when left to individual judgment.
Pinning down a metric definition
For each metric, answer these five questions in writing:
- Unit. Is the numerator counted per user, per session, or per order? It should match the randomization unit, or the analysis must correct for correlated observations.
- Denominator. Who counts as "at risk"? Usually users exposed to the experiment, not all users on the site. Counting unexposed users dilutes the effect.
- Window. How long after exposure does an outcome count? A 7-day window means a user exposed on Monday and converting the next Tuesday does not count. Every user needs the same window, or users who joined late get less time to convert.
- Deduplication. If two events share an
event_id, count one. Retries and double-fires are common. - Order of events. An outcome before the first exposure does not count as caused by the treatment.
Ratio metrics need extra care. "Revenue per order" divides by orders, but orders are an outcome of the experiment. If the treatment changes how many orders happen, the denominator itself moved. Prefer per-user metrics, such as revenue per exposed user, when the unit is the user.
Checking the definition with code
A short reference implementation removes ambiguity. Data writes it, runs it on a small sample, and engineering compares it with their own output. The example below applies deduplication, first-exposure, and the 7-day window from the spec.
from datetime import datetime, timedelta, timezone
def completion_counts(events, window=timedelta(days=7)):
"""Return {variant: (converted_users, exposed_users)}."""
seen = set()
deduped = []
for e in sorted(events, key=lambda e: e["ts"]):
if e["event_id"] in seen:
continue
seen.add(e["event_id"])
deduped.append(e)
first_exposure, variant = {}, {}
for e in deduped:
if e["name"] == "experiment_exposure" and e["user_id"] not in first_exposure:
first_exposure[e["user_id"]] = e["ts"]
variant[e["user_id"]] = e["variant"]
converted = set()
for e in deduped:
if e["name"] != "checkout_completed":
continue
start = first_exposure.get(e["user_id"])
if start is not None and start <= e["ts"] <= start + window:
converted.add(e["user_id"])
result = {}
for v in set(variant.values()):
users = [u for u, x in variant.items() if x == v]
result[v] = (sum(u in converted for u in users), len(users))
return result
t0 = datetime(2026, 11, 1, 12, 0, tzinfo=timezone.utc)
h = lambda n: t0 + timedelta(hours=n)
events = [
{"event_id": "a1", "name": "experiment_exposure", "user_id": "u1", "variant": "control", "ts": t0},
{"event_id": "a2", "name": "checkout_completed", "user_id": "u1", "ts": h(1)},
{"event_id": "a2", "name": "checkout_completed", "user_id": "u1", "ts": h(1)}, # duplicate
{"event_id": "b1", "name": "experiment_exposure", "user_id": "u2", "variant": "control", "ts": t0},
{"event_id": "c1", "name": "experiment_exposure", "user_id": "u3", "variant": "treatment", "ts": t0},
{"event_id": "c2", "name": "checkout_completed", "user_id": "u3", "ts": h(2)},
{"event_id": "d0", "name": "checkout_completed", "user_id": "u4", "ts": h(-1)}, # before exposure
{"event_id": "d1", "name": "experiment_exposure", "user_id": "u4", "variant": "treatment", "ts": t0},
{"event_id": "e1", "name": "experiment_exposure", "user_id": "u5", "variant": "treatment", "ts": t0},
{"event_id": "e2", "name": "checkout_completed", "user_id": "u5", "ts": h(24 * 8)}, # outside window
]
print(sorted(completion_counts(events).items()))It prints [('control', (1, 2)), ('treatment', (1, 3))]. Only u1 and u3 count as conversions. The duplicate is dropped, u4 converted before exposure, and u5 converted after the window closed.
Exposure logging
The exposure event deserves its own rules, because most analysis bugs begin there.
- Log at the point of difference. Fire the event when the user could actually see the changed experience, not when they are assigned. A user assigned at login who never reaches checkout should not be in the denominator for a checkout metric.
- Log both variants the same way. Control users must also fire
experiment_exposure. If only treatment logs it, you cannot compare like with like. - Record the variant in the event. Do not rebuild it later from a flag service, because flag configuration can change during the test.
- Log once, or dedupe. Repeat firing is fine if you dedupe on
user_idand use the first exposure time.
How the variant is chosen is covered in the next chapter. Here the point is that the assignment must be written to the event stream.
Common errors
- Metric names without formulas. "Conversion" means different things on different dashboards. Always write the numerator, denominator, and window.
- Mixed identities. Logged-out events keyed on a device id cannot be joined to a user-level metric. State how anonymous ids are linked to
user_id, or exclude logged-out users in eligibility. - Timestamps from different clocks. Client clocks drift and have time zones. Compare windows using server time.
- Schema drift. A property renamed from
order_valuetoamountbreaks the metric silently. Treat the spec as a contract and require a review for any change. - Platform gaps. The event exists on web but not on the Android app. Either implement it everywhere or restrict eligibility.
- Instrumentation changing the experience. A tracking call that slows the checkout page affects the treatment, and the guardrail metric may then reflect the logging.
Validating before launch
Ask engineering to run the experiment in staging with test users in both variants and check:
- Every event in the spec appears, with all required properties and no nulls.
- Exposure events fire for both variants, with the correct
variantvalue. - Duplicate
event_idvalues are rare, and a deliberate retry is removed by deduplication. - Data's reference query on the staged events matches the dashboard number.
Sign-off from product, engineering, and data on this checklist belongs in the brief, next to the decision rule.
Exercise
Your brief defines the primary metric as "orders per user". Engineering proposes a client-side order_placed event that fires when the Buy button is clicked. Name two problems with this definition and write the fix for each.
Show answer
First, a button click is not an order. The payment may fail or the request may never reach the server, so the metric overcounts, and the rate of failure may differ by variant. Fix: use a server-side order_created event that fires when the order is stored and payment is authorized. Second, "orders per user" does not name the denominator or window. Fix: state "distinct orders by exposed users within 7 days after first exposure, divided by distinct exposed users", with event_id deduplication. Also keep the exposure event for both variants, so the denominator can be computed.