Partial Failure, Ordering, and Eventual Consistency
Understand partial API failures, message ordering, and eventual consistency, then design status models and recovery paths clients can reason about.
A checkout can commit work even when its response times out, and a read model can lag behind the source of truth. Model operations as accepted, processing, completed, failed, or compensating; expose a status endpoint and reconcile ambiguous outcomes before retrying effects. The examples also cover per-entity ordering and recovery-capacity estimates.
Partial Failure, Ordering, and Eventual Consistency
Introduction
A checkout request can reach the server, reserve inventory, and then time out before the response reaches the browser. The client cannot tell whether the server did nothing or committed work. A blind retry may create a second workflow.
POST /checkouts
Idempotency-Key: checkout-123
A stable key lets the service recognize a replay, but the client still needs a way to check whether the operation is pending, complete, or being compensated. This guide covers operation status, per-entity ordering, and recovery from delayed or missing updates.
Model the outcome explicitly
Return acceptance separately from completion when work continues asynchronously. A response can give the caller a stable operation ID and status URL:
{
"operationId": "op_7f32",
"status": "accepted",
"statusUrl": "/operations/op_7f32"
}
Define each state in the API contract. accepted means the service recorded the request; processing means work is underway; completed and failed are terminal outcomes; compensating means the service is undoing an earlier step. Poll the status resource with bounded intervals or send a notification. Include a version or update time so clients can detect stale status. Return completed only after the operation’s promised effects are confirmed.
stateDiagram-v2
[*] --> Accepted: request recorded
Accepted --> Processing: worker starts
Processing --> Processing: retryable step error, retry within policy
Processing --> Completed: required effects confirmed
Processing --> Failed: terminal failure, nothing to undo
Processing --> Compensating: terminal failure, earlier effects need undo
Compensating --> Compensating: retryable compensation error or repair pending
Compensating --> Failed: compensation confirmed, workflow ends
Completed --> [*]
Failed --> [*]
Here, accepted and processing are nonterminal. Retryable step failures stay in processing while the retry policy allows another attempt. completed and failed are terminal. If compensation still needs work, keep the operation in compensating, including when an operator must repair it; mark it failed only after no compensation remains outstanding.
Checkout request with a lost response
The API records an operation before returning 202 Accepted with an ID and status URL. HTTP defines 202 as accepted for processing, not completed; the response representation should describe the current status and point to a status monitor. See RFC 9110, Section 15.3.3. If that response is lost, the client retries POST /checkouts with the same idempotency key. This API returns the existing operation instead of creating another checkout.
GET /operations/op_7f32
{
"operationId": "op_7f32",
"status": "processing",
"version": 3,
"statusUrl": "/operations/op_7f32"
}
The checkout worker reserved inventory, but the payment result was not recorded before the connection failed. The reconciliation job checks the inventory reservation and, where available, queries payment by its provider reference. If payment succeeded, it records completed. If payment was declined, it enters compensating, releases the reservation, then records failed. A retryable lookup or release error leaves the operation in processing or compensating; the status endpoint reports that state while retries or operator repair continue. If payment status is still unknown, do not blindly send a new charge. When the provider documents idempotency keys, reuse the same stable provider key for the retry; otherwise keep the operation in processing for reconciliation or operator review. See API idempotency and safe replays for the replay boundary.
When to use eventual consistency
It fits workflows where independent services own their data, where read models can lag briefly, or where asynchronous processing protects availability. It is a poor fit for an invariant that must be checked atomically, such as preventing a bank account from spending the same balance twice. Keep strong consistency for the narrow operation that protects the invariant, then distribute resulting events afterward.
| Approach | Latency | Availability | Stale-read behavior | Complexity | Recovery |
|---|---|---|---|---|---|
| Strongly consistent operation | Higher when coordination is required | A participant or quorum failure can block writes | Reads reflect committed writes within the consistency boundary | Coordination and contention | Retry the operation safely; resolve failures inside its transaction boundary |
| Eventual consistency | Lower for accepted asynchronous work | Services can accept work while another service is unavailable | Read models can lag; expose versions or freshness | Pending states, ordering, and reconciliation | Replay or reconcile missed updates |
| Bounded retry | Adds delay while waiting for a dependency | Preserves the workflow if the dependency recovers | Existing projections may remain stale during retries | Retry limits, backoff, and idempotency | Retry while the step is still valid; stop at a defined limit |
| Saga compensation | Adds time for compensating steps to complete | Other participants can continue independently | Intermediate effects remain visible until compensation finishes | Each compensation needs its own state and failure handling | Apply a new business action, then reconcile or route failures for repair |
Compensation is not rollback
In a workflow spanning several services, a later failure cannot usually undo earlier commits with one database rollback. A saga handles this by issuing compensating actions, such as releasing a reservation after payment fails. Compensation is a new business operation: it can fail, take time, or produce a result that differs from the original state. For example, a refund may reverse a charge, but it does not erase the charge from the ledger.
Choose between retrying the failed step and compensating based on the business rule. If the dependency may recover and the action remains valid, retry with a bounded policy. If the workflow can no longer continue, run an explicit compensation. Make each step and compensation safe to repeat, record its outcome, and expose intermediate states such as compensating or compensation_failed through the operation status API. Provide a manual repair path for cases where compensation itself cannot complete.
flowchart TD
A[Partial failure leaves some steps committed] --> B[Persist operation as pending]
B --> C{Can the failed step still complete?}
C -->|Yes| D[Retry the idempotent step within its limit]
D --> E{Did the retry succeed?}
E -->|Yes| F[Resume the workflow]
E -->|No| G[Compensate completed steps]
C -->|No| G
G --> H{Did compensation succeed?}
H -->|No| I[Queue operator repair]
F --> J[Reconcile authoritative state and projections]
H -->|Yes| J
I --> J
J --> K[Repair gaps and verify entity versions]
K --> L[Publish terminal status and projection freshness]
The reconciliation step checks the final state even when retries or compensation report success. That catches lost notifications and projections that missed an update.
Key takeaways
- Model compensation as a durable, repeatable operation, not an automatic rollback.
- Keep the original and compensating actions visible in the operation history.
- Decide whether to retry, compensate, or require operator repair for each failure point.
Implementation snippet: version check
A consumer can ignore stale events and flag a sequence gap for repair. The update and stored version should be atomic.
async function apply(event: AccountEvent): Promise<void> {
await db.transaction(async (tx) => {
const current = await tx.getVersion(event.accountId);
if (event.version <= current) return; // duplicate or stale
if (event.version !== current + 1)
throw new Error("sequence gap; retry or reconcile");
await tx.apply(event);
await tx.setVersion(event.accountId, event.version);
});
}
Production failures and mitigations
- The event is committed but the API response is lost. A retry can start a duplicate workflow unless the client reuses its idempotency key.
- A consumer crashes after updating its database but before acknowledging the message. Make the handler safe to replay.
- A projection lags while clients poll aggressively. Expose processing status and use bounded polling or notifications.
- A poison event blocks a strict-order partition. Quarantine it, alert, and define whether later events may proceed.
Reconciliation jobs should compare authoritative state with projections and repair gaps.
Observability checklist
- Measure end-to-end workflow duration and time spent in each state.
- Track consumer lag, retry counts, dead letters, and sequence gaps.
- Compare projection freshness with an explicit lag objective.
- Log operation IDs, entity versions, and event IDs across services.
- Alert on stuck nonterminal operations and reconciliation backlog.
Estimate recovery capacity
Size recovery work from measured arrival and processing rates rather than a generic target. For one example, assume an integration normally receives 100 events per second, processes only 80 per second while a dependency is degraded, and stays degraded for 30 minutes. The queue grows by (100 - 80) × 1,800 = 36,000 events.
If the recovered service can process 180 events per second while new work continues to arrive at 100 events per second, its net catch-up rate is 80 events per second. Draining 36,000 events then takes 36,000 ÷ 80 = 450 seconds, or 7.5 minutes. During that period, a projection behind this queue can remain stale; track its oldest event age and version lag so clients can distinguish stale reads from missing data.
Use effective throughput in the estimate. If retries, database limits, or rate caps reduce the recovery rate to 144 events per second, net catch-up is 44 per second and the same backlog takes about 13.6 minutes to clear. Include reconciliation records and retry attempts in the measured work rate, and reserve capacity for new traffic. Otherwise, catch-up can keep the queue from shrinking even after the dependency recovers.
Security and compliance notes
Authorize status lookups against the same tenant boundary as the original request. Do not expose internal event payloads through a public status endpoint. Validate event producer identity and schema. Keep enough operation and event history to support audit and reconciliation, while applying retention limits and redacting sensitive fields from logs and status responses.
Common pitfalls
Do not mark an accepted operation complete or return a stale projection without its freshness or version. Avoid claiming exactly-once business effects; make writes replay-safe and reconcile durable state. After a timeout, resolve the first attempt before retrying a non-idempotent side effect, because it may already have succeeded.
Quick recap checklist
- State which records are authoritative and which views may lag.
- Expose operation status when completion can take time or remain uncertain.
- Define ordering at the entity or partition level and use versions to detect stale events.
- Make consumers replay-safe and provide reconciliation for inconsistent state.
Interview questions
Further reading
- Event sourcing explains how to represent domain changes as an append-only event history.
- API idempotency and safe replays covers duplicate requests and replay-safe side effects.
- Retries, timeouts, backoff, and circuit breakers covers bounded retry behavior when dependencies fail.
- Microsoft Azure Architecture Center: Saga pattern. Workflow coordination and compensating transactions across services.
- Microsoft Azure Architecture Center: Event Sourcing. Event history, projections, and eventual consistency.
Conclusion
When a request times out, the operation may still be running. Expose its state, let the client check the same operation ID, and reconcile before declaring success or repeating a side effect.
Category
Related Posts
Ordering Guarantees in Distributed Messaging
Understand how message brokers provide ordering guarantees, from FIFO queues to causal ordering across partitions, and the trade-offs in distributed systems.
Event Envelopes and Metadata for Reliable EDA
Learn how event envelopes separate transport context from payload, apply CloudEvents attributes, propagate correlation IDs, and validate messages safely.
API Clients, Servers, and Network Boundaries Explained
Understand what API clients and servers each own, how network boundaries fail, and how timeouts, retries, and trust boundaries shape reliable integrations.