State, Identity, and the Cost of Uncertainty
One charge when the provider answers after the client has given up
A payment page that continues loading after you press Pay leaves you with an uncomfortable decision. Perhaps the browser lost its connection, or the payment provider is taking longer to respond. You refresh the page and find no confirmation in your order history. Should you try again? From what the browser shows, there is no reliable way to tell whether the first payment request reached the provider.
A Baodium customer faced that situation during a promotion. The customer selected a jacket, pressed Pay, and eventually tried again when the page failed to confirm the purchase. Checkout recorded one order, but the payment provider recorded two authorizations. The customer then saw two pending amounts on the card account, even though there had been only one intended purchase.
The payments engineers reconstructed the attempts. The provider had approved the first authorization, but the response never reached Checkout Service. Checkout treated the timeout as a failed payment, and the second click submitted a new authorization with a different identity. Nothing in Baodium’s database linked the two requests to one intended payment.
In Chapter 2, we estimated the resources an operation needs while it is running. Here the difficulty continues after the request has stopped waiting. The provider may have completed an action, and we still need to find out what happened before allowing another one.
Timeouts and Uncertain Payment Outcomes
A card authorization asks the provider to approve a payment and may reserve the customer’s funds. A later capture collects an authorized amount under the provider’s contract. The two pending amounts at Baodium represented authorizations, so the customer had not necessarily been charged twice. The duplicated reservations still needed correction.
The timeout had established only that Checkout Service did not receive a result within its deadline. It said nothing definitive about the provider’s decision. Marking the payment failed allowed another independent submission, which is how the second authorization happened.
After the incident, the team changed what checkout recorded and what the customer saw. An uncertain provider result became a pending operation that checkout could investigate. Instead of inviting the customer to pay again, the page displayed a payment-verification status and a reference that could be retrieved after a refresh.
The team also disabled the Pay button while a submission was in progress. That reduced accidental double clicks, although it did little for a browser refresh, a mobile client retry, or two tabs submitting at the same time. Checkout needed to recognize repeated requests at the server and decide whether they referred to an earlier operation or a genuinely new payment.
Idempotence and Operation Identity
An idempotent operation has the same intended effect when performed again. Think of a light switch with a dedicated On button. Pressing On twice leaves the light on. A button that toggles the light is different, because pressing it again changes the result.
Some application operations already have that property. Setting a shipping address to a particular value can be repeated without making a second address change. Adding money to a balance or authorizing a payment is different. Repeating either operation may create another financial effect.
For those operations, we need a way to recognize an earlier request. A numbered cheque offers a useful comparison. Two cheques for the same amount can represent two legitimate payments, but presenting the same cheque again should not create a second payment. Its number identifies the original instruction. A payment idempotency key plays a similar role, provided the receiving system records and enforces the identity.
At Baodium, checkout would assign one durable operation ID to the intended authorization. Repeated submissions of that authorization would retrieve the same operation, and attempts sent to the provider would reuse its provider idempotency key. A new refund, capture, or genuinely new authorization would receive a different operation identity.
Payment API and Durable State
Before changing the handler, the engineers agreed on what the client should receive. A request to authorize an order includes a payment-method reference and an idempotency key chosen for that intended submission. Checkout authenticates the caller, validates the order, and records the payment operation before contacting the provider.
POST /v1/orders/4471/payment-authorizations
Idempotency-Key: checkout-4471-authorization-1
{"payment_method_id":"pm_21"}
HTTP/1.1 202 Accepted
{"operation_id":"payop_783","status":"PENDING"}
The identifiers in this shortened HTTP example are illustrative. The operation IDs stored by Baodium use UUIDs as shown in the schema. The 202 Accepted response means that checkout has durably accepted responsibility for completing or resolving the operation. It does not promise that the provider approved the payment. The client can request GET /v1/payment-operations/payop_783 to retrieve the current status. A definitive decline and a pending outcome need different customer messages, and the API contract must describe both.
The application also needs more than one identifier. The order ID names the purchase. The payment operation ID names one intended authorization, capture, refund, or void. An individual provider attempt has its own record for diagnostics, while all attempts for the same intended action reuse the operation’s provider key. Later, when services publish events, a message ID identifies one event and lets consumers recognize redelivery. The identifiers are related, but none can replace the others.
The operation record needs enough information to repeat or reconcile the original request without rebuilding it from an order that might have changed. A stored amount, currency, payment-method token, provider account, and request fingerprint bind its identity to the business action.
CREATE TABLE payment_operations (
operation_id uuid PRIMARY KEY,
order_id bigint NOT NULL REFERENCES orders(id),
operation_type text NOT NULL,
idempotency_key text NOT NULL,
provider_account text NOT NULL,
provider_key text NOT NULL,
request_hash text NOT NULL,
amount_minor bigint NOT NULL CHECK (amount_minor >= 0),
currency char(3) NOT NULL,
payment_method_ref text NOT NULL,
status text NOT NULL,
provider_reference text,
created_at timestamptz NOT NULL DEFAULT now(),
UNIQUE (order_id, idempotency_key),
UNIQUE (provider_account, provider_key)
);In this simplified schema, amount_minor stores the amount in the currency’s smallest supported unit, such as cents for USD. The payment method is a provider reference, not a card number. The provider reference is unavailable until checkout receives or later retrieves evidence of the provider’s result. The durable local identity is already present before the external call begins.
A client that repeats an idempotency key with the same business parameters retrieves the recorded operation, subject to authorization checks. Reusing that key with a different amount, payment method, or other material parameter produces a conflict. Checkout computes request_hash from a documented canonical representation of those parameters. An attempt number or tracing header is excluded because it can change during a legitimate retry.
Caller Identity, Authorization, and State Authority
Knowing an operation ID establishes which payment we are discussing. It does not establish who may retrieve or change it. Consider a merchant employee who can review orders but is not permitted to issue refunds. If the employee obtains another person’s refund operation ID or idempotency key, the service must still refuse the unauthorized action.
An authenticated principal identifies the person or service making the request. Authorization determines whether that principal may perform the requested action on the specified resource. The payment operation’s identity supports retries. Authority determines which component may record the business outcome. These decisions meet in the same request, but they serve different purposes.
Checkout first validates the caller’s access to the order before returning an earlier operation or its status. Creating a refund requires an additional permission check for that payment and merchant. Payment Service owns the financial operation’s result, while the order-owning service commits the corresponding order transition under its state rules. A gateway’s successful token validation does not replace those checks.
The same distinction applies to deployment approvals. A pipeline may repeat a request under one operation ID, but that ID cannot authorize the pipeline to deploy an artifact it is no longer permitted to release. Chapter 4 develops identity propagation across services, and Chapter 11 returns to resource ownership and authorization boundaries.
Concurrent Submissions and Database Transactions
The operation record gives checkout a way to identify a retry. It also has to prevent two requests from creating different operations for the same unresolved payment. Imagine a customer double-clicking Pay while two handlers read the order at nearly the same moment. Both see an unpaid order. If each performs an ordinary check followed by an insert, both may create an authorization before either one sees the other’s write.
Checkout resolves that race inside a local database transaction. It locks the order row, checks its current payment operation and state, and either retrieves that operation or creates a permitted new one. The operation row and the order’s reference to it commit together. Every path that starts an authorization follows this procedure.
We also want the database to reject a second active authorization if a future code path fails to follow the intended procedure. The following partial unique index provides that safeguard for the operation states in this design.
CREATE UNIQUE INDEX one_active_authorization_per_order
ON payment_operations (order_id)
WHERE operation_type = 'authorize'
AND status IN (
'pending', 'reconciliation_pending',
'authorized', 'manual_review'
);An authorization with an unresolved outcome continues to block another independent authorization. After a definitive decline or a confirmed void, the business workflow may permit a new operation. Its state transition and the index predicate must agree with that policy. The database rule cannot, by itself, establish whether a customer’s second request is authorized or whether a provider has already processed the first one.
The local transaction commits before checkout calls the provider. Keeping it open during a remote request would occupy a database connection and an order-row lock throughout the provider’s response time. Chapters 1 and 2 showed how that kind of unnecessary occupancy can affect unrelated requests. Once the intent is committed, a worker or request handler can send the recorded details under the same provider key.
Conditional Updates and Transaction Isolation
The same concurrency problem appears in inventory. Suppose two customers try to reserve the last item. If two transactions read an available quantity of one and then independently write back zero, both customers might receive a reservation even though there is only one item.
For inventory kept in one PostgreSQL row, the condition can be part of the update.
UPDATE inventory
SET available = available - 1
WHERE sku = 'sku-9' AND available > 0
RETURNING available;The statement returns no row when no stock can be reserved. PostgreSQL rechecks the condition after conflicting row updates, preventing this statement from reducing the last unit below zero twice. Creating the reservation record must occur in the same transaction, so a failed insert can roll back the quantity change.
This is a conditional update. A related technique, optimistic concurrency control, includes an expected record version in the update condition. Both are useful when the invariant can be enforced on the records being changed.
More complicated invariants may involve several rows. At PostgreSQL’s usual READ COMMITTED isolation level, two transactions can each observe a valid state and then make changes that violate a rule when considered together. Suitable row locks, database constraints, or SERIALIZABLE transactions may be needed. A serialization failure requires retrying the local transaction, without issuing a new external payment.1
Provider Idempotency and Recovery Contracts
Even a correctly committed local intent cannot make an external provider part of Baodium’s database transaction. A caller might send the request, lose the response, and still be unable to establish whether the provider approved it. Reusing the provider key is safe only under that provider’s idempotency contract.
The payments engineers checked the key’s scope, the required request parameters, its retention period, and the provider’s behavior when two requests using the same key arrive concurrently. They also established how checkout could retrieve an outcome after a timeout. Some providers allow lookup by payment reference or key. Others require another request using the original key, and overlapping attempts may return a conflict or in-progress response.
A retry must use the original provider account, operation type, and material parameters. If the provider reports that the request is still being processed, checkout waits and checks again. Inventing a new key would risk creating another authorization. The recovery policy also needs a deadline for cases that the provider cannot resolve automatically.
Retention matters. Suppose Baodium retains its operation record for fourteen days, but the provider recognizes idempotency keys for only seven. On day eight, checkout can retrieve the original key locally, although the provider may treat a new submission as a different payment. The old key is no longer sufficient evidence that a retry cannot create another authorization. Recovery may need a provider payment lookup, transaction report, or manual investigation instead. The actual period must come from the provider’s documented behavior.
Persisting Results and Guarding Order State
When the provider confirms an authorization, checkout needs to record that result against the original operation. A definitive decline also has a final outcome. The difficult cases occur when processing stops between two systems. Table Table compares the evidence available after an interruption.
The middle two cases are indistinguishable to a recovery worker that finds only a pending local operation. A submitted flag does not solve this. A process may stop immediately before sending a request or immediately afterward, with no reliable local evidence of whether the provider received it. Checkout needs the provider’s recovery mechanism rather than an inference from a local flag.
The order and payment operation have different responsibilities. The operation records the outcome of one authorization. The order also needs to account for inventory, fulfillment, cancellation, and later payment actions. The states in Figure Figure describe the payment portion of that workflow.
Consider a delayed provider response arriving after a customer has canceled the purchase or chosen another payment method. A recovery worker cannot use the order ID alone to apply that response. It must confirm that the order still refers to the same payment operation and has not changed since the worker read it.
UPDATE orders
SET state = 'PAYMENT_AUTHORIZED',
provider_authorization_id = $1,
version = version + 1,
updated_at = CURRENT_TIMESTAMP
WHERE order_id = $2
AND payment_operation_id = $3
AND version = $4
AND state IN (
'PENDING_PAYMENT', 'RECONCILIATION_PENDING'
);The numbered parameters represent values supplied by the database client through a prepared statement. A successful update changes one row. If it changes none, checkout reloads the order and operation rather than forcing the result into an order that may have advanced. Another handler might already have recorded the same outcome, or the late result might require cancellation recovery.
The payment-operation result and the matching order transition commit in one local transaction. If the order was canceled while authorization was in progress, the provider result is still recorded, but normal checkout does not resume. A confirmed authorization may instead require a void. That corrective action gets its own identity and recovery record.
Reconciliation Workers, Leases, and Fencing
A customer should not have to keep a browser open while checkout resolves an uncertain payment. Background workers can examine unresolved operations, query the provider, and save confirmed outcomes. They also need to find operations abandoned by a process crash, even when no exception handler had an opportunity to mark them for recovery.
Two workers might discover the same operation. To reduce overlap, a worker takes a time-limited lease on the record. Think of reserving a meeting room for a particular interval. Another team can book it after that interval ends. The expiry is useful if the first worker stops responding, but the original worker might resume after its lease expires.
The recovery record therefore needs a lease owner and a monotonically increasing fencing token. Each new claim advances that token. Updates from an earlier claimant are rejected because its token no longer matches the current one. We add the required fields to the operation table.
ALTER TABLE payment_operations
ADD COLUMN next_check_at timestamptz NOT NULL DEFAULT now(),
ADD COLUMN lease_owner uuid,
ADD COLUMN lease_expires_at timestamptz,
ADD COLUMN lease_version bigint NOT NULL DEFAULT 0;WITH available AS (
SELECT operation_id
FROM payment_operations
WHERE status IN ('pending', 'reconciliation_pending')
AND next_check_at <= now()
AND (lease_expires_at IS NULL OR lease_expires_at < now())
ORDER BY next_check_at
LIMIT 10
FOR UPDATE SKIP LOCKED
)
UPDATE payment_operations AS p
SET lease_owner = $1,
lease_expires_at = now() + interval '60 seconds',
lease_version = p.lease_version + 1
FROM available
WHERE p.operation_id = available.operation_id
RETURNING p.operation_id, p.lease_version;The claim uses a worker UUID as its first parameter. Recovery updates check that UUID, the returned lease version, and the unexpired lease in the database before changing the operation. If a paused worker resumes after another has claimed the record, its old version cannot overwrite the newer worker’s decision.
The database clock supplies the lease expiry for that local claim. Even so, an expired lease cannot cancel a payment request already running at the external provider. Both workers may have reached the provider, so they must use the same payment operation and provider key. Fencing protects local state transitions. Provider idempotency and reconciliation protect the external action.
Workers claim only as many operations as they can process before renewal or expiry. A large batch processed serially may lose its leases before the last records are reached. Provider notifications, synchronous responses, and recovery workers all use the same guarded result-recording procedure. A notification is authenticated and matched to the original provider account and operation before it can change payment state.
Compensation and Multi-Service Transactions
Even after we establish what the provider did, checkout may still need to correct it. A payment could be authorized while inventory subsequently rejects the reservation. Baodium cannot roll back the provider’s authorization by rolling back its own database transaction. It needs a new operation that asks the provider to cancel the authorization.
An action that counteracts an earlier confirmed action is called compensation. Travel booking provides another example. A booking service may reserve a flight and hotel, then discover that the requested rental car is unavailable. Canceling the flight is a second operation with its own possible failures. It cannot erase the airline’s original record.
The business effect determines the available correction. An uncaptured payment authorization may be voided under the provider’s rules. A captured payment may require a refund. Inventory reservations can be released while they are still valid, and a shipment can be canceled only before the carrier passes the relevant cutoff. An email already delivered cannot be recalled. These policies need agreement from the business owner, because two technically available corrections may have very different customer consequences.
When Baodium needed to void an authorization, checkout created a new void operation, linked it to the original authorization, and placed the order in COMPENSATION_PENDING . Both changes committed locally before the worker contacted the provider. The void reused its own stable key during retries. A lost void response left a second unresolved operation. A definitive refusal entered COMPENSATION_FAILED and required an operator rather than pretending the order was fully corrected.
A sequence of durable local transactions across services, with corrective operations for completed steps, is called a saga. The term comes from research on long-running database transactions.2 A saga record tracks completed steps, unresolved actions, and compensation still required. It is useful for bookings, fulfillment, account provisioning, and other workflows that cross transactional boundaries.
A workflow engine such as Temporal or AWS Step Functions can persist the workflow’s progress and arrange retries or compensation steps. The team still has to decide which actions may be repeated, which provider outcomes need reconciliation, and what the business permits after partial completion. Moving the workflow into an engine does not change those requirements.
Event Publication and the Transactional Outbox
There is another failure boundary in checkout. After committing an order transition, Order Service may need to publish an event so that Inventory, Notification Service, or another consumer can respond. If the database commits and the process crashes before publishing, those consumers may never learn about the change. Publishing first creates the opposite risk: the broker accepts an event for an order transition that later rolls back.
This is the dual-write problem. The application’s database and the message broker do not normally participate in one atomic transaction. Baodium used a transactional outbox to connect the two.
The name is a useful everyday analogy. In an office, someone can finish a letter and place it in an outgoing tray. Another person collects and sends the letters later. If the first person leaves, the letter is still waiting to be sent. Order Service follows the same pattern by committing the business change and a pending event record in its own database. A relay publishes committed outbox records to the broker.
with db.transaction():
changed = orders.advance(
order_id, expected_version, next_state)
if not changed:
raise ConcurrentOrderUpdate(order_id)
outbox.insert(
message_id=event_id,
order_id=order_id,
event_type=event_type,
payload=payload,
)Both repository calls use the same database transaction. If the order transition fails, the event insert rolls back with it. If the transaction commits and the process crashes, the outbox row is available to a relay when processing resumes.
The relay publishes each record with its original message ID and marks it published after the broker acknowledges receipt. It can crash between those two steps and publish the same event again. The outbox therefore provides durable publication with possible duplicates, which consumers must recognize. A relay can poll the outbox table or read committed changes through a tool such as Debezium.
For a consumer whose business update uses the same local database as its deduplication marker, the marker and business update can commit together.
with db.transaction():
first = processed_events.try_insert(
consumer="inventory", message_id=event.message_id)
if first:
inventory.apply_reservation(event)
broker.acknowledge(event)The marker has a uniqueness constraint for the consumer and message ID. If the transaction rolls back, neither the marker nor its local effect is durable, so redelivery can try again. If the transaction commits and the broker acknowledgment is lost, the next delivery finds the marker and does not repeat the update. The consumer still needs a business rule for two different messages requesting the same reservation, and markers must be retained for the supported replay period.
Kafka’s exactly-once features can coordinate certain Kafka input and output operations under Kafka transactions. They do not turn updates to an unrelated database or payment provider into the same atomic operation. Chapter 12 examines event delivery, offsets, ordering, and replay in detail.
Recovery Evidence and Failure Testing
Recovery workers may run for weeks without encountering a difficult case. That can make an untested recovery procedure look dependable until a provider interruption leaves real customers waiting. Baodium therefore measured unresolved operations directly from durable records, including the age of the oldest unresolved payment and the rate at which recovery completed those operations.
The age matters because a stable number of pending operations can conceal one customer payment that has waited far beyond the expected recovery time. After an outage, the engineers also compared new unresolved operations with completed reconciliations to determine whether the backlog was getting smaller.
The payments team compared records in both directions. Starting from Baodium’s operation table found unresolved local attempts. Starting from provider transaction reports found authorizations without a matching local result, including those whose original responses had been lost. Checking only provider references already stored locally would miss some of the most important cases.
Before releasing the new workflow, the team deliberately interrupted it after the local intent committed, after the provider accepted the request, and after the local result committed. It also submitted duplicates concurrently, delayed provider responses, expired worker leases, and redelivered outbox events. For each test, the engineers inspected local state and the provider’s recorded effects. A successful HTTP response at the end of a test could not establish that no duplicate authorization had occurred.
Support staff received a status view backed by the same operation records. An operator retry used the existing operation identity and the provider’s actual recovery contract. Replacing a payment required a confirmed earlier outcome and a recorded reason permitted by the order workflow.
Versioned Deployment Authorization
The same design decisions appear outside payment processing. Imagine a Jenkins pipeline submitting a production change to a validation service. The service evaluates the request, but Jenkins loses the response. Before Jenkins retries, an administrator publishes a new deployment policy.
The validator now needs to do two things. A repeated submission should retrieve the decision already made under the original request identity. At deployment time, however, the enforcement service must check whether that decision is still valid under the current policy. Returning an older ALLOW result does not grant permanent permission to deploy.
The change ID identifies the proposed deployment and its target. A request key identifies a repeatable evaluation submission, and an evaluation ID records the decision under a particular policy revision. The evaluation includes its input digest, revision, decision, and evidence. When Jira is unavailable and an approval cannot be verified, the service may record INDETERMINATE and decline to authorize execution until it can obtain the required evidence.
CREATE TABLE policy_revision (
revision bigint PRIMARY KEY,
body_sha256 text NOT NULL,
published_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE change_evaluation (
evaluation_id uuid PRIMARY KEY,
change_id uuid NOT NULL,
request_key text NOT NULL,
input_sha256 text NOT NULL,
policy_revision bigint NOT NULL
REFERENCES policy_revision(revision),
decision text NOT NULL CHECK (
decision IN ('ALLOW', 'DENY', 'INDETERMINATE')),
UNIQUE (change_id, request_key)
);The unique key prevents two evaluations from being recorded under one submission identity. On a repeated request, the validator compares the stored input digest before returning the earlier result. The deployment controller separately verifies the artifact, target, caller’s permission, policy revision, and validity period when execution is authorized. Appendix B develops this architecture and its recovery cases.
A booking quote that expires, a cloud account whose policy changes, and a bank transfer awaiting renewed risk approval introduce similar concerns. Operation identity preserves the history of an earlier decision. Execution still depends on the current authority and business state.
Summary
The customer who pressed Pay twice had intended one purchase. Baodium’s first implementation could not recognize that intention after the provider response was lost, and the second submission created another authorization. The revised workflow recorded the payment before sending it, reused its identity during recovery, and required provider evidence before changing an unresolved result.
That decision led to the other parts of the design. Concurrent requests needed guarded database transitions. Partial checkout required corrective operations that could themselves fail. Events needed durable publication, while recovery workers needed a way to avoid overwriting newer results. Each mechanism addressed a place where one system could finish an action without another system receiving reliable evidence of it.
We encounter the same uncertainty when confirming a booking, provisioning a cloud resource, or authorizing a deployment. Once an operation continues across services, the design needs a durable way to retrieve its progress and a policy for deciding what may happen next. Chapter 4 examines the communication paths that create these situations, including deadlines, cancellation, retries, and overloaded dependencies.
After this chapter
⌘/Ctrl K to search