# Feature flags

> For agents: start with the [agent guide](https://ratstack.sh/llms.txt). Every page is Markdown by default; add `Accept: text/html` for HTML.

New on /news: [Rivet self-hosts on any cloud through Alchemy](/news).

## What it does

The `packages/flags` [cartridge](/lore/cartridges) evaluates typed flags.
A flag declares its name, [schema](/lore/schemas-define-the-boundary), default, owner, purpose, removal date, and [evidence ladder](/lore/flags-climb-on-evidence).

Each rung names its authority and exit measurements. A read scope is the partition for a flag value and its evidence.
A child schema defines it; the default is `global`.

Handlers request the `Flags` [service](/lore/services-capture-dependencies) from core.
The Config [adapter](/lore/hexagonal-architecture) reads deployment configuration.
The memory adapter supplies rules and writable values for tests.

The KV adapter owns its namespace through [Alchemy](/skills/learn-alchemy).
Under the default policy, missing KV values use Config values or declared defaults.
The `refuse` policy returns a typed failure on a missing or failed replica read.

- `listFlags` lists names, owners, and removal dates.
- `getFlag` evaluates one flag for an optional subject.
- Allow-lists select a value for named subjects.
- Percentage rules use a stable hash of the flag name and subject.
- The first matching rule wins. Missing subjects use the default.

`EVENTS_ENABLED` defaults to `false` and stays deploy-time Config.
Live KV writes cannot change this flag.

`EVENTS_IDENTITY_MODE` defaults to `daily`.
The Worker reads its live value for each captured request.
Config keeps the existing environment keys and boolean spellings.
An empty KV namespace preserves Config behavior.

Invalid Config stops initialization.
A failed KV read follows the catalog's `failurePolicy`.
The default policy returns the declared default. The `refuse` policy preserves the typed failure.

Previews use Config and declare no flags namespace.
The production Worker and content backend read KV.

[Alchemy](/skills/learn-alchemy) still selects analytics resources during deployment.
See [Analytics](/systems/analytics) for capture and identity behavior.

## The standard

- Flag values pass their declared schemas.
- Every declaration names an owner and a `removeBy` date.
- Lint rejects declarations without a literal removal date.
- The flags build rejects expired registered events flags with a typed repair message.
- Each subject keeps its rollout bucket when the rollout percentage changes.
- The lifecycle permits `declared` → `rollingOut` → `on` → `removed`.
- Declared [Effect](/lore/effect-basics) actors record lifecycle transitions. Removed flags stay removed.
- Each [capability](/systems/capabilities) shares its [contract](/systems/capabilities) across surfaces. JSON encoding is required for `getFlag`.

Three operator capabilities replace the raw setter:

- `flip_feature_flag` climbs one rung or flips `off`.
- `record_flag_evidence` records a measurement at the current rung and exact scope.
- `read_flag_ledger` reads a bounded attempt page and the authoritative position.

Climbs use the capability approval service. Above agent, they also need an `approvalRef` quote.
The roles are `agent`, `arbiter`, and `owner`. Token checks belong in the child's composition.

`off` bypasses approval and still records its caller in the attempt ledger.

The CLI accepts `--yes` or asks for interactive approval on a climb.
Its default composition has no live ledger and returns a named error.

The CLI records `local-cli` as a channel label.
Its caller has no authenticated person identity.

The public Worker, [RPC](/skills/learn-rat-stack) readers, and read-only sandbox expose no flag writes.
A child mounts its operator [surface](/lore/one-schema-three-surfaces) and supplies its approval policy and ledger adapter.

Each available-store attempt records its caller, flag, observed old value, requested value, time, and outcome.
The journal stores an immutable Pending key before the approval gate.
A separate completion key records success, denial, failure, or interruption.
Both keys share an attempt id.

Missing completion means Pending with an unknown result.
A failed completion write returns a typed error; the flag may have changed.
Audit storage failures block only writes.
Config and default journals use composition-local memory.

A projection is a copy derived from a committed value.

The default operator adapter uses one Durable Object per flag and scope.
It serializes transitions and commits the value, receipt, and dirty projection marker together.
An alarm projects that committed value to KV. Failed projection keeps the marker for redrive.

Readers use KV and never call the Durable Object.

KV changes may take 60 seconds or more to reach another location.
The observed old value in an attempt may be stale. Climb validation uses the DO's authoritative position.
Use deployment settings or a stronger control path for kill switches and safety stops.

The explicit KV ledger fallback keeps immutable attempt and outcome keys.
It refuses authoritative flips and evidence writes with `FlagAtomicityRequired` by default.
A composition can opt in with `authoritativeWrites: "accept-non-atomic-unserialized"`.

That option accepts the absence of atomic commit and cross-isolate serialization.
Writes to the same KV key can hit its one-write-per-second limit.

The crash-recovery proof uses a persisted service double.
Native workerd transaction and alarm behavior still needs provider qualification.
The operator ledger is not wired into the deployed Stack.

The lifecycle journal is scoped memory, with no durable state between processes.

## How to check

1. Run `pnpm --filter @rat-stack/flags test` for rollout properties, generated write histories, audit failures, and lifecycle histories.
2. Run `pnpm --filter @rat-stack/core exec vitest run test/patterns-rule.test.ts` for the removal-date [fence](/lore/the-fence).
3. Run `pnpm turbo run check test build --concurrency=1` for the full gate.
4. Inspect the deployment plan. Readers declare one KV namespace. The operator [layer](/lore/layers-make-dependencies-explicit) adds the ledger DO and its KV write [binding](/lore/bindings).
5. Follow [Add a feature flag](/skills/add-a-feature-flag) for scoped evidence, authority, and crash-redrive checks.

To remove the cartridge:

1. Replace `apps/site/src/flags.ts` with core imports.
2. Export `flagsLayer = Flags.defaults(eventFlags)` and `liveFlagsLayer = flagsLayer`.
3. Remove the package dependency and its directory.

Callers keep their typed defaults.
The CLI retains its named read-only failure.

## Sources

1. [Flags cartridge](https://github.com/joelhooks/rat-stack/tree/main/packages/flags)
   rat-stack. Evaluation, adapters, audit journal, lifecycle, and behavior tests. Accessed 2026-10-11.

2. [How KV works](https://developers.cloudflare.com/kv/concepts/how-kv-works/)
   Cloudflare. Eventual consistency, cached missing keys, and no atomic transactions. Accessed 2026-10-11.

3. [Workers KV limits](https://developers.cloudflare.com/kv/platform/limits/)
   Cloudflare. One write per second to each key. Accessed 2026-10-11.

## Lore on this page

- [Flags climb on evidence](/lore/flags-climb-on-evidence)
- [Workers answer requests; Durable Objects own named state](/lore/workers-answer-requests-durable-objects-own-named-state)
- [Scopes release resources when work ends](/lore/scopes-own-resources)
- [Dead letters need a return path](/lore/dead-letters-need-a-return-path)
- [A cartridge owns one job and its resources](/lore/cartridges)

## Linked from

- add-a-feature-flag → Declare a typed feature flag, its scoped evidence ladder, approval roles, removal date, and durable ledger adapter. → [Read page](https://ratstack.sh/skills/add-a-feature-flag)

- Agent guide → An Effect stack so pure (aspirational) Kit Langton will blush. → [Read page](https://ratstack.sh/llms.txt)

- Change log → What changed in the files served here, newest first. → [Read page](https://ratstack.sh/log)

- Durability → Seven durable Effect patterns, each with its seam, its fence, and the incident that taught it. → [Read page](https://ratstack.sh/systems/durability)

- Flags climb on evidence → A flag ladder connects each rollout step to scoped measurements, approval, and a durable receipt. → [Read page](https://ratstack.sh/lore/flags-climb-on-evidence)

- Full agent guide → An Effect stack so pure (aspirational) Kit Langton will blush. → [Read page](https://ratstack.sh/llms-full.txt)

- Learn the stack | rat-stack → Hands-on guides to Effect actions, XState lifecycles, and the seams between stack pieces. → [Read page](https://ratstack.sh/skills)

- Rat Stack systems | rat-stack → The systems rat-stack ships, the standard each keeps, and how to check it. → [Read page](https://ratstack.sh/systems)

- Source change history (log.md) → The generated change log as Markdown. → [Read page](https://ratstack.sh/log.md)
