Service Communication and Cascading Failure
A child deadline and a permit on the fraud call
Imagine investigating a checkout service that has become painfully slow. Customer requests are timing out, the worker pool is almost full, and the queue of incoming requests continues to grow. Yet the CPU dashboard shows plenty of unused capacity. You might wonder whether adding more workers would solve the problem. Before doing that, we need to find out what the existing workers are waiting for.
Baodium encountered this situation a few weeks after integrating an external fraud-scoring provider. Every checkout required a risk decision before payment could begin. Order Service sent the assessment to Fraud Service, which collected the necessary inputs, contacted the provider, and returned an approval, denial, or manual-review decision.
When the integration was first released, the provider usually responded in less than a tenth of a second. Several weeks later, its response time increased to nearly two seconds. The provider was still returning valid decisions, so ordinary error-rate alerts showed little change. Meanwhile, checkout requests accumulated until Order Service had no available workers for new customers.
The engineers discovered that most workers were waiting for Fraud Service, which was itself waiting for the external provider. We saw in Chapter 1 how requests can spend more time acquiring a database connection than executing their queries. Here the waiting crossed multiple services, and each caller continued using resources while another system took longer to respond.
How a Slow Dependency Affects Its Callers
Consider one checkout during the incident. Order Service assigned a worker to the request, validated the cart, and called Fraud Service. Fraud Service acquired capacity from its provider client and submitted the assessment. Order Service then waited for Fraud Service, while Fraud Service waited for the provider.
Figure Figure shows the nested calls and the resources they occupied.
Order Service used a blocking request model, where a worker thread remained assigned to each checkout until the request completed. The worker consumed little CPU while waiting for a network response, but it could not serve another customer. As more requests waited, the available worker count fell even though the machines were doing relatively little computation.
Fraud Service had its own limit on concurrent provider requests. Once all those slots were occupied, additional assessments began waiting inside Fraud Service. Order Service workers continued waiting for their responses, including the time spent in that internal queue.
The team could estimate how serious the problem had become using the relationship from Chapter 2. One Order Service instance received about 200 checkouts per second. During the slowdown, each checkout spent approximately 2.05 seconds in the fraud-dependent portion of its request, including the processing around the provider call.
To sustain that arrival rate with blocking workers, the instance would need an average of
workers occupied by that portion of the request alone.
Its worker pool contained only 300. The calculation described the capacity required to keep up with incoming traffic, which the service could no longer do. Requests accumulated or timed out because completions could not match arrivals.
An asynchronous implementation would release its thread while waiting, although the requests would still consume memory and could occupy network connections, admission slots, or other resources. The failure would appear in different measurements. We would still need to limit how many operations were allowed to wait.
Finding the Source of the Delay
Adding workers was one of the first suggestions during the incident. It would give Order Service more room to accept checkout requests, but Fraud Service was already limiting its outgoing provider calls. Additional Order Service workers would spend more time waiting for the same constrained dependency.
The engineers examined a distributed trace from an affected checkout. Most of the request duration came from the Fraud Service call. Inside Fraud Service, they had separate measurements for acquiring a provider client slot and waiting for the provider response.
Those measurements were useful together. If slot-acquisition time increased while provider-call duration remained stable, the team would investigate additional callers, contention, and the local admission policy. Instead, provider-call duration had increased first. As those calls occupied the available slots for longer, acquisition time began increasing as well.
The provider slowdown explained the initial delay. The growing queues explained why the effect spread into Order Service.
The next decision was more difficult than increasing a worker count. Checkout needed a fraud decision before taking payment, but how long should it wait for that decision, and what should happen when the provider could no longer respond within the customer’s deadline?
Required Results and Work That Can Finish Later
Before changing timeouts or concurrency settings, the checkout team reviewed what a successful purchase required.
An order could be confirmed only after an acceptable fraud decision, a payment authorization, the required inventory reservation, and the order’s committed state. The original handler also waited for Notification Service to send the confirmation email.
The email was an unnecessary part of the synchronous checkout path. Once the purchase was committed, a delay in sending the receipt did not change whether the customer had placed an order. Returning an error because email delivery failed could encourage the customer to submit the purchase again.
Fraud evaluation was different. Baodium’s policy prohibited payment until the risk assessment produced an acceptable result. If that decision could not arrive before the checkout deadline, the service needed to defer the assessment or reject the request under a defined policy.
Table Table records the distinction for the main checkout dependencies.
The team removed notification delivery from the request path. When Order Service confirmed a purchase, it wrote an OrderConfirmed event to the transactional outbox introduced in Chapter 3. Notification Service could process that event afterward, including when its own dependencies were temporarily unavailable.
The fraud decision still had to precede payment. However, the customer’s HTTP request did not have to remain open while the assessment was completed. Checkout could record a durable pending operation, return its reference to the customer, and continue the assessment through a recovery worker.
That option came with responsibilities of its own. The application needed a status endpoint, an expiration policy, and enough recovery capacity to finish the assessments it accepted. The customer also needed an accurate message explaining that payment had not begun.
The same distinction affects calls we might run concurrently. Independent product-page lookups can often run together. A fraud decision and a payment authorization cannot be issued independently when payment requires prior risk approval. Concurrency can reduce waiting, but it cannot remove a dependency established by the business workflow.
Limiting Outbound Fraud Calls
Once checkout could defer an assessment, Order Service no longer needed to let every customer request wait for Fraud Service.
The engineers introduced a caller-side concurrency limit of 80 active fraud calls per Order Service instance. Before sending a request, a handler attempted to acquire a permit. If all permits were occupied, checkout retained the durable assessment and returned a pending result without calling Fraud Service.
A limit dedicated to one dependency is often called a bulkhead. The term comes from the compartments inside a ship, where a damaged compartment can be isolated from the others. For Order Service, the important effect was straightforward: fraud calls could no longer occupy every worker available for checkout and its other responsibilities.
The permit had to be acquired without waiting. If handlers queued indefinitely for a permit, Order Service would reproduce the original problem inside its own process. A request that could not start its fraud assessment promptly would be deferred instead.
Why Both Services Need Admission Limits
You might wonder why Order Service needed this control when Fraud Service already limited the number of evaluations it accepted.
Consider Fraud Service accepting connections while its processing threads are all busy. Its provider limit may protect the external provider, but callers can still accumulate while waiting to reach that limit. Order Service needs a restriction of its own because its workers and memory have their own capacity limits.
Fraud Service separately limits the evaluations it admits and the requests it sends to the provider. In Baodium’s configuration, each Fraud Service instance admitted up to 80 active evaluations, with no additional unbounded provider queue behind that limit. An evaluation retained its provider-side allocation while its provider attempts and retry delays were still active.
These limits cover different resources. The Order Service limit controls how many of its handlers can wait for Fraud Service. Fraud Service’s limit controls how many evaluations can use its own resources and the provider integration. A caller timeout cannot safely release provider-side capacity while an abandoned request is still running there.
The per-instance values also need to fit the larger fleet. Additional instances, deployment surge, other clients using the same provider account, and recovery workers all contribute to total demand. The provider may enforce separate limits on request rate and simultaneous calls, so both must be tested.
Chapter 9 develops fleet-wide admission, rate limits, and recovery allocations in detail.
When to Queue, Defer, or Reject
A short, bounded queue can be useful when a burst is likely to clear before requests reach their deadlines. It needs limits on both the number of waiting requests and how long they may wait.
For Baodium’s fraud path, the team chose immediate admission or durable deferral. A local queue would consume the customer’s remaining deadline while waiting for capacity that the provider might not restore soon.
A pending operation also consumes resources. Checkout must create a durable record, provide a way to retrieve its progress, and eventually complete or expire it. If the backlog grows faster than recovery can process it, accepting more deferred checkouts eventually becomes unsustainable. At that point, checkout must refuse new work according to its admission policy rather than promise completion it cannot reasonably provide.
The outbound bulkhead protects workers waiting on fraud. Ingress admission and database capacity still determine how many checkout requests Order Service can accept in total.
End-to-End Request Deadlines
A concurrency limit controls how many requests may wait. A deadline controls how long an admitted request is allowed to wait.
Checkout’s overall response objective included several operations: validating the request, evaluating fraud, authorizing payment, reserving inventory, committing the order, and preparing the response. Giving every downstream call its own full checkout deadline would allow the combined request to run far beyond what the customer was promised.
Baodium allocated at most one second to the complete Fraud Service call. That budget included transport time, processing inside Fraud Service, waiting for a provider slot, provider attempts, any retry delays, and returning the result. The provider could receive only the time left after those earlier steps.
Figure Figure illustrates how the available time decreases as a request moves through the call chain.
The engineers established the initial allocation from the checkout response objective and representative request traces. They then tested it under delayed dependencies. We cannot obtain the end-to-end 99th-percentile latency simply by adding the p99 values of individual operations, because those measurements may describe different requests and different combinations of delays. The complete checkout path needs its own latency measurement.
Before beginning fraud evaluation, Order Service checks the time remaining on the incoming request. If an earlier step has consumed most of the budget, checkout may defer the assessment immediately rather than send a call that cannot finish within the available time.
Deadlines and Individual Attempt Timeouts
The deadline applies to the entire assessment. An attempt timeout applies to one request sent during that assessment.
Suppose the fraud budget is one second and the first provider attempt consumes half of it. Another attempt would have to fit within the remaining half second, including any retry delay and the time needed to record the result. Starting the second attempt with another full one-second allowance would exceed the original deadline.
Connection acquisition and waiting for a client slot use the same budget. A request that spends 300 milliseconds waiting for admission has 300 milliseconds less available for provider processing.
Client timeout settings also need careful interpretation. In Python’s requests library, for example, a read timeout normally limits inactivity while receiving data rather than the total duration of a response. A server that continues sending small amounts of data can extend the call beyond what a reader might expect from that setting. Connection setup, DNS resolution, and TLS negotiation have their own behavior and may require additional controls depending on the client library.
The integration needs a total deadline that covers the relevant operations. The engineers tested it by delaying connection setup, response headers, and response-body delivery with a stub or fault-injection proxy such as Toxiproxy. The observed completion and cleanup times had to fit the application’s intended limits.
Passing Deadlines Between Services
Order Service passes the remaining fraud budget to Fraud Service. Fraud Service subtracts the time already consumed before making a provider attempt. This is deadline propagation.
A monotonic clock is appropriate for measuring elapsed time inside one process, but its raw reading has no useful meaning to another host. An absolute timestamp introduces clock-synchronization concerns. gRPC communicates deadlines using a timeout duration on the wire, allowing the receiver to establish a local deadline. Other transports need an agreed way to communicate and reduce the available time.
The team verified propagation by introducing a delay inside Fraud Service before provider dispatch. If the call arrived 300 milliseconds late, the provider attempt needed to receive less time. Passing a fresh one-second budget would allow Fraud Service to continue processing after Order Service had already stopped waiting.
Cancellation and Work That Continues
A deadline tells the caller when it may stop waiting. That does not establish when the receiving service stops processing.
Suppose an Order Service handler starts an outbound call in a background thread and waits for its result with a one-second timeout. In Python, a timeout from a future’s result(timeout=1) method stops the wait, while the background task may continue running.
If the handler releases its concurrency permit immediately, another checkout can begin an outbound call while the original one is still occupying a client slot. After enough timeouts, the number of active calls can exceed the intended limit even though every handler followed the local timeout rule.
The engineers therefore tied resource accounting to the lifetime of the actual outbound operation. A permit was released when its local call finished or when cancellation and cleanup had completed. If the client library allowed a timed-out task to continue, that task remained part of the active-work accounting.
Cancellation also needed to reach retry delays and nested calls. An assessment waiting before another attempt should stop when its deadline expires, unless responsibility has deliberately moved to durable recovery.
The receiving service must enforce its own limits. Closing an HTTP connection may stop a local client from waiting without stopping processing at the external provider. Fraud Service may still have an active provider attempt, and the provider may continue consuming capacity.
This is why local cancellation, remote idempotency, and admission controls appear together in the design. Cancellation protects resources the application can stop using. Stable operation identity allows recovery when the remote outcome is uncertain. Service-side admission protects the dependency from work that continues after a caller has disconnected.
Chapter 3 established the recovery rules for state-changing operations such as payments and inventory reservations. The same uncertainty can affect fraud assessments when the provider stores or charges for an evaluation.
Retries and Failure Containment
A dependency slowdown also creates pressure to retry.
Imagine that an API gateway makes three attempts to reach Order Service, the service mesh permits three attempts to reach Fraud Service, and the provider client makes three attempts of its own. Depending on how those retries are nested, one original request could produce as many as
provider attempts.
That is a serious increase in demand against a provider that is already struggling. The engineers needed one component to decide when a provider request could be repeated.
Baodium assigned that responsibility to Fraud Service. It owned the assessment identity, the provider integration contract, and the remaining execution budget. Automatic retries for this route were disabled in the gateway, service mesh, and provider SDK.
Before retrying, Fraud Service classified the previous outcome. A connection failure known to have occurred before the request was sent may permit another attempt. A completed approval, denial, or manual-review decision ends the assessment. A timeout after dispatch is different because the provider may still be processing the earlier request. Recovery may require a status lookup or another submission using the original assessment identity under the provider’s idempotency contract.
The available deadline matters as much as the error category. If provider evaluations are consistently taking two seconds, repeated half-second attempts are unlikely to produce a useful decision. They may also create additional provider demand when the abandoned attempts continue running.
For eligible transient failures, Fraud Service used bounded retry delays with jitter, a randomized variation that prevents many callers from retrying at the same instant. It checked the remaining deadline before waiting and before sending another request. A per-assessment attempt limit and a shared retry allowance prevented prolonged failures from generating an unbounded stream of requests.
Once the synchronous retry allowance was exhausted, the assessment entered deferred recovery. Recovery workers used their own execution deadlines but retained the original assessment identity and provider-safe recovery procedure.
Circuit Breakers
A concurrency limit controls the number of admitted requests. A circuit breaker can also stop new calls when recent results indicate that a dependency is unlikely to meet its contract.
During Baodium’s incident, the provider continued returning valid fraud decisions. A circuit breaker that watched only HTTP error codes would have missed much of the problem. The useful failure signal was that provider responses had become too slow for checkout.
The engineers could open the breaker after a tested threshold of timeouts or excessive response durations, returning pending outcomes for new assessments. After a recovery interval, a limited number of probe requests could check whether normal processing had resumed.
The admission limit remained in effect during those probes. Otherwise, a recovered provider could immediately receive another large burst of work. Chapter 9 develops breaker thresholds, retry budgets, and recovery procedures.
Implementing a Durable Fraud Assessment
The revised checkout path needed three pieces that would cooperate without depending on a single request handler remaining alive. First, Order Service recorded the assessment and the exact inputs used to make the decision. It then attempted to dispatch the assessment within the available deadline. Finally, a provider result could be applied only if it still belonged to the checkout’s current input version.
The following snippets show the main responsibilities. Repository and deadline methods are illustrative application interfaces.
Recording the Assessment
A risk assessment belongs to a particular version of the checkout inputs. The version changes when risk-relevant information changes, such as the cart, delivery details, or payment method.
def risk_assessment(checkout):
return risk_repo.get_or_create(
checkout_id=checkout.id,
input_version=checkout.risk_input_version,
inputs=risk_inputs.snapshot(checkout),
)The database enforces one assessment record per checkout and input version. Concurrent requests can therefore retrieve the same record rather than creating independent assessments for identical checkout inputs.
CREATE TABLE risk_assessments (
id uuid PRIMARY KEY,
checkout_id uuid NOT NULL,
input_version integer NOT NULL,
input_digest text NOT NULL,
state text NOT NULL,
dispatch_owner uuid,
dispatch_expires_at timestamptz,
dispatch_version bigint NOT NULL DEFAULT 0,
UNIQUE (checkout_id, input_version)
);The repository stores the immutable input snapshot alongside the assessment, with input_digest identifying those inputs. The snapshot can be stored in a protected column or a related record. That lets recovery evaluate the same version rather than reconstructing it from a cart that may have changed.
A unique constraint prevents duplicate assessment records. It does not, by itself, prevent two handlers from sending the same assessment to Fraud Service concurrently.
The dispatcher therefore claims the assessment through a conditional database update before sending it. The claim contains an owner, an expiry, and a version that prevents a worker with an expired claim from overwriting newer local progress. Chapter 3 developed the same lease and fencing mechanism for payment reconciliation.
A second handler that cannot claim the assessment retrieves its current status. If the original handler crashes, recovery can eventually claim it again. Any repeated provider submission must reuse the assessment identity and obey the provider’s idempotency and reconciliation rules.
Checking the Available Deadline
Once an assessment is ready for dispatch, Order Service checks its remaining request budget and attempts to acquire an outbound permit.
def reserve_fraud_call(request):
deadline = request.child_deadline(
maximum_ms=1000,
reserve_ms=checkout_policy.after_risk_budget_ms,
)
if not deadline.can_start_call():
return deadline, None
return deadline, outbound_fraud_slots.try_acquire()If there is insufficient time or no permit is available, the durable assessment remains pending. The handler returns its reference without adding another outbound call.
Dispatching and Recording the Result
After the assessment has been claimed and the outbound permit obtained, Order Service calls Fraud Service with the same assessment identity and input version.
def evaluate_risk(assessment, permit, deadline):
with permit:
return fraud_client.evaluate(
assessment_id=assessment.id,
input_digest=assessment.input_digest,
inputs=assessment.inputs,
deadline=deadline,
)The client must enforce the supplied deadline and account for any local work that continues after a timeout. Fraud Service separately enforces its provider admission limit and owns provider retries.
When a result arrives, Order Service records it only if the assessment still applies to the checkout’s current inputs.
def commit_risk_result(assessment, decision):
return risk_repo.record_decision_if_current(
assessment_id=assessment.id,
input_version=assessment.input_version,
decision=decision,
)The repository performs a guarded database transition. It must verify the assessment’s expected state, the current checkout input version, and the applicable dispatch claim before recording the result. A late timeout cannot replace an approval already committed by another handler, and an approval for an earlier cart version cannot authorize payment for changed contents.
A canceled checkout also cannot proceed to payment because an older risk decision eventually arrived. The service retains the historical assessment for investigation while enforcing the current checkout state.
If the request handler disappears before it can record a deferred outcome, the assessment is still durable. Recovery workers discover unfinished records and continue them under the same operation identity.
Pending Checkout Responses and Recovery
When fraud evaluation could not finish during the original request, Baodium returned a durable checkout reference and a pending status.
The customer saw a message explaining that payment verification was still in progress and that no payment authorization had begun. The page could retrieve the latest status without submitting another fraud evaluation.
An HTTP API can express this through 202 Accepted, a status URL, and an operation identifier.1 A Retry-After header may suggest when the client should check again. The status endpoint must authenticate and authorize the caller, since the reference may expose information about a customer’s purchase.
Recovery workers read pending assessments and submit or reconcile them under a shared provider capacity allocation. They must leave room for live traffic and for provider operations already in progress. A fresh execution deadline may be assigned to a recovery attempt, while the original assessment identity is preserved.
The application also distinguishes an assessment that has not received a provider decision from one whose completed decision requires a human reviewer.
A delayed approval is not sufficient to begin payment without another check. The cart, price, delivery eligibility, payment method, or risk-relevant account data may have changed while the assessment was pending. The order-owning service must confirm that the assessment applies to the current checkout version and that the business rules still permit payment.
The team also defined when a deferred checkout would expire. A backlog that cannot be completed within that interval makes new acceptance risky. If recovery falls behind beyond the approved limits, Order Service must stop accepting additional deferred operations or use another documented customer outcome.
Authentication, Authorization, and Deferred Actions
Deferring fraud evaluation introduced a wider security concern. When an operation runs later, what permission allows the worker to complete it?
Consider a merchant employee requesting a refund. The employee may have permission to inspect orders without having permission to refund a payment. Hiding the Refund button in the interface helps the user experience, but it cannot enforce that permission. The API has to verify the request.
Authentication identifies the principal making the call. Authorization determines whether that principal may perform the requested action on the resource. Authority identifies the service responsible for committing the business outcome.
Chapter 3 introduced these distinctions for payment identity. They become more important when several services participate in an operation or when a worker acts after the original user session has ended.
Payment Service can authorize a refund using the payment’s recorded merchant, the employee’s membership, and the current refund policy.
principal = request.authenticated_principal
payment = payments.get(request.payment_id)
if payment is None:
raise NotFound()
if not memberships.active(principal.id, payment.merchant_id):
raise NotFound()
if not permissions.allows(principal.id, "refund", payment):
raise Forbidden()
refunds.request_once(
payment, request.amount, request.idempotency_key)Returning 404 when the principal cannot access the merchant prevents the API from confirming whether another merchant’s payment exists. A principal who can inspect the payment but lacks refund permission receives 403. Unauthenticated requests receive 401 under the application’s authentication contract.
The example assumes the refund operation also validates the amount, refundable balance, and payment state within a guarded transaction. Those are business requirements that a role check alone cannot enforce.
OpenID Connect can establish a browser user’s identity, while OAuth 2.0 provides a framework for delegated authorization. An application may use a server-managed session or access tokens at its APIs.2
Internal service authentication presents a related problem. Order Service may call Payment Service on behalf of an employee. Authenticating Order Service establishes which service made the call, but Payment Service still needs a trustworthy basis for the employee’s delegated authority. That may come from a properly scoped token or a durable approved operation whose identity and permissions the receiver can verify.
Forwarding an unsigned user identifier in a request header would allow a compromised caller to impersonate another user. The internal network location is not sufficient proof of the caller’s identity or permissions.
Applications often combine role-based access control with resource-specific policy checks. A refund role can establish the general capability, while merchant membership, payment state, amount limits, and regional rules determine whether the particular refund is allowed.
Authorization When Execution Happens Later
Now suppose an employee requests a refund at 10:00. The operation is accepted for deferred processing because the payment provider is unavailable. At 10:04, an administrator revokes the employee’s refund permission. The worker is ready to submit the refund at 10:07.
Should it proceed?
The application needs a business rule for when authorization takes effect. Some operations may execute under a durable approval recorded at acceptance. Others require permission to be checked again immediately before dispatch. Large refunds may require approval from a second employee, and some approvals may expire after a specified interval.
Baodium’s approval record can identify the principal, payment, amount, operation ID, policy revision, approval time, and expiry. The worker verifies that the approval applies to the queued operation before contacting the provider.
def dispatch(refund):
approval = approvals.get(refund.approval_id)
if not approval.valid_for(refund):
return refunds.send_for_review(refund.id)
if not policy.permits_execution(approval, refund):
return refunds.send_for_review(refund.id)
provider.submit(
refund, idempotency_key=refund.operation_id)The worker authenticates with its own service identity and loads the durable refund operation before this code runs. The permits_execution method applies the selected revocation and expiration policy, including a current permission check when that policy requires one.
A final permission read cannot, by itself, prevent revocation from racing with an external dispatch. If a revocation must stop an action that is about to execute, the protected execution boundary needs a coordinated rule for deciding which action takes effect first. Appendix B examines this problem in a deployment-authorization service.
The queue message identifies the operation to perform. It does not independently authorize the worker to perform it.
Testing the Slowdown and Recovery Path
After implementing the limits, the team needed evidence that checkout would behave correctly under the conditions that had caused the incident.
They used a provider stub capable of returning valid decisions, rejecting calls, delaying responses, and never responding. That allowed the engineers to reproduce the slowdown without depending on the external provider.
The first test repeated the original problem. Provider responses slowed toward two seconds while incoming checkout traffic continued at its expected rate. The engineers measured active outbound calls, waiting workers, admission decisions, and pending checkout creation. The bulkhead was useful only if unrelated Order Service operations could continue normally.
They then tested a provider that never responded. The request deadline needed to end local waiting, cancellation needed to release resources the application could actually release, and remote attempts that might still be running had to remain within Fraud Service’s provider accounting.
The team also inspected every attempt received by the stub. A counter inside Fraud Service’s retry loop would miss retries introduced by a gateway, mesh, or SDK. Measuring at the provider boundary showed whether the complete system honored the configured retry policy.
Finally, the engineers started with a backlog of pending assessments while new checkout requests continued arriving. Recovery workers had to share the provider allocation without exhausting live traffic capacity. They also needed to respect checkout expiration, cancellation, and changes to the assessed inputs.
The release review compared more than request latency. Returning a pending status quickly would improve the initial HTTP response even if customers never received a final result. The team therefore tracked confirmed checkout completion, time to resolve deferred assessments, backlog age, and expired checkouts.
After release, Order Service reported occupied workers, active outbound fraud calls, and admission outcomes. Fraud Service reported active provider attempts, acquisition delay, provider-call duration, and reasons for deferral. The durable assessment records supplied the recovery measurements from Chapter 3.
Together, these measurements allowed an engineer to distinguish a slow live request from an assessment waiting for capacity and one requiring manual review. Chapter 8 develops how to instrument and correlate these observations across an entire request path.
Applying the Same Decisions to a Booking Service
Consider a travel-booking service that reserves a seat, authorizes payment, sends a receipt, and records analytics. The traveler needs to know whether the reservation and payment were confirmed. Receipt delivery and analytics can finish later.
The sequence of required operations matters. Starting payment before confirming seat availability might shorten the initial wait, but an unavailable seat would then require compensation for an authorization already made. If the booking contract requires a secured seat before payment, the service should establish that result first.
A payment response can also be lost after the provider has authorized it. The booking service needs the durable operation identity and reconciliation procedure developed in Chapter 3. If the result cannot be confirmed before the request deadline, the API can return a pending booking reference under a documented recovery policy.
We can begin with a small design: a booking API, a transactional database for reservation state, a bounded payment client, and a durable job path for receipts. Additional services may become useful when different teams need independent ownership or when resource isolation becomes necessary.
The important decisions are already present in that first design. We need to know which results must be confirmed before responding, which calls may continue afterward, how long each dependency may occupy resources, and what the customer can retrieve after an interruption.
Summary
Baodium’s fraud provider continued returning valid decisions during the incident. The problem was how long those decisions took to arrive and how many checkout requests accumulated while waiting for them. Adding workers would have allowed more requests to wait without increasing the provider’s ability to complete assessments.
The revised design gave Order Service a limit on outbound fraud calls and a deadline that followed the request through Fraud Service. When an assessment could not finish within that time, checkout recorded it for recovery and returned a pending reference. The customer could retrieve its progress, while background workers completed or expired the operation under the same provider-capacity limits.
Those changes also required retry ownership, reliable cancellation accounting, and checks that delayed decisions still applied to the current checkout. The engineers could make those choices because they had first agreed on which business results were required before payment could begin.
We will encounter the same resource problem again when requests repeatedly fetch data that has barely changed. In Chapter 5, Baodium’s catalog team introduces caching to reduce database reads. That design relieves pressure on the source, although it also creates decisions about how old a cached result may be and what happens when the cache is unavailable.
RFC 9110, Section 15.3.3, defines
202 Acceptedas an acknowledgment that processing has been accepted but may not be complete.↩︎An OpenID Connect ID token is intended for the client. An API accepting access tokens must validate the token type, issuer, audience, lifetime, and other applicable constraints. A valid token does not establish ownership of a particular payment.↩︎
After this chapter
⌘/Ctrl K to search