Skip to content
File

Blob: references/authority-and-state.md

Markdown86 lines

Authority and state

Start with a fact and the operation that changes it. Who can settle a disagreement about that fact? What must still be true when the operation takes effect? Which other state can change independently?

“The database owns state” is often too broad. One row can contain authoritative identity fields and copied configuration fields. A controller can hold all the variables while callers still make its decisions through combinations of setters. The useful boundary owns the decision and enforces its conditions.

Separate identity, admission, and permission

anvil, a CI application, uses tessera as an identity provider. Rachel described the division directly:

tessera only manages identities, authorization is still handled by anvil

The provider authenticates a person and supplies a stable subject identifier. anvil decides whether to create a local account for that identity, whether the account is disabled, and which projects it owns. Successful sign-in answers who is calling; it does not grant access to another person's CI projects.

The identity binding also has a continuing meaning. anvil resolves an already-bound provider subject before considering an email match. A changed email can update the bound user's profile when it does not collide with another account; it cannot silently move that subject onto another local account. Verified email can link a previously unknown subject to an unbound legacy account during migration. An account already bound to another subject produces a conflict. Database constraints make the subject unique and allow only one binding per local user, so concurrent attempts cannot both win merely because their initial lookups found no binding.

The key follows the identity domain. A subject from one configured issuer can identify an account there; a service accepting several issuers must distinguish those namespaces too.

Keep the decision valid through its effect

An accurate read can become stale before a write. The enforcement mechanism must cover the interval in which another participant could invalidate the condition.

Specter distributes key-value storage across nodes that own intervals in a ring. A route to a node can become obsolete while membership or a key interval is moving. The receiving handler therefore rechecks active membership and the predecessor interval, holds the relevant ownership read locks through local KV execution, and returns ErrKVStaleOwnership when the route no longer agrees with local ownership. Releasing those locks immediately after checking would leave a gap in which the node could lose the key before operating on it. The named outcome also distinguishes an obsolete route from an ordinary result of the KV operation.

anvil applies the same idea to project configuration. Its stateless request Worker checks project ownership in D1, a shared SQL database, then sends a configuration command to ProjectDO: a per-project Cloudflare Durable Object acting as a stateful owner with its own SQL storage. Repository configuration and webhook definitions live together there. ProjectDO checks that the proposed repository URL is compatible with the configured webhooks inside the transaction that changes the configuration, then returns an applied or rejected outcome. A Worker deciding compatibility from copied D1 fields before making that call would be deciding against a possibly older configuration. The local ownership check and the configuration transaction answer different questions; neither replaces the other.

git-on-cloudflare stores Git objects in pack files in object storage. A per-repository actor owns the catalog that determines which packs are active. Compaction rewrites several packs into a replacement, so its expensive work runs outside that actor against a catalog snapshot obtained with a compaction lease. When the result returns, the actor checks that the lease still matches, no receive is active, the catalog version is unchanged, and the source rows still describe the same active packs. One of those checks is:

const currentPacksetVersion = (await store.get("packsetVersion")) || 0;
if (currentPacksetVersion !== args.packsetVersion) {
  await store.delete("compactLease");
  return {
    status: "retry",
    reason: "packset-changed",
    message: "The active pack catalog changed before compaction could commit.",
  };
}

A finished calculation is a proposal based on particular inputs. Acceptance belongs where those inputs can be checked against current state. This allows expensive work to happen elsewhere without giving it authority to overwrite intervening changes.

Give derived state an owner and a refresh path

A projection is a useful read shape derived from another source. Its value comes partly from allowing readers to avoid repeating expensive work. Its design needs a clear answer to how it catches up.

anvil's D1 project index lets a user list projects without querying every ProjectDO. Its project identity and owner fields are authoritative for authorization, while fields such as repository URL, default branch, and configuration path are copies of ProjectDO configuration. Calling the whole D1 row either canonical or disposable would obscure this split.

A ProjectDO configuration transaction records projectIndexSyncStatus: "needs_update" and arranges an alarm, a persisted scheduled callback on the object. The request can return the configuration accepted by ProjectDO immediately. The alarm later reads that configuration and updates the copied D1 fields. Success clears the pending status; failure retains the obligation and records a later retry time. This is a local change followed by recoverable publication into a read index, with a period in which the index can lag. It does not require the request Worker to coordinate a transaction across both databases.

In the earlier t networking overlay, a server gossiped a serialized view of its connected clients to other servers. The consumer needed the latest published view, not a history of every serialization. Client events rebuilt one atomic.Value, replacing a cache keyed by checksums of past client sets. That removed historical entries without removing anything the reader used. The published bytes were a derived snapshot; an event still awaiting the background rebuild could remain absent from them.

Choose freshness according to the use. A list view may tolerate a pending refresh. A command that must respect a newly revoked permission needs current authority at its admission boundary.

Separate independent lifetimes

Vaskel, a communication application, supplied a useful diagnostic during work on its client state:

If fixing one state requires adding another negated condition to an existing Boolean expression, ask whether you're encoding a finite-state machine accidentally.

Follow that cue by identifying the actual alternatives. A message draft can be in authoring, submitting, retained after an uncertain attempt, or cleaning up after successful Send. The stored command includes the identity and payload needed to retry the same Send. It remains present after success until local draft cleanup finishes, so testing only whether an attempt exists cannot distinguish unknown outcome from accepted message. The cleanup branch makes that distinction explicit:

| {
    phase: "cleanup";
    record: DraftRecord & { attempt: SendMessage };
    outcome: "sent";
  }

The controller chooses fresh submission, retry, or cleanup from the phase. It preserves the exact command for uncertain retries and does not reopen submission when deletion of a successfully sent local draft fails. Persistence progress and connectivity remain separate dimensions: a connected client can still have unavailable draft storage, and a stored draft can outlive a network connection.

Other state should remain independent. A paginated activity view can have both earlier and later pages available; those are not exclusive modes. Someone can already be participating in a media room while microphone capture is pending or transport is reconnecting. A loaded workspace section can be useful while another section is still loading. Combining these facts into one exclusive phase would erase valid combinations or impose waiting that the product does not require. The useful state machine excludes impossible combinations while preserving independent lifetimes.

Choose the agreement the product needs

One decision owner is useful when an operation needs an immediate, settled answer. Independently writable replicas need another model. tres hosts files, text pastes, and shortened links behind public IDs or chosen path slugs. Its Cloudflare backend and Go backend each accept writes into their own database, then pull the other's ordered outbox of change events. A successful local create can therefore precede knowledge that the other backend accepted different content under the same ID.

Both replicas settle a same-ID create with the same rule: the earlier created_at wins, with go before cf when timestamps tie. A receiver replaces its local payload if the incoming create wins, or ignores the incoming loser, and advances the replication cursor. Applying replicated work emits no new outbox event. Each peer can consume the other's original create and reach the same winner without a new round of echoed changes.

Deletion has stronger semantics than losing that comparison. A tombstone permanently consumes the ID; a later create under it cannot reinstate content. Discarding a conflicting create must therefore never emit a tombstone for the shared ID. Such a tombstone names the ID alone, not the losing payload or origin, and would delete the winning content too. Cleaning up a losing copy and deciding that nobody may use the ID are different operations.

These choices serve different promises. Allowing either disconnected deployment to accept a chosen slug can work with later deterministic resolution, provided local success is not presented as an irrevocable global claim. A promise that the caller has permanently secured a globally unique slug at acceptance requires agreement before success. The conflict rule cannot supply that stronger promise after the fact.

For interrupted transitions and retries, continue with failure and recovery. For representing these distinctions in code, use representation and API craft.