Developer guide: 10. Feature flags
Create and evaluate feature flags: conditions, rollouts, payloads, exposure, scheduling and approvals.
10. Feature flags
A flag is a named switch that Lucida evaluates for one person at a time. Use flags to release code gradually, target by person properties, serve variants and JSON config, and to power experiments (section 11). Every call below was run against a real project.
Shorthand used in this part: P="$LUCIDA_API/v1/projects/$PROJECT_ID". In tables {p} is /v1/projects/{project_id}. Scopes are flag:read and flag:write unless the table says admin. Account keys that hold *:read and *:write cover both.
10.1 Flag kinds and create
Route | Scope | Purpose |
|---|---|---|
|
| list, |
|
| create, answer |
|
| one flag |
|
| partial update (null or absent = unchanged). While an experiment is running on the flag, a patch that changes what it serves (variant weights, |
|
| soft delete (restorable); |
|
| undelete; the flag comes back disabled (turn it on yourself) |
|
| deleted flags |
|
| versions: |
|
| flags that use this one as a prerequisite; |
Create body: key (required, 1-100 chars of letters, digits, _ - ., unique, else 400/409), name, description, kind, enabled (default false), filters, variants, payloads, stickiness, tags, encrypt_payload.
| Rules |
|---|---|
| no |
| 2 or more |
| serves a JSON payload; put it in |
| exactly the variants |
| variants carry model config payloads ( |
# boolean, on for 50% of pro-plan people
lc -X POST "$P/flags" -d '{"key":"new-checkout","name":"New checkout","enabled":true,
"filters":{"conditions":[{"rollout_pct":50,"filters":[{"type":"person","key":"plan","op":"eq","value":"pro"}]}]}}'
# multivariate with payloads and a stored (sticky) assignment
lc -X POST "$P/flags" -d '{"key":"cta-color","name":"CTA color","kind":"multivariate","enabled":true,
"variants":[{"key":"control","rollout_pct":50},{"key":"green","rollout_pct":50,"payload":{"color":"green"}}],
"filters":{"sticky":true,"conditions":[{"rollout_pct":100}]}}'
# remote config
lc -X POST "$P/flags" -d '{"key":"limits","name":"Limits","kind":"remote_config","enabled":true,
"payloads":{"default":{"max_items":10}},"filters":{"conditions":[{"rollout_pct":100}]}}'
# AI config
lc -X POST "$P/flags" -d '{"key":"assistant","name":"Assistant","kind":"ai_config",
"variants":[{"key":"default","rollout_pct":100,"payload":{"model":"x","messages":[{"role":"system","content":"You help."}]}}]}'The flag answer holds id, key, kind, enabled, filters, variants, payloads, stickiness, tags, version (integer, bumps on every save), lifecycle, expires_at, protected_envs, environment_state, owner_user_id, namespace_id, holdout_id.
Gotchas:
A new flag is
enabled: falseand a flag with no conditions matches nobody. A usable flag is enabled and has at least one condition.PATCHacceptsname,description,kind,enabled,filters(replaces the whole object),variants,payloads,stickiness,tags,expires_at,lifecycle(draft,active,launched,deprecated),owner_user_id,protected_envs,environment,reason(stored in history). Bad values answer400with the valid list.top-level stickinesspicks the hash unit (see 10.3).filters.stickystores assignments.Per-flag extras:
PUT|GET|DELETE {p}/flags/{id}/value-schema(body{"schema": JSON-Schema subset}, max 32 KB; saves that break it are400),PUT {p}/flags/{id}/purpose(below),GET|POST {p}/flags/{id}/linksandPOST .../links/issue(link tickets;kindisjira,linear,github,gitlab,docsorother; max 50 links per object),GET {p}/flags/{id}/usage?from=&to=(daily evaluation counts),GET .../impact?metric_id=&event=&days=,GET .../blast-radius(how many known people each condition serves),GET {p}/flags/code-refsandPOST(report code references),GET {p}/flags/sharedandGET|PUT|DELETE .../flags/{id}/shares[/{target_id}](share a flag with other projects),POST .../flags/{id}/copy-to-projects({targets:[project ids], overwrite?, copy_schedules?}).
10.2 The filters grammar
filters is an object. Everything is optional; conditions does the work.
Key | Type | Meaning |
|---|---|---|
| array | ordered; the first matching condition decides |
| bool | store on-assignments so allocation changes do not move people |
| bool | stop at the first condition whose filters match; a rollout miss there is final ( |
| bool | force off for everyone (use the kill route) |
| string | hash salt (rotate with |
| array |
|
| string[] | serve only to SDKs that declare one of these app contexts (max 50) |
|
| public keys never see |
| bool | an identified person keeps the bucket of their pre-identify anonymous id |
| object | set by experiments (holdout, layer range, switchback or geo design); do not hand-edit |
| string |
|
A condition is {rollout_pct, filters[], segment?, aggregation?, variant_override?, payload_patch?}:
rollout_pct(required, 0-100): share of units that pass once the filters match.filters[]: all must pass (AND). Conditions are ORed by order.segment: key of a flag segment (10.6); matches units in any segment rule AND this condition's own filters.aggregation:{kind: person|group|device|context, group_type?, context_kind?}per-condition bucketing unit.variant_override: serve this variant key when the condition matches (multivariate).payload_patch: RFC 7386 merge patch applied to the payload this condition serves.
A filter is {type, key, op, value}:
|
| Extra fields |
|---|---|---|
|
| |
|
|
|
| cohort membership (key = cohort id) | |
|
| |
| the SDK's app version | semver ops |
| another flag's value | |
| multi-kind context |
|
| an event count in the session or page |
|
op is exactly one of: eq, neq, in, not_in; contains, ncontains, icontains, not_icontains, starts_with, not_starts_with, ends_with, not_ends_with, regex, nregex; gt, gte, lt, lte, between, not_between; is_set, is_not_set; is_date_before, is_date_after; semver_eq, semver_neq, semver_gt, semver_gte, semver_lt, semver_lte, semver_tilde, semver_caret, semver_wildcard; array_contains_any, array_contains_all, array_contains_none; ip_in_cidr, ip_not_in_cidr. Anything else is 400.
# pro or team, in the EU, app version >= 3.2, not in the "internal" cohort
lc -X POST "$P/flags" -d '{"key":"eu-feature","name":"EU feature","enabled":true,"filters":{"early_exit":true,"conditions":[
{"rollout_pct":100,"filters":[
{"type":"person","key":"plan","op":"in","value":["pro","team"]},
{"type":"geo","key":"continent","op":"eq","value":"EU"},
{"type":"app_version","key":"app_version","op":"semver_gte","value":"3.2.0"}]},
{"rollout_pct":10,"filters":[{"type":"person","key":"beta","op":"is_set"}]}]}}'10.3 Variants, rollout, sticky bucketing, environments
Each unit hashes to a fixed point in 0-100 from the flag key, the salt and the unit id. A unit is in when its point is below
rollout_pct. Raising a rollout only adds people.stickiness(top level) chooses the hashed unit:distinct_id(default),person_id,device_id,group:<type>orcontext:<user|device|org>.filters.sticky: truestores the assignment (only "on" results: the booleantrueor the served variant). A stored person keeps their value (reason: sticky_bucket) even if rollout or weights change. A decide call writes sticky rows only for the flags it evaluated: those inflag_keys, or all flags when you name none.GET {p}/flags/{id}/sticky-assignmentsanswers{total, values:[{value, units}]};DELETEforgets them.POST {p}/flags/{id}/rerandomizebody{"confirm":"<flag key>","reason":"...","reset_sticky":false}rotates the salt. Everyone is bucketed again. Answer{flag_id, environments, sticky_removed, results_reset_at, warning}. While an experiment is running on the flag it answers409 experiment_running; with?force=trueit rotates the salt and restarts the experiment's analysis window, andresults_reset_atis set (as withPOST {p}/experiments/{id}/rerandomize).Environments: a project starts with
production(default) anddevelopment. A key belongs to one environment and that is the environment the flag is evaluated in.PATCHwith"environment":"development"writes an override ofenabledandfiltersfor that environment only; the base flag stays. Remove an override withDELETE {p}/flags/{id}/environments/{env}.GET {p}/flags/{id}/copy-preview?from=&to=shows a diff andPOST {p}/flags/{id}/copy {"from":"production","to":"development"}copies state across.protected_envslists environments where edits need approval (10.9).
10.4 Toggle, rollout, kill, dry-run, bulk
Route | Body | Purpose |
|---|---|---|
|
| turn on or off |
|
| set the rollout of the first condition (creates one when there is none) |
|
| set or clear |
|
| returns |
|
| up to 100 flags; each commits alone; answer |
The running-experiment guard (section 10.1) also covers these routes. While an experiment is running on the flag, toggle, rollout, POST .../copy (environment copy), DELETE .../environments/{env} (override removal), POST .../rerandomize, POST .../release/advance (a phase the pipeline applies directly), early access create and a PATCH that changes stage (they edit the flag's conditions), and bulk enable, disable and copy_environment answer 409 with type .../experiment_running, and every one takes ?force=true to override it (in a bulk call the refusal is that flag's error in the per-flag result, not an HTTP 409). POST .../kill always works. Not guarded: starting a gradual rollout plan (POST .../rollouts), a cross-project copy (POST {p}/transfers), applying a change request, and the system writers (the release pipeline's automatic progression, schedules, bandits). Treat those as bypasses and check for a running experiment yourself.
Bulk action values: add_tags and remove_tags (with tags), enable and disable (optional environment), copy_environment (with from and to). Anything else is reported per flag as unknown action.
FLAG_ID=$(lc "$P/flags?q=new-checkout" | jq -r '.data[0].id')
lc -X PATCH "$P/flags/$FLAG_ID/rollout" -d '{"rollout_pct":100}'
lc -X POST "$P/flags/$FLAG_ID/toggle" -d '{"enabled":true}'
lc -X POST "$P/flags/$FLAG_ID/kill" -d '{"active":true,"reason":"incident 42"}' # off for everyone
lc -X POST "$P/flags/$FLAG_ID/kill" -d '{"active":false}' # back to normal
lc -X POST "$P/flags/bulk" -d '{"action":"add_tags","ids":["'$FLAG_ID'"],"tags":["checkout"]}'10.5 Evaluate: server polling and the decide call
Two hosts serve flags to apps. Both are on the capture host $LUCIDA_CAPTURE.
Route | Auth | Purpose |
|---|---|---|
| public or secret key | decide: values for one person |
| project key | batched decide; the key is checked before the body, so a bad or missing key is |
| secret key with | all definitions of the key's environment for local evaluation; |
| secret key with a flag-read scope, as above (capture-only | plaintext payload of one remote-config flag without evaluating targeting: |
| project key | push of definition changes |
| project key | OpenFeature OFREP |
| public key | SDK config (autocapture, replay, consent mode) |
|
| the same definitions on the API host, for tools |
Server SDKs poll /v1/flags/definitions with a secret key that has flag:read (mint it with ["capture","flag:read"] to send events too) and evaluate locally. Cohort and big-segment filters need the server and come back as requires_server.
Decide request:
curl -sS -X POST "$LUCIDA_CAPTURE/v1/flags" -H "Content-Type: application/json" -d '{
"api_key":"'"$PK"'","distinct_id":"user_123",
"person_properties":{"plan":"pro"},"flag_keys":["new-checkout","cta-color","limits","typo"]}'Field | Meaning |
|---|---|
| or |
| required unless |
| inputs for the matching filter types |
|
|
| multi-kind context entries ( |
| for |
| declared app contexts |
| only these flags; omitted = all |
|
|
|
|
Response:
{"flags":{"new-checkout":{"enabled":true,"value":true,"reason":"condition_match","condition_index":0},
"cta-color":{"enabled":true,"variant":"green","value":"green","payload":{"color":"green"},"reason":"condition_match","condition_index":0},
"limits":{"enabled":true,"value":true,"payload":{"max_items":10},"reason":"condition_match","condition_index":0}},
"request_id":"4057e9cf...","unknown_flags":["typo"]}Per flag: enabled, value (true/false or the variant key), variant and payload when present, reason, condition_index (-1 when no condition decided), optional runtime branches for event-count filters. Top level: request_id, unknown_flags (requested keys the project does not have, only when there are some), quota_limited (plan quota exhausted: 200 with no flags, keep cached values), layer_defaults.
reason is exactly one of:
| Meaning |
|---|---|
| a condition's filters and rollout matched |
| nothing matched, value is off |
| a stored assignment decided |
|
|
| flag disabled (or archived) |
| kill switch on |
| a prerequisite decided it |
| needs server evaluation (cohort or big-segment filter on a client-side path) |
| no unit to hash |
| held out by an experiment holdout |
| outside the experiment layer range |
| flag not served to the declared app contexts |
| forced by the request |
| forced by a stored person preview (10.7) |
Errors are problem+json: 400 malformed or no unit, 401 bad key, 403 request origin on the flag blocklist (10.7), 429 rate limit (read Retry-After), 503 definitions unavailable (retry).
10.6 Exposure events
POST /v1/flags only decides. Experiment results count a person from their first exposure event, so HTTP callers must record one. SDKs do it for you. Either:
# one call: decide and record
curl -sS -X POST "$LUCIDA_CAPTURE/v1/flags" -H "Content-Type: application/json" \
-d '{"api_key":"'"$PK"'","distinct_id":"user_123","flag_keys":["cta-color"],"send_exposure":true}'
# or send both events yourself when you act on the value
curl -sS -X POST "$LUCIDA_CAPTURE/v1/batch" -H "Content-Type: application/json" -d '{"api_key":"'"$PK"'","batch":[
{"uuid":"0192f4c4-7f0e-7c3a-9d21-5b1f0e8a4c51","event":"$feature_flag_called","distinct_id":"user_123",
"properties":{"$feature_flag":"cta-color","$feature_flag_response":"green","locally_evaluated":false,"$feature_flag_request_id":"<request_id>"}},
{"uuid":"0192f4c4-7f0e-7c3a-9d21-5b1f0e8a4c52","event":"$exposure","distinct_id":"user_123",
"properties":{"$feature_flag":"cta-color","$feature_flag_response":"green","locally_evaluated":false}}]}'Results read event IN ('$exposure','$feature_flag_called') with $feature_flag = the flag key and the variant in $feature_flag_response (a string; empty is ignored). Either event is enough. send_exposure is not deduped across calls; do not send an exposure when your own fallback was served.
10.7 Segments, templates, previews, notifications, blocklist, settings, policy, purposes
Route | Scope | Purpose |
|---|---|---|
`GET | POST {p}/flag-segments | PUT |
|
|
|
|
| re-materialise a |
`GET | POST {p}/flag-segments/{id}/change-requests` | |
`GET | POST {p}/flag-segments/{id}/schedules | |
`GET | POST {p}/flag-templates |
|
`GET | POST | DELETE {p}/flag-previews` |
`GET | POST {p}/flag-notifications |
|
`GET | POST {p}/flag-blocklist |
|
`GET | PUT {p}/flag-settings` |
|
`GET | PUT {p}/flag-policy` |
|
|
| flag purpose and expected lifetime |
Segment
kind:rules(rules:[{filters:[...]}], OR of AND-ed filters),list(explicit member keys, no rules) orsynced(needssource:{table, column?}naming a mirrored warehouse table, else400). Thekeyis what a condition'ssegmentfield names. Unknown segment keys match nobody.Notification channels:
[{"type":"email","to":"..."}, {"type":"slack","url":"..."}];typeisemail,slack,teams,discord,webhookoraccount_team. Up to 100 flag keys; empty list = all flags; at least one channel. URLs are stored sealed and never returned (the answer shows only{type}).Blocklist
kindishostorcidr.Flag settings:
{confirm_on_save, default_conditions[], max_conditions, max_flags}.Flag policy:
{required_tags[], require_owner, require_description, allowed_contexts[]}. Allowed contexts aredistinct_id,person_id,device_id,group:<type>,context:<user|device|org>. Applies to saves from now on.Purposes (exactly):
release,experiment,operational,kill_switch,permission,sunset. Default lifetimes in days: release 40, experiment 40, operational 7, sunset 14, kill_switch and permission none.PUT .../flag-purposes/lifetimestakes{purpose: days|null}.
lc -X POST "$P/flag-segments" -d '{"key":"pro-users","name":"Pro users","kind":"rules",
"rules":[{"filters":[{"type":"person","key":"plan","op":"eq","value":"pro"}]}]}'
lc -X POST "$P/flag-segments" -d '{"key":"beta-list","name":"Beta list","kind":"list"}'
lc -X POST "$P/flag-segments/$SEG_ID/members" -d '{"add":["user_123","user_456"]}' # {"member_count":2}
lc -X POST "$P/flags" -d '{"key":"beta-ui","name":"Beta UI","enabled":true,
"filters":{"conditions":[{"rollout_pct":100,"segment":"beta-list"}]}}'
lc -X POST "$P/flag-previews" -d '{"distinct_id":"qa1","flag_key":"cta-color","variant":"green"}'
lc -X POST "$P/flag-blocklist" -d '{"kind":"cidr","value":"203.0.113.0/24","note":"scraper"}'
lc -X POST "$P/flag-notifications" -d '{"name":"to webhook","flag_keys":["new-checkout"],"channels":[{"type":"webhook","url":"https://example.com/hook"}]}'
lc -X PUT "$P/flag-policy" -d '{"required_tags":[],"require_owner":false,"require_description":true,"allowed_contexts":[]}'10.8 Health, stale flags, coverage, audit
Route | Scope | Purpose |
|---|---|---|
|
| every current health state (badges) |
|
| states |
|
|
|
`GET | POST {p}/flag-health-hooks` |
|
| token (no key) | alert receiver; unknown or revoked token is |
|
|
|
|
| per flag evaluation series |
|
|
|
Create a hook with {"name","format","signed?","trigger_id?"}; format is generic, alertmanager or watchtower (Watchtower hooks are always signed). The answer is {hook, url, secret}; url and secret appear once. Report with the generic format:
HOOK_URL=$(lc -X POST "$P/flag-health-hooks" -d '{"name":"pager","format":"generic"}' | jq -r .url)
curl -sS -X POST "$HOOK_URL" -H "Content-Type: application/json" \
-d '{"flag":"new-checkout","environment":"production","status":"unhealthy","reason":"error rate up","links":["https://example.com/alerts/1"]}'
# {"applied":1,"received":1,"triggered":null,"unmatched":[]}generic status values: healthy, unhealthy, ok, firing, resolved. A report without flag covers every flag in that environment. Signed hooks need Lucida-Signature: t=<unix>,v1=<hex HMAC-SHA256 of "<t>.<body>"> (5 minute tolerance). With trigger_id, an unhealthy report fires that flag trigger.
10.9 Schedules, rollout plans, guarded rollout, release pipelines, triggers
Route | Scope | Purpose |
|---|---|---|
`GET | POST {p}/flags/{id}/schedules | DELETE .../schedules/{sid}` |
| next runs of a recurrence | |
`GET | POST {p}/flags/{id}/rollouts |
|
`GET | POST {p}/flags/{id}/guarded-rollout |
|
|
| every move from rollouts, pipelines and guarded rollouts |
`GET | POST {p}/release-pipelines | PUT |
`GET | POST {p}/flags/{id}/release |
|
`GET | POST {p}/flags/{id}/triggers |
|
| token | fire a trigger |
Schedule body:
{action, run_at, payload?, recurrence?, cron?, ends_at?, timezone?, then?}.actionisenable,disable,set_rollout(payload{rollout_pct, condition_index?}),apply_filters({filters}),add_condition({condition, position: first|last}),apply_variants({variants}) orapply_payloads({payloads});payload.environmentselects an environment (not for variants or payloads).recurrenceisdaily,weekly,monthly,yearlyorcron(thencronis a five-field expression).ends_atneeds a recurrence and must be afterrun_at.thenis the paired second half (enable at 9, disable at 17) with its ownrun_at.Rollout plan:
steps:[{pct, hold_minutes?, guardrail_experiments?[]}], optionalenvironmentandstart_at. The answer hasstatus(running) andcurrent_step.Guarded rollout needs a multivariate flag (the first variant is the safe control). Body
{steps?:[10,50,100], advance_every_hours?, guardrails:[{metric:<metric uuid>, direction, threshold, action}]};directionislower_is_betterorhigher_is_better;actionisrollbackornotify(notifypauses untilacknowledge).Release pipeline body:
{name, description?, phases:[{name, environment, rollout_pct?, hold_minutes?(5-43200), requires_approval?, guardrail_experiments?[<=10], on_breach?: pause|rollback}]}. Start withPOST .../release {"pipeline_id"}; the release starts atcurrent_phase: -1andadvanceapplies the next phase or, for a gated phase, opens a change request (the answer holdsreleaseandchange_request).Trigger body
{name, action, environment?};actionisenable,disableorkill. The answer is{trigger, url, secret}shown once.
lc -X POST "$P/flags/$FLAG_ID/schedules" -d '{"action":"set_rollout","run_at":"2027-01-01T09:00:00Z","payload":{"rollout_pct":100}}'
lc -X POST "$P/flags/$FLAG_ID/rollouts" -d '{"steps":[{"pct":10,"hold_minutes":60},{"pct":50,"hold_minutes":60},{"pct":100}]}'
lc -X POST "$P/release-pipelines" -d '{"name":"dev-then-prod","phases":[
{"name":"Development","environment":"development","rollout_pct":100},
{"name":"Prod 10%","environment":"production","rollout_pct":10,"hold_minutes":60,"on_breach":"pause"},
{"name":"Prod 100%","environment":"production","rollout_pct":100,"requires_approval":true}]}'
lc -X POST "$P/flags/$FLAG_ID/triggers" -d '{"name":"pager","action":"kill"}' # keep .url secret10.10 Approvals, change requests, confirmations
The project approval policy puts risky actions behind a reviewed change request.
Route | Scope | Purpose |
|---|---|---|
`GET | PUT {p}/approval-policy` |
|
|
| propose a flag edit (same body as |
|
| list; |
|
| |
| ||
| request approval for `{subject: cohort | |
| none |
|
Policy keys (exactly): cohort.delete, dashboard.delete, experiment.start, experiment.pause, experiment.stop, experiment.update, flag.release, flag.enable, flag.disable, flag.rollout, flag.conditions, flag.variants, experiment.custom_code, segment.update. A rule is {quorum (default 1), approver_roles[], approver_users[], allow_self_approve (default false), condition, expires_hours (1-2160, default 168)}. condition.kind is any, rollout_above (pct), rollout_change (points), freeze_window (from_hour, to_hour, days) or flag_tagged (tags).
lc -X PUT "$P/approval-policy" -d '{"required":["flag.rollout"],"rules":{"flag.rollout":{"quorum":1,"allow_self_approve":false,"condition":{"kind":"any"},"expires_hours":24}}}'
lc -X PATCH "$P/flags/$FLAG_ID/rollout" -d '{"rollout_pct":50}'
# 409 problem type .../approval-required: "flag.rollout needs approval in this project; submit a change request"
CR=$(lc -X POST "$P/flags/$FLAG_ID/change-requests" -d '{"filters":{"conditions":[{"rollout_pct":50}]},"reason":"gradual"}' | jq -r .id)
lc -X POST "$P/change-requests/$CR/approve" -d '{"apply":true,"note":"ok"}' # a different admin unless allow_self_approveAn approved request applies as status: applied with applied_version. A request is stale if the flag changed after it was made. Clear the policy with PUT {p}/approval-policy {"required":[]}.