Multi-Partner Book Purchasing Broker

Medium · System Design · Software Engineer · Technical Screen

Prompt

Design a backend brokerage service that buys books across a network of external partner bookstores on a caller's behalf. A client calls POST /v1/purchase supplying a target isbn, requested quantity, per-copy budget ceiling (max_price), and transaction deadline (ttl_ms)—for example, requesting 2 copies of 9780262046305 at up to $45.00 per copy within a 600,000 ms (10-minute) window.

Your service must enforce four core guarantees:

  • Concurrent price discovery: Query all healthy partner bookstore APIs in parallel to find the best qualifying offer.
  • Deadline-bound execution: If any bookstore can supply the requested copies at or below max_price before ttl_ms expires, execute the order.
  • Strict idempotency: Partner connections can drop or time out mid-flight; a client request must never result in buying the book twice.
  • Post-confirmation payment capture: Coordinate with an internal payment service so buyer funds are captured only after a partner bookstore confirms the purchase.

In addition to POST /v1/purchase, support asynchronous progress updates and a status-lookup endpoint for in-flight orders. Keep request intake highly available, isolate slow or offline bookstores so healthy partners continue fulfilling requests, and record a complete audit trail of partner price checks, responses, and order state transitions.

Scope & Expectations

  • API design: Specify POST /v1/purchase, order-status polling endpoints, and asynchronous update contracts, including how client retries stay idempotent.
  • Database schema & order state machine: Model the relational tables, audit store, and explicit order lifecycle states (such as PENDING, PURCHASED, FAILED, and REFUNDED) with race-safe state transitions.
  • Distributed orchestration & rollbacks: Walk through parallel quote fan-out, TTL expiration, reconciling ambiguous partner timeouts without double-ordering, and two-phase payment hold/capture/rollback flows.
  • Fault isolation & auditability: Explain how rate limits, timeouts, and degraded bookstores are contained while preserving a debuggable history of every external interaction.

Step-by-step walkthrough

  1. Clarify requirements and boundary rules

    A book purchase broker sits between buyers and unreliable third-party bookstores. Every hard problem lives at the boundaries between systems: partner APIs go down or time out, prices change between checking and buying, money moves in a separate payment service, and every request carries a Time-To-Live (TTL) (a deadline in milliseconds after which we must stop searching if no deal was found). Pinning down the exact rules first keeps the state machine clean.

    Functional requirements

    • Accept POST /v1/purchase with isbn, quantity, max_price, and ttl_ms, plus a client-generated order_id, payment method reference, and shipping address reference.
    • Fan-out (querying multiple downstream services in parallel) across all partner bookstores to find the lowest price at or below max_price before ttl_ms expires.
    • Coordinate with the internal payment service using two-phase card payments: authorization (placing a temporary hold on the buyer's funds without moving money) and capture (actually charging the held funds), capturing funds strictly after a partner bookstore confirms fulfillment.
    • Provide GET /v1/purchase/{order_id} for polling order status and send asynchronous status updates via signed webhooks (HTTP callbacks pushed to a client URL when state changes).

    Non-functional requirements

    • Idempotency (the property that repeating the exact same request produces the exact same single purchase rather than buying twice), even across partner network timeouts.
    • High availability at intake: accepting POST /v1/purchase must stay fast and up even if half the partner bookstores are down.
    • Fault isolation: one slow or broken bookstore must never block quotes or purchases from healthy bookstores.
    • Full auditability: record every price quote, partner response, and state transition so support engineers can reconstruct why any order succeeded, failed, or chose one bookstore over another.

    Explicit assumptions (state and confirm with the interviewer)

    • max_price is the maximum landed unit price per copy (item price plus that copy's share of shipping; taxes out of scope), and all quantity copies must be fulfilled in one shipment by a single bookstore.
    • TTL bounds starting the purchase, not shipping. Once we send a buy request to a bookstore before expires_at, we must drive that attempt to a known outcome even if the clock passes expires_at; walking away mid-call could leave an unaccounted book order.
    • ttl_ms spans from 1,000 ms (a single fast quote round) up to 24 hours ("watch prices until a bookstore drops below my budget").
    • Partner bookstores have uneven API capabilities, so we model each partner's supported features explicitly:
    Partner capability            Why the broker cares
    ----------------------------  -----------------------------------------------------------------
    Quote endpoint (+ batching)   Fetches price and stock; batching checks 50+ ISBNs in one call
    Reserve / hold                Locks price and stock for a few minutes before committing to buy
    Idempotency key on orders     Lets us safely retry a timed-out order call without buying twice
    Order lookup by our key       Lets us ask "did order K go through?" after a network timeout
    Cancel endpoint               Undoes a confirmed order if our payment capture fails afterward
    Outbound webhooks             Pushes confirmation, shipping, or cancellation events to us
    Failed-transaction fee        Penalizes failed order attempts (changes retry ranking)
    Rate limit (calls/sec)        Caps how frequently we can poll quotes from this partner
    
  2. Back-of-the-envelope numbers

    Before picking queues or caches, let's check whether the bottleneck is our own servers, our database, or our partners' rate limits.

    Traffic assumptions
      Purchase requests           500,000 / day  ->  ~5.8 req/s average (~6 req/s)
      Back-to-school peak (10x)                  ->  ~60 req/s
      Partner bookstores          8 partners, each allowing at most 50 API calls/s
      TTL mix                     70% short TTL (<= 10 s): 350,000/day, 1 quote round
                                  30% long TTL (minutes to 24 h): 150,000/day, ~30 min average wait
    
    Partner quote calls
      Short-TTL fan-out           350,000/day x 8 partners = 2.8M calls/day
                                  -> ~32 calls/s total, or ~4 calls/s per partner (~40/s at 10x peak)
    
      Long-TTL (naive: poll every 60 s per waiting order)
                                  150,000/day x 30 polls x 8 partners = 36M calls/day
                                  -> ~417 calls/s total, or ~52 calls/s per partner AVERAGE
                                  (~520/s at peak -> blows right past the 50 calls/s partner limit!)
    
      Long-TTL (shared watch per unique ISBN)
        Active waiting orders     150,000/day x (30 min / 1,440 min per day) = ~3,125 concurrent orders
        Unique ISBNs watched      Popular textbooks overlap -> assume ~1,000 distinct ISBNs
        Shared poll rate          1,000 ISBNs / 60 s = ~16.7 calls/s per partner (~17 calls/s)
    
      Combined per partner        ~4/s (short) + ~17/s (watch) = ~21 calls/s average (fits under 50/s!)
                                  At 10x peak, short-TTL rounds need ~40/s, leaving ~10/s for watch polls
    
    Purchases completed
      60% match rate              300,000 purchases/day -> ~3.5/s average, ~35/s peak
    
    Storage
      Transactional order rows    500,000/day x ~2 KB (order + steps + events) = ~1 GB/day (~365 GB/yr)
      Partner quote/response log  (~2.8M + ~11.5M watch + ~0.7M order calls) = ~15M calls/day
                                  x ~1 KB structured summary = ~15 GB/day (~5.5 TB/yr; raw bodies 30 d)
    

    Three design decisions fall straight out of this math:

    1. Our own intake traffic is tiny: 60 writes/s at peak fits comfortably on a single PostgreSQL primary with synchronous standbys—no database sharding needed.
    2. Partner rate limits are the real bottleneck: polling per order breaks partner limits even on an average day (52 calls/s > 50 calls/s), whereas deduplicating polls per (ISBN, partner) cuts watch calls to ~17 calls/s and lets short-TTL deadlines take priority during traffic spikes.
    3. Audit logs outweigh order rows 15-to-1: keeping ~5.5 TB/year of quote logs in cheap append-only object storage keeps the transactional database lean and fast.
  3. API design

    Because checking prices, waiting for a price drop, confirming an order, and capturing payment can take anywhere from half a second to hours, POST /v1/purchase is asynchronous: it validates and persists the request, then immediately returns HTTP 202 Accepted.

    1. Submit a purchase request
       POST /v1/purchase
       Headers: Authorization: Bearer <token>
       Body:
       {
         "order_id": "6f1c9a20-...",           // Client-generated UUID (idempotency key)
         "isbn": "9780262046305",
         "quantity": 2,
         "max_price": {"amount_cents": 4500, "currency": "USD"},   // Max landed price per copy
         "ttl_ms": 600000,
         "payment_method_ref": "pm_98a...",
         "shipping_address_ref": "addr_31b...",
         "callback_url": "https://client.example/webhooks/books"   // Optional
       }
       Responses:
         202 Accepted  {"order_id": "6f1c9a20-...", "status": "PENDING",
                        "status_version": 1, "expires_at": "2026-11-30T18:25:00Z",
                        "status_url": "/v1/purchase/6f1c9a20-..."}
         200 OK        Same body if (client_id, order_id) already exists with identical payload
         409 Conflict  {"error": "order_id_reused_with_different_payload"}
         400 Bad Req   Invalid ISBN-13 checksum, quantity < 1, or ttl_ms outside [1000, 86400000]
    
    2. Check order status
       GET /v1/purchase/{order_id}
       -> 200 OK {"order_id": "...", "status": "PURCHASED", "status_version": 5,
                  "partner_id": "bookstore_d", "unit_price_cents": 4400,
                  "total_charged_cents": 8800, "expires_at": "...",
                  "history": [{"status": "PENDING", "at": "..."}, ...]}
    
    3. Cancel a waiting order (allowed only in PENDING or QUOTING; 409 once PURCHASING starts)
       POST /v1/purchase/{order_id}/cancel
    
    4. Internal support audit trail
       GET /v1/purchase/{order_id}/audit?client_id=...
    
    5. Outbound client webhook & inbound partner webhook
       POST {callback_url}                  {"order_id", "status", "status_version", "at"} (HMAC-signed)
       POST /v1/partners/{partner_id}/events  (Partner-signed; deduplicated by partner_event_id)
    

    Why each field earns its place:

    • Client-generated order_id + request_hash: If the client's network drops right after sending POST /v1/purchase, retrying with the same order_id returns the existing order instead of buying two sets of books. Storing a SHA-256 request_hash of the body catches client bugs that accidentally reuse an order_id for a different ISBN (409 Conflict).
    • status_version: Webhooks over the public internet can arrive out of order (PURCHASED arriving before CAPTURING). Including an integer status_version (1, 2, 3, ...) lets the client discard any webhook whose version is older than the highest version it has already seen.
    • Integer cents (amount_cents): Representing $45.00 as 4500 avoids binary floating-point rounding bugs (0.1 + 0.2 != 0.3).
  4. Data model and order state machine

    We store orders and workflow state in PostgreSQL (one primary plus two synchronous standbys across availability zones, where a commit waits for any one standby so losing one zone never blocks writes). Every table keys orders by (client_id, order_id) so two different clients cannot collide if they pick the same UUID.

    purchase_order    PK (client_id, order_id), request_hash, isbn, quantity, max_unit_price_cents,
                      currency, ttl_ms, expires_at, status, status_version, failure_reason,
                      authorized_cents, selected_partner_id, unit_price_cents, total_cents,
                      payment_method_ref, shipping_address_ref, callback_url, created_at, updated_at
    
    order_step        PK (client_id, order_id, step_key), step_type (AUTHORIZE, CAPTURE, VOID, REFUND),
                      idempotency_key UNIQUE, status (STARTED, SUCCEEDED, FAILED, UNKNOWN),
                      external_ref, started_at, finished_at
    
    partner_attempt   PK (client_id, order_id, attempt_no), partner_id, idempotency_key UNIQUE,
                      partner_order_ref, quoted_unit_price_cents, confirmed_unit_price_cents,
                      fee_cents, status (SENT, CONFIRMED, REJECTED, UNKNOWN, CANCEL_SENT, CANCELED),
                      reject_reason, sent_at, resolved_at
    
    order_event       PK (client_id, order_id, seq), from_status, to_status, reason, actor, at
                      -- Append-only audit trail of state transitions; never updated or deleted
    
    timer             PK (timer_id), client_id, order_id,
                      kind (TTL_EXPIRY, RECONCILE_PARTNER, RETRY_STEP), fire_at
    
    isbn_watch        PK (isbn, partner_id), waiting_orders, next_poll_at,
                      last_item_price_cents, last_in_stock, last_polled_at
    
    outbox            PK (id), topic, payload, created_at
                      -- Transactional outbox: written in the same DB transaction as state changes
    

    A transactional outbox is a table inside the same database where we insert outgoing queue messages in the exact same SQL transaction as our row update; a background relay process then forwards those rows to the task queue and deletes them. That eliminates the classic dual-write bug where the database commit succeeds, the server crashes a millisecond later, and the queue message is never sent.

    Order state machine

                   auth declined / cancel / TTL
       +--------+ -----------------------------> +--------+
       |PENDING |                                | FAILED | <---+
       +--------+                                +--------+     | TTL expired / cancel /
           | auth succeeded ($max x qty held)        ^          | capture failed + partner canceled
           v                                         |          |
       +--------+  offer <= max_price   +------------+          |
       |QUOTING | --------------------> | PURCHASING | ---------+
       +--------+ <-------------------- +------------+          |
                     partner rejected       |                   |
                     & TTL still left       | partner confirmed |
                                            v                   |
                                        +-----------+ ----------+
                                        | CAPTURING |
                                        +-----------+ ---> +--------------+
                                            |              | NEEDS_REVIEW | (capture failed &
                               capture ok   v              +--------------+  partner can't cancel)
                                        +-----------+
                                        | PURCHASED | ---> +-----------+ ---> +----------+
                                        +-----------+      | REFUNDING |      | REFUNDED |
                                          partner cancels  +-----------+      +----------+
                                          after capture
    

    Notice that a partner network timeout does not transition out of PURCHASING: the attempt row becomes UNKNOWN, while the order stays locked in PURCHASING until we verify whether the bookstore created the order.

    To prevent race conditions—for example, a TTL_EXPIRY timer firing at the exact millisecond a worker selects a winning quote—every transition uses optimistic locking (Compare-And-Swap), a conditional UPDATE checking WHERE status = :expected_from:

    BEGIN;
    
    UPDATE purchase_order
    SET status = :to_status,
        status_version = status_version + 1,
        updated_at = now()
    WHERE client_id = :client_id
      AND order_id = :order_id
      AND status = :from_status;
    -- If 0 rows are updated, another worker or webhook already moved this order: ROLLBACK!
    
    INSERT INTO order_event (client_id, order_id, seq, from_status, to_status, reason, actor, at)
    VALUES (:client_id, :order_id, :status_version, :from_status, :to_status, :reason, :actor, now());
    
    INSERT INTO outbox (id, topic, payload, created_at)
    VALUES (:outbox_id, 'order-work', :payload, now());
    
    COMMIT;
    
  5. High-level architecture

    We decouple the fast HTTP intake path from slow, failure-prone partner calls and payment coordination using a task queue, durable timers, and stateless orchestrator workers:

     Clients
       | POST /v1/purchase, GET status, POST cancel
       v
     [ API Gateway ]  (TLS, auth, per-client rate limits)
       |
       v
     [ Purchase API ]  (Stateless, 3+ zones; writes PENDING order + TTL timer + outbox in 1 DB tx)
       |
       v
     [ Orders DB (PostgreSQL) ]  (Primary + 2 sync standbys)
       |
       +---> [ Outbox Relay ] ---> [ Task Queue ] <--- [ Timer Service ] (TTL, reconcile, backoff)
                                         |
                                         v
                             [ Saga Orchestrator Workers ]
                               |           |            |
                +--------------+           |            +------------------+
                v                          v                               v
       [ Payment Service ]      [ Quote Aggregator ]           [ Partner Order Gateway ]
         authorize / capture      fan-out rounds +               reserve / place_order /
         void / refund            shared isbn_watch              get_order / cancel
                                           |                               |
                                           +---------------+---------------+
                                                           |
                                                           v
                             [ Partner Adapters (A .. H) ] (Timeouts, token buckets, circuit breakers)
                                |                     ^
                                v                     | Inbound partner webhooks
                         [ Bookstore APIs A .. H ] ---+---> POST /v1/partners/{id}/events
    
       Every adapter call ---> [ Async Audit Stream ] ---> Object Storage (30d raw) + Warehouse (2y)
       Every state change ---> [ Webhook Notifier ]   ---> Signed POST to client callback_url
    

    Why orchestration over choreography? In choreography, separate microservices subscribe to each other's events (QuoteFound, OrderConfirmed, PaymentFailed) with no central coordinator. In orchestration, one central state machine (Saga Orchestrator) commands each step and records every transition in one place. Because money and external purchases require ironclad rollbacks and a single GET /audit timeline, centralizing the state machine in stateless orchestrator workers is much easier to debug, test, and audit.

    Partner adapters isolate third-party quirks. Each bookstore speaks a different JSON/XML format and error scheme, so each gets a thin adapter implementing one uniform interface (quote, reserve, place_order, get_order, cancel) and reporting its capability flags.

  6. Deep dive 1: Concurrent fan-out, offer selection, and TTL timers

    Short TTLs (seconds): parallel fan-out with a hard round deadline.

    1. As soon as POST /v1/purchase commits PENDING, an orchestrator worker calls authorize(max_price * quantity) on the internal payment service (~100 ms). For ultra-short TTLs (< 2,000 ms), the read-only quote fan-out runs in parallel with authorize since reading quotes has no side effects, and selection waits until authorize succeeds (QUOTING).
    2. The quote aggregator fans out quote requests concurrently to all 8 partner adapters whose circuit breakers are closed (skipping the network call if a cached quote for (partner_id, isbn) is under 10 seconds old).
    3. One slow bookstore must never stall the round. Each partner call gets a timeout of min(1.5 * partner_p99_latency, round_deadline)—where p99 latency is the response time that 99% of recent calls beat—and round_deadline = min(2000 ms, remaining_ttl_ms - 300 ms).
    4. Once all partners respond or round_deadline fires, we pick the cheapest valid landed price per copy, breaking ties in favor of the partner with the highest recent fulfillment success rate:
    def choose_offer(quotes: list[dict], max_unit_price_cents: int, quantity: int) -> dict | None:
        """Return the lowest-priced in-stock offer <= max_unit_price_cents.
    
        Each quote dict holds:
          - partner_id: str
          - unit_price_cents: int  (item price + per-copy shipping for this quantity)
          - in_stock: int
          - success_rate: float    (rolling 24h order confirmation rate in 0.0..1.0)
          - error: str | None
        """
        best_quote = None
    
        for quote in quotes:
            # Ignore partners that timed out, errored, or lack enough copies.
            if quote["error"] is not None or quote["in_stock"] < quantity:
                continue
    
            # Enforce the buyer's per-copy budget ceiling.
            if quote["unit_price_cents"] > max_unit_price_cents:
                continue
    
            if best_quote is None:
                best_quote = quote
            elif quote["unit_price_cents"] < best_quote["unit_price_cents"]:
                best_quote = quote
            elif (
                quote["unit_price_cents"] == best_quote["unit_price_cents"]
                and quote["success_rate"] > best_quote["success_rate"]
            ):
                # Tie-breaker: prefer the more reliable bookstore at the exact same price.
                best_quote = quote
    
        return best_quote
    

    Runner-up acceptable quotes are kept in sorted order so that if our top bookstore rejects the order (e.g., last copy just sold out) and time remains before expires_at, the orchestrator immediately tries runner-up #2 without another fan-out round.

    Long TTLs (minutes to hours): shared (ISBN, partner) price watch without stampedes.

    If Round 1 finds no offer <= max_price and expires_at is still minutes away, the order increments isbn_watch.waiting_orders and goes idle (consuming zero worker threads). Every 60 seconds, the quote aggregator polls active (isbn, partner_id) pairs—using batch quote endpoints wherever supported—and matches new prices against waiting orders for that ISBN.

    One subtle trap: if 50 students are watching the same textbook and Bookstore D drops its price to $44 with only 3 copies in stock, waking all 50 orders at once would stampede Bookstore D with 47 doomed buy calls! Instead, the matcher wakes waiting orders in FIFO order (created_at ASC) only up to the reported in_stock count (say, enough orders to claim those 3 copies plus 1 backup).

    Durable TTL timers, never sleep(). TTL_EXPIRY is a row in timer committed during intake. At expires_at, the Timer Service enqueues a TTL_EXPIRY job. If the order is still in QUOTING (or PENDING), the guarded UPDATE moves it to FAILED (NO_OFFER_BEFORE_TTL) and voids the payment hold. If the order already moved to PURCHASING at t = 9m58s, the WHERE status IN ('PENDING', 'QUOTING') guard matches 0 rows and safely does nothing.

    Concrete timeline: 2 copies, max_price = $45.00, TTL = 10 minutes
    ------------------------------------------------------------------------------------
    00:00.00  POST /v1/purchase -> commits PENDING + TTL timer (10:00), returns 202
    00:00.12  Payment service authorizes $90.00 hold            -> status: QUOTING
    00:01.40  Round 1 finishes: A=$52, B=$49, C=timeout, D..H=0 -> registers isbn_watch
    04:10.00  Watch poll sees D=$44.00 (5 in stock)             -> wakes order
    04:10.05  Commits partner_attempt #1 + RECONCILE timer      -> status: PURCHASING
    04:10.60  D reserves & confirms 2 copies @ $44.00 ($88.00)  -> status: CAPTURING
    04:10.85  Payment service captures $88.00 ($2.00 released)  -> status: PURCHASED
    
  7. Deep dive 2: End-to-end idempotency across flaky partner networks

    Every internal and external side effect uses a deterministic idempotency key derived from R = {client_id}:{order_id}—never a random UUID generated inside a retry loop! Scoping by client_id ensures Client X and Client Y never collide even if both pass "order-1".

    Side-effecting call                Derived idempotency key              Persisted BEFORE call in
    ---------------------------------  -----------------------------------  ------------------------
    Client -> POST /v1/purchase        (client_id, order_id)                purchase_order PK
    Broker -> Payment authorize        R:auth:1                             order_step
    Broker -> Partner reserve / buy    R:{partner_id}:{attempt_no}          partner_attempt
    Broker -> Payment capture          R:capture                            order_step
    Broker -> Payment void / refund    R:void, R:refund                     order_step
    Broker -> Partner cancel           R:{partner_id}:{attempt_no}:cancel   partner_attempt
    Broker -> Client webhook           R:webhook:{status_version}           outbox
    

    Two rules prevent double purchases when partner calls time out or workers crash:

    1. Persist the attempt AND its reconciliation timer before touching the network. Before sending POST /orders to Bookstore B, the worker commits partner_attempt (attempt_no = 1, idempotency_key = K, status = 'SENT') and a RECONCILE_PARTNER timer (fire_at = now() + timeout + 2s) in one database transaction. Even if the worker VM crashes 1 millisecond after sending the HTTP packet, that durable timer guarantees another worker will check what happened to K.
    2. Increment attempt_no ONLY after a definitive rejection. If Bookstore B replies 422 Out of Stock, attempt_no = 1 becomes REJECTED, and trying Bookstore D uses attempt_no = 2. If Bookstore B times out or returns 502 Bad Gateway, attempt_no = 1 becomes UNKNOWN and we keep reusing the exact same key K until we prove whether order K exists:
    t        Broker worker                                     Bookstore B
    -------  ------------------------------------------------  ----------------------------------
    0.00 s   DB tx: insert attempt #1 (key K, SENT)
                    + RECONCILE_PARTNER timer @ 7.0 s
    0.02 s   POST /orders (Idempotency-Key: K) ------------->  Creates partner order #881 ($88)
                                                  X  <-------  200 OK lost when TCP drops!
    5.02 s   HTTP timeout! Mark attempt #1 -> UNKNOWN
    7.00 s   RECONCILE timer fires:
             GET /orders?client_reference=K ---------------->  200 OK {id: "#881", CONFIRMED, $88}
    7.15 s   Mark attempt #1 -> CONFIRMED;
             guarded transition PURCHASING -> CAPTURING
    

    What if a legacy bookstore supports neither idempotency keys nor lookup-by-reference? We never blind-retry POST /orders against it: the attempt stays UNKNOWN, we poll their order list / daily report or alert ops after a threshold, and we penalize that partner's tie-breaker score so modern idempotent partners always win ties.

  8. Deep dive 3: Payment-and-purchase saga and rollbacks

    Because partner bookstores and our payment service are separate systems with no shared database transaction, we coordinate them with the Saga pattern: a sequence of local steps where each forward step defines a compensating action (an explicit undo step) to run if a later step fails.

    Forward step                                 Compensating action if a later step fails
    -------------------------------------------  ---------------------------------------------------
    1. Authorize (max_price x quantity)          Void the authorization hold
    2a. Reserve stock & price at partner         Cancel the partner reservation (free, lightweight)
    2b. Place partner order                      Cancel the partner order (may fail once shipped)
    3. Capture confirmed total (<= authorized)   Issue a payment refund
    

    Why this exact sequence keeps money and books consistent:

    • Authorize before ordering, capture after confirmation: Authorizing first proves the buyer has funds before we ask any bookstore to ship a book. Capturing last satisfies the requirement to charge only confirmed orders, and capturing $88 on a $90 hold automatically releases the unused $2.
    • Refresh aging holds before ordering on long TTLs: For a 20-hour price watch, an early card hold might have been reversed by the issuing bank. Before step 2b, if the hold is stale or invalid, we re-authorize (R:auth:2) first so we almost never land in "bookstore confirmed, but card capture failed."
    • Never compensate an UNKNOWN step: While a partner attempt is UNKNOWN after a timeout, we never void the buyer's payment hold and never order from a second bookstore. If Bookstore B actually created order #881, voiding the hold early would leave us owing Bookstore B for a book we can no longer charge the buyer for!
    Failure scenario                              Saga recovery path                       End state
    --------------------------------------------  ---------------------------------------  ------------
    1. Card authorization declined                Nothing to undo                          FAILED
    2. TTL expires before any offer <= max_price  Void authorization hold                  FAILED
    3. Partner definitively rejects; TTL left     Try runner-up quote (`attempt_no + 1`)   QUOTING
    4. Partner definitively rejects; TTL passed   Void authorization hold                  FAILED
    5. Partner call times out                     Keep hold; reconcile by key K            PURCHASING
    6. Partner confirmed; capture fails (network) Retry capture with same key `R:capture`  PURCHASED
    7. Partner confirmed; capture fails permanently:
       - Partner cancellation succeeds            Cancel partner order + void residual     FAILED
       - Partner cannot cancel (already shipped)  Page ops with full audit context         NEEDS_REVIEW
    8. Partner cancels order after we captured    Refund captured amount (`R:refund`)      REFUNDED
    

    Every compensating step (void, cancel, refund) is retried with exponential backoff using its deterministic idempotency key until it succeeds. When an unrecoverable mismatch occurs (capture permanently failed and the partner already shipped the box), transitioning to NEEDS_REVIEW pages a human operator instead of lying with FAILED.

  9. Scaling, fault tolerance, auditability, and trade-offs

    Rate limiting and circuit breakers

    • Shared token-bucket rate limiters: Each partner adapter enforces a token bucket (a counter in Redis refilled at the partner's rate_limit_rps, say 50 tokens/s, where each outbound call spends 1 token). Short-TTL quote rounds pull from the bucket with high priority; background isbn_watch polls only use spare tokens, stretching their 60-second poll interval gracefully during peak bursts instead of triggering 429 Too Many Requests errors.
    • Endpoint-scoped circuit breakers: Each partner gets separate circuit breakers (automatic switches that stop calling a failing dependency so threads do not pile up waiting on timeouts) for quote, place_order, and get_order. Only 5xx errors and network timeouts trip a breaker—never 404 Unknown ISBN or Out of Stock. Keeping get_order on its own breaker ensures we can still resolve UNKNOWN in-flight orders even while blocking new orders to a struggling bookstore.

    Auditability and automated reconciliation

    • Every adapter logs (order_id, partner_id, endpoint, idempotency_key, status_code, latency_ms, parsed_price, parsed_stock, error) asynchronously to an append-only stream, storing raw payloads for 30 days in object storage (with buyer names and shipping addresses redacted) and structured rows for 2 years in the warehouse.
    • Hourly invariant checks verify that every PURCHASED order has a SUCCEEDED capture of the exact same amount, no FAILED order retains an open authorization hold past 1 hour, and daily partner settlement files match partner_attempt (CONFIRMED) 1-for-1 (flagging any orphan order to NEEDS_REVIEW).

    Summary of key trade-offs

    • Async 202 Accepted + task queue vs. synchronous POST: Keeps intake fast (< 50 ms) and resilient to partner outages, at the cost of requiring clients to poll GET or handle webhooks.
    • Centralized saga orchestrator vs. event choreography: Concentrates state transitions, compensations, and audit history in one readable codebase, trading looser service coupling for transactional clarity.
    • Shared (ISBN, partner) watch vs. per-order polling: Cuts long-TTL partner traffic below rate limits (~17/s vs. ~52/s per partner), trading instant detection for up to a 60-second poll delay.
    • Waiting up to a 2-second round deadline vs. buying the first valid quote: Secures the lowest price across all bookstores, adding up to 2 seconds of latency on short-TTL orders when one partner is slow.

Intuition & how it works

Think of a book purchase broker like a personal book-buying assistant working with a budget cap, a stopwatch, and a strict receipt book. When you ask for 2 copies of a textbook at $45 or less within 10 minutes, the assistant does not keep you waiting on the phone: they immediately write your order into a ledger, hand you a tracking stub (HTTP 202 Accepted), place a temporary authorization hold on your payment card (freezing $90 without charging you yet), and call all 8 partner bookstores in parallel (fan-out). To prevent buying the book twice when a bookstore's connection drops mid-order, every call carries a deterministic idempotency key (a unique ticket ID derived from your order_id so repeating a timed-out call returns the existing order instead of creating a second one). Finally, payment and partner ordering are coordinated as a saga (a multi-step workflow across separate services where every step has a matching undo step), capturing your money only after a bookstore confirms your order.

Why do simpler designs fail here? Doing price checks, partner ordering, and payment inside one synchronous POST request makes your API hang whenever a single bookstore is slow, and if the caller disconnects mid-flight, neither side knows whether a book was purchased. Treating a bookstore network timeout as a failure—either retrying with a brand-new request ID or immediately ordering from a second bookstore—causes double purchases whenever the first bookstore actually processed the request before its response dropped. And polling all 8 bookstores every minute for each waiting order individually multiplies outbound calls until partner rate limits block the broker completely.

Let's trace one concrete order (order_id = "ord_42", quantity = 2, max_price = $45, TTL = 10 min) across three bookstores (A, B, C):

1. Intake & hold (t = 0.0 s):
   Client sends POST /v1/purchase (order_id = "ord_42") -> saved as PENDING, returns 202.
   Worker authorizes $90 hold (key "c1:ord_42:auth:1") -> moves to QUOTING.

2. Fan-out Round 1 (t = 0.2 s .. 1.5 s):
   A quotes $52, B quotes $49, C times out -> none <= $45!
   Order registers interest in shared isbn_watch for this ISBN (polled once/min, not per order).

3. Price drop & timeout recovery (t = 4m 10s):
   Shared watch poll sees B dropped to $44 (5 in stock) -> wakes "ord_42".
   Worker commits attempt #1 (key "c1:ord_42:B:1", SENT) + RECONCILE timer, moves to PURCHASING.
   POST /orders to B times out at 5 s! Worker does NOT try A or C and does NOT void the $90 hold.
   At t = 4m 17s, RECONCILE timer calls GET /orders?ref=c1:ord_42:B:1 -> B confirms Order #881 ($88)!

4. Capture & finish (t = 4m 18s):
   Order moves to CAPTURING -> captures $88 (key "c1:ord_42:capture"), releasing the extra $2 hold
   -> moves to PURCHASED and pushes signed webhook (status_version = 5) to client.

Key trade-offs

  • Asynchronous 202 Accepted + task queue vs. synchronous POST. Persisting the request and returning 202 in tens of milliseconds keeps the entry point fast and unaffected by partner outages, and makes multi-hour Time-To-Live (TTL) (expiration deadline) price watches possible. The trade-off is that clients must poll GET /v1/purchase/{order_id} or receive webhooks (outbound HTTP callbacks), and we must run a queue and durable timer service.
  • Orchestrated saga vs. event choreography. A central orchestrator (one worker service driving an explicit state machine) keeps every transition, rollback, and audit reason in one place. Choreography (independent services reacting to each other's events) reduces central coupling, but scatters rollback logic across services and makes answering "what happened to ord_42?" much harder.
  • Authorize at intake, capture after confirmation vs. charging upfront. Placing an authorization hold first rejects declined cards before we touch any bookstore and guarantees we never capture real money without a confirmed book. The cost is holding the buyer's credit line during the search and handling the rare case where capture fails after partner confirmation via partner cancellation or human escalation (NEEDS_REVIEW).
  • Reusing the same idempotency key after timeouts vs. retrying a new partner immediately. Keeping attempt_no fixed on network timeouts—and never voiding the payment hold while an attempt is UNKNOWN—eliminates double purchases and unpaid partner orders. The trade-off is that orders sit in PURCHASING while status lookup reconciles the unknown outcome.
  • Shared (ISBN, partner) price watch vs. per-order polling. Deduplicating background polls by unique ISBN keeps long-TTL traffic around ~17 calls/s per partner instead of ~52 calls/s average (~520/s at peak), staying inside a 50 calls/s partner limit. The trade-off is up to one polling interval (~60 s) of delay before noticing a price drop.
  • Waiting up to a 2-second round deadline vs. buying the first valid quote. Waiting for all healthy partners (bounded by min(2 s, remaining TTL)) finds the true lowest price rather than merely the fastest bookstore's price, at the cost of up to 2 seconds of extra latency when one partner is slow.
  • Relational DB for orders vs. append-only object storage for audit logs. Orders need ACID transactions and optimistic locking (conditional UPDATE ... WHERE status = :expected checks so two workers cannot act twice), whereas partner quote logs are ~15x larger (~5.5 TB/year vs. ~365 GB/year) and write-once, making cheap object storage + warehouse tables a better fit.

Common mistakes

  • Running partner fan-out and purchasing synchronously inside POST /v1/purchase, which ties entry-point availability to the slowest partner and leaves orphaned purchases when client HTTP connections time out.
  • Generating a fresh random UUID on every retry instead of deriving a deterministic idempotency key from (client_id, order_id, attempt_no), turning every lost HTTP response into a duplicate purchase.
  • Scheduling timeout reconciliation only inside an in-memory catch block instead of committing a durable RECONCILE_PARTNER timer in the same database transaction as the SENT attempt—if the worker crashes mid-request, the order stays stuck in PURCHASING forever.
  • Treating a timeout as a rejection and immediately ordering from the next bookstore or voiding the buyer's payment hold while the first bookstore may have fulfilled the order.
  • Using sleep(ttl_ms) inside a worker process for TTL expiration, which vanishes whenever workers restart or redeploy.
  • Waking all waiting orders at once on a price drop when a bookstore only has 2 copies in stock, stampeding the partner API with dozens of guaranteed-to-fail order calls.
  • Counting 404 Not Found or Out of Stock responses as failures in a circuit breaker, tripping the breaker and blacklisting a healthy bookstore just because an obscure ISBN is unavailable.
  • Logging raw partner payloads without redacting buyer PII (names and shipping addresses) in long-lived audit buckets.

Follow-up questions

  • What happens if a partner bookstore raises or lowers its price between your initial quote check and the final order confirmation? Treat every quote as a non-binding estimate and treat the partner's reservation or order confirmation as the source of truth. Whenever a partner API supports a two-step reserve hold or accepts a max_unit_price_cents guard field on POST /orders, use it so the bookstore itself locks the price or rejects a sudden hike. If a partner confirms at a changed price that is still at or below the buyer's max_price, accept it and capture that confirmed amount (which remains covered by our max_price * quantity authorization hold); if a partner ignores our limit and confirms above max_price, immediately trigger the saga's partner-cancel compensation, record both prices in the audit log, and try the next-best quote if TTL remains.
  • Suppose a partner vendor bills a non-refundable penalty on every rejected order attempt—how would you adapt partner selection and retries? Every failed POST /orders attempt now costs real money, so we eliminate blind attempts and price failure risk directly into partner selection. First, never resend POST /orders after a timeout before calling the free GET /orders lookup endpoint, pre-validate ISBN/address formats locally, and re-verify stock or place a free reserve hold right before ordering. Second, rank offers that meet max_price by expected_cost = unit_price * quantity + failed_txn_fee * p_fail(partner) (using each partner's rolling 24-hour order failure rate) so a $0.20 cheaper bookstore with a 20% failure rate loses to a reliable one, and cap fee-bearing attempts per order (say at 2) with a tighter circuit-breaker threshold on that partner.
  • How would you design a circuit breaker so your workers stop hammering a partner bookstore that is persistently throwing HTTP 500 errors? Give each partner adapter separate circuit breakers per endpoint (quote, place_order, get_order) with three states—CLOSED (normal traffic, tracking error rate over a 30-second sliding window), OPEN (fast-fail locally without network calls during a 30-second cooldown that doubles on repeated trips up to 5 minutes), and HALF_OPEN (let 3 probe requests through; close if all 3 succeed, reopen immediately if any fails)—counting only 5xx statuses and network timeouts as errors once volume exceeds a minimum sample (e.g., >= 20 calls and >= 50% failures in 30 s). While quote or place_order is OPEN, fan-out and selection skip that bookstore and log skipped: breaker_open to the audit trail, while get_order stays on its own independent breaker so we can still reconcile UNKNOWN in-flight orders. Sharing breaker state in Redis alongside a brief local cache lets all worker instances stop calling a broken partner within a second.

Follow-up questions

Similar questions

More Sentry.Io interview questions

All 1 Sentry.Io questions →