Blob: references/failure-and-recovery.md
Failure and recovery
Follow an operation far enough to distinguish durable acceptance, external execution, acknowledgement, and local cleanup. A lost response can leave the effect committed. A committed row can leave external work unfinished. Recovery depends on knowing which of these facts survived.
The first decision is the product's promise. Prevent the consequence that would break it, and use existing receipts, leases, replay, expiry, or operator procedures for the remaining work.
Enforce the consequence where it is observable
Vaskel is a communication app in which one account can move its room participation between devices. An account actor owns the current participation generation, a room actor coordinates media, and listeners play tracks forwarded through a media service. For an explicit Move, Rachel accepted brief overlap provided listeners never saw or heard the same person twice. The replacement device should remain usable even when the predecessor device or its media resources fail to close promptly.
That makes current generation and playback selection the important boundaries. The account accepts a replacement generation without awaiting predecessor disposal. Room snapshots expose the current generation, and each listener disables and detaches old-generation playback before playing the replacement. Late tracks or responses cannot restore the retired playback. Different listeners can switch at different times while each plays at most one generation. Account-generation checks and participant lease expiry eventually retire missed predecessor resources.
This separates logical replacement from physical teardown. It avoids making progress depend on an obsolete device while preserving the actual listening experience.
Deliberate Leave, moderation removal, and permission revocation have a different purpose: forwarding must stop and participation intent must end. After an operational failure, the account can retain the identifier of the interrupted participation and the user's intent to continue it through an explicit Resume. A deliberate end cancels that inherited intent. Before admitting a resumed session, the system must establish that the predecessor can no longer forward and resolve whether its termination still permits continuation. A delayed response or recovery must not silently bring someone back after Leave, and an explicit transfer cannot override a pending deliberate Leave.
A timeout waiting for teardown proves neither that forwarding stopped nor that an ended participation became resumable. Vaskel therefore retains stronger closure barriers for these operations than for disposing of an explicitly transferred predecessor. The useful distinction is the consequence being promised: continued participation on a replacement device versus stopped participation and canceled intent.
Preserve the identity of uncertain work
A retry of an operation whose result is unknown should describe the same operation. Preserve its command ID, issue time, and payload.
Vaskel's message owner is the actor that stores a room's or conversation's messages and decides whether the caller may change them. It checks current access and command age, then looks for a receipt keyed by user, operation, and command ID. A matching payload hash returns the previous result; reusing the ID with different work produces command_conflict. The message mutation and receipt are written in the same owning transaction. Thus a lost response can be recovered without creating another message, while a receipt does not become perpetual authority to act after access or the retry window has expired.
The client persists the attempt before sending when persistent drafts are available. After success, it enters a distinct cleanup phase. Its failure path includes:
if (!this.active || this.state.phase === "cleanup") return;That small condition has a specific meaning: failing to delete a local draft after a successful Send cannot reopen submission. The original command is retained for uncertain retries; success changes what recovery is allowed to do.
A command receipt establishes acceptance at that owner. It does not say every recipient received the message or a push alert. Failed broadcasts can be recovered through message replay; push alerts have a weaker delivery contract. The command-age check also prevents an old attempt from becoming fresh work after its receipt has been compacted. Keeping these meanings separate makes acknowledgement useful without promising more than the owning transaction settled.
Leave enough state to recover
Flamemail stores email bodies in object storage and keeps inbox and message metadata in a database. Deleting an inbox must remove its stored mail and revoke access through existing sessions. It purges message objects and revokes sessions before deleting the metadata that names the inboxes:
await purgeEmailStorage(env.STORAGE, emailIds);
await Promise.all(targetInboxes.map((inbox) => revokeInboxSessionToken(env, inbox.fullAddress)));
await db.delete(inboxes).where(inArray(inboxes.id, inboxIds));If object deletion or session revocation fails, the database metadata still identifies the work to revisit. Removing that metadata first would discard the convenient record of which objects and sessions remain to be cleaned up. This ordering preserves recovery even though the stores cannot all participate in one transaction.
tessera's identity service chooses a different recovery cost for a single-use invitation. It validates the request, password bounds, and abuse check before conditionally consuming an unexpired, unused invite. Only the winning consumer attempts account signup. If signup then fails, the invite stays consumed and an operator issues another one. The design prevents competing consumers while accepting a burned invitation; it does not guarantee that consumption produces an account. Checking predictable failures first reduces avoidable reissuance. Automatic compensation becomes worthwhile when manual reissuance no longer satisfies the intended workflow, such as a promised unattended onboarding process.
For each interrupted sequence, identify the durable evidence of progress and the next valid action. Avoid deleting the only record needed to finish cleanup or using a generic retry to replay an effect that may already have happened.
Retry according to the effect
A retry-safe database transaction does not make the surrounding operation exactly once. RMC measured Minecraft-server usage for billing. Serializable transactions protected local usage increments, with bounded retries for serialization conflicts. A later reporting task read the aggregate and sent a set operation to the billing provider. Local accounting, publishing the reporting task, and the provider accepting the report were separate effects. Some increment wrappers also launched asynchronous work and logged failures, so returning from a wrapper did not establish that all increments had completed. Stronger local isolation answered one question about competing updates; it did not settle completion or replay across the whole billing path.
Mail sending exposes the same problem sharply: an error can occur after a recipient accepted a message. Blindly retrying the send can deliver another copy. Dermail's sending worker retained queue retry for recognized greylisting when no recipients had accepted the mail, but returned queue success for broad send failures and several later save or notification failures, logging them without automatic retry. That policy gives different treatment to known non-acceptance and uncertain or already-completed effects. It also accepts that some failures will not recover automatically; suppressing retry and writing a log do not themselves finish a failed send or save a sent copy.
tres replicates hosted files, pastes, and links between independent backends. Its blob replication supplies a separate failure mode: retry exhaustion that the scheduler cannot recognize. Content metadata can arrive at a replica before a file or paste's bytes, so the row remains pending and reads return 503 pending_replication. The Cloudflare backend's intended give-up branch leaves the row pending but clears its next retry deadline. The pending-row query also treats a null deadline as ready for work, which makes those supposedly exhausted rows eligible in later cycles. A counter or give-up branch does not enforce a bound unless the persisted terminal state agrees with the query selecting retries.
A blocked operation can preserve correctness
git-on-cloudflare keeps Git objects in packs and maintains an ordered catalog of active packs. Each received pack gets a sequence number; a compacted pack records the lowest and highest receive sequence among its sources. Active pack ranges must form a disjoint cover. Lookup visits packs by highest sequence first, with tier as a tiebreaker, and takes the first copy of an object it finds. This is an ordering rule for object representations and their pack locations, not a timestamp on Git content.
Compaction must preserve that ordering when replacing several catalog entries with one. Suppose it combined packs for receives 1, 3, 4, and 5 while leaving pack 2 active. The replacement would claim range [1, 5] and sort ahead of pack 2. A duplicate representation previously found in pack 2 before pack 1 could now be found in the replacement first. The planner therefore rejects a window if any unselected active pack, including one in another tier, overlaps its sequence interval. Adjacent entries within one tier are insufficient if another tier lies between them.
The automatic planner also limits a four-pack selection to 20,000 source objects and 16 MiB of source bytes. It prefers the oldest admissible window, but can skip an oversized initial import and compact a later closed window. For example, a large pack 1 need not prevent compacting small packs 2–5 when their interval contains no other active pack. If every closed window exceeds the budget, or no closed window exists, the planner reports blocked and leaves the existing packs readable. Retrying a stale catalog snapshot can help; repeatedly retrying an inadmissible selection cannot. Larger work would need a separately planned repack rather than silently expanding automatic maintenance beyond its budget.
tres has a different reason to preserve old state. Its independently writable Cloudflare and Go backends pull each other's ordered outbox events. The pull cursor acknowledges that the configured peer has durably processed all events through that sequence. Maintenance may remove an event only when it is older than 30 days and the peer has acknowledged it. A recent acknowledged event stays within the retention window; an old unacknowledged event stays until the peer catches up. Thirty days is consequently not a hard upper bound on outbox storage during a prolonged outage.
Deleting events advances a compaction watermark. A peer asking for history before that watermark receives sync_cursor_too_old and needs recovery or backfill, rather than an incomplete stream presented as complete. Blob garbage collection has a separate boundary: it can remove expired or deleted file bodies while retaining content rows and tombstones. Those records keep IDs consumed and preserve the conflict semantics described in authority and state. Failure to delete a body leaves its cleanup metadata available for a later attempt.
Progress, bounded work, and correctness are separate properties. State which one an automatic mechanism can provide and what happens when it reaches its limit.
Recovery can meet the experience without removing the cause
Composer combines live media into a composed output. On one audio input, missing Opus packets left holes in playback. Enabling forward error correction and packet-loss concealment let the receiver recover or synthesize audio for missing portions of the timeline. The recovery test required continuous decoded audio while keeping the same nonzero network loss count in both cases:
old.lost == 3 && recovered.lost == 3,
"recovery concealed the network loss counter"The output could become acceptable while the incoming packet omissions remained. Intentional silence also needed separate treatment so it would not be counted as lost packets. This preserves two useful facts: whether the listener gets continuous audio, and whether the transport still loses data. Recovery can finish at the accepted listening result without claiming prevention, while the unchanged counter remains an accurate starting point if another workload exceeds what concealment can cover.
See authority and state for the owner of each transition and change and validation for checks that exercise interrupted operations.