Architecture-00014 — Checkout Saga Orchestration Pattern & Audit Trail

By Engineering Team•October 8, 2026•7 min read

Metadata

System order-service (saga workflow host), consumed by shop-service/ui-application/ui-admin-application indirectly via order creation
Document ID Architecture-00014
Author Engineering Team
Status Approved / Implemented

This document covers: (a) the saga pattern’s own mechanics — how CheckoutSagaWorkflow structures steps, retries, timeouts, and compensation; (b) the order_orchestrations/SagaHistory audit-trail mechanism that turns the saga’s execution into a queryable statement of record; (c) order_status, the separate customer-facing order-lifecycle timeline; (d) the SSE/Pub/Sub channel that projects live saga progress to a connected client; (e) the cmd/api-vs-cmd/worker Temporal client/server topology — which process starts/signals a run versus which one actually executes it; and (f) the end-to-end request flow this all adds up to, across the happy path and its main failure scenarios. It deliberately does not re-describe the payment-capture-specific request/response flow already covered end-to-end by Architecture-00012, nor the payment-ledger/refund audit trail covered by Architecture-00013 — this doc sits one level up from both, at the level of the orchestration pattern itself and the generic step-by-step audit record it produces for any step, not just payment.


Diagram

Checkout saga pattern — distributed transaction coordination


Components

Component Role in the saga pattern
order-service (cmd/api) The HTTP/gRPC-facing process. OrderController.Create schedules CheckoutSagaWorkflow on order creation (POST /api/v1/order) via temporalClient.ExecuteWorkflow and returns 201 Created immediately — the HTTP request never blocks on the saga’s own completion. Also hosts the PaymentSignalService/ShipmentSignalService gRPC servers, the SSE endpoint (GET /api/v1/order/:id/stream), and the Pub/Sub receiver for saga progress events. Holds its own Temporal client, used only to start workflows (ExecuteWorkflow) and send signals (SignalWorkflow) — it never executes workflow or activity code itself.
order-service (cmd/worker) A separate binary/process, the only one that actually executes saga logic. Runs the Temporal Worker SDK polling task queue checkout-queue (domainchekoutsaga.TaskQueue) — the saga cannot execute a single step without this process running, per ADR-00034. Holds its own Temporal client (used by the Worker SDK to poll/dispatch, not to start or signal workflows), registers CheckoutSagaWorkflow, LatePaymentReconciliationWorkflow, and every exported method on *activity.Activities. Hosts the Pub/Sub publisher for saga progress events.
CheckoutSagaWorkflow The workflow definition itself — the single coordinator function that sequences every step and decides every compensation branch, per ADR-00033. Executes exclusively inside cmd/worker.
LatePaymentReconciliationWorkflow A second, independently-registered workflow (same cmd/worker process) that re-runs the reservation→shipment→consume sequence for a payment_captured signal that arrives after CheckoutSagaWorkflow has already closed past its 15-minute window — started under a distinct deterministic ID (checkout-saga-reconcile-<orderID>), never colliding with the original run’s ID.
Activities (ReserveInventoryActivity, CreatePaymentOrderActivity, CreateShipmentActivity, ConsumeInventoryActivity, ReleaseInventoryActivity, RefundPaymentActivity) Individually retried units of work — each one an RPC call out to inventory-service, payment-service, or shipment-service, wrapped in defaultActivityOptions’ RetryPolicy{MaximumAttempts: 3}. Every outbound call is wrapped with withAuthMetadata, injecting tenant_id/user_id/role as gRPC metadata, per the platform’s security contract (.claude/rules/06-security.md).
PaymentSignalService / ShipmentSignalService (gRPC, served by order-service’s cmd/api, port 50051) The addressable wake-up surface. payment-service’s Razorpay webhook handler calls SignalPaymentCaptured; shipment-service’s flow calls SignalShipmentCreated. Both are thin gRPC delegates to CheckoutSagaService, which calls temporalClient.SignalWorkflow(ctx, "checkout-saga-"+orderID, "", <signalName>, signal) from inside cmd/api — the call is issued from the API process but is routed by the Temporal server to whichever workflow instance is actually suspended waiting for it inside cmd/worker.
order_orchestrations (MongoDB collection) The saga’s own internal execution bookkeeping — one document per order’s saga, holding CurrentStep/StepStatus/Attempts/LastError and the full ordered SagaHistory array. Written only from cmd/worker’s activities.
order_status (MongoDB collection) A separate, customer-facing order-lifecycle timeline — status (coarse state) plus an append-only process_status[] array of fine-grained states (ORDER_PLACED, PAYMENT_PROCESSING, SHIPMENT_CREATION_FAILED, etc.). Seeded at order creation (cmd/api) and appended to from the workflow’s recordOrderStatus helper (cmd/worker). See Section C below — this is a distinct collection from order_orchestrations, not an alias for it.
AppendStepTransitionActivity The one mechanism that writes to order_orchestrations’ SagaHistory — called at every step transition, success or failure, never mutating the immutable order document itself.
OrderStreamEventPublisher / Pub/Sub topic order-saga-events / RegisterOrderStreamEventReceiver / OrderStreamBroker The SSE delivery chain. PublishOrderStreamEventActivity (in cmd/worker) publishes a MessageEnvelope[Event] to a real Google Cloud Pub/Sub topic; cmd/api’s receiver subscribes and forwards each message into an in-process, per-order fan-out broker; the SSE handler reads off that broker. See Section D below.

A. The saga pattern — step sequence, retries, and timeouts

CheckoutSagaWorkflow(ctx workflow.Context, input domainchekoutsaga.CheckoutSagaInput) (*CheckoutSagaResult, error) runs the checkout transaction as one linear sequence of activity calls, each wrapped in the same defaultActivityOptions:

defaultActivityOptions = workflow.ActivityOptions{
    StartToCloseTimeout: 30 * time.Second,
    RetryPolicy:         &temporal.RetryPolicy{MaximumAttempts: 3},
}
  1. ReserveInventoryActivity — reserves stock for every line item. A failure here ends the saga immediately; nothing has been charged or shipped yet, so no compensation is needed.
  2. CreatePaymentOrderActivity — creates the Razorpay order via payment-service. A failure here triggers releaseInventory (the inventory reservation from step 1 is undone) before the saga ends.
  3. Wait for payment capture — the workflow blocks on a workflow.NewSelector racing two branches: a payment_captured signal (delivered via PaymentSignalService.SignalPaymentCaptured, triggered by payment-service’s Razorpay webhook handler) against a durable workflow.NewTimer(paymentWaitTimeout), where paymentWaitTimeout = 15 * time.Minute. If the timer fires first, the saga treats the checkout as abandoned and runs the same releaseInventory compensation as step 2’s failure path.
  4. executeCreateShipment — once payment is confirmed captured, creates the shipment via shipment-service. A failure here is the saga’s most consequential failure mode: payment has already been captured, so compensation must run both refundPayment and releaseInventory together — a concrete example of why ADR-00033 treats this as something only a coordinator with full transaction context can decide correctly.
  5. consumeInventory — a best-effort step converting the earlier reservation into an actual stock deduction, run after shipment creation succeeds.
  6. StepCompleted — the terminal, successful state.

A background goroutine, listenForLateShipmentConfirmation, keeps listening for a shipment_created signal that might arrive after the workflow has already moved past the point it was waiting for one — a duplicate or delayed signal is logged and reconciled against CurrentStep rather than silently dropped or double-processed.

Compensation functions (releaseInventory, refundPayment) are themselves just further activity calls — not a special workflow construct — called explicitly by name, in explicit order, from whichever failure branch needs them. This is the concrete shape of the “saga pattern”: forward steps and compensating steps are both ordinary activities, and the workflow function’s own control flow is the single place that decides which one runs when.


B. The audit-trail mechanism — order_orchestrations and SagaHistory

Every step transition — not just failures — is recorded via AppendStepTransitionActivity, which appends one entry to the saga’s order_orchestrations document:

type SagaHistoryEntry struct {
    Step      string
    Status    string
    Timestamp time.Time
    Metadata  map[string]string
}

type OrderOrchestration struct {
    ID, TenantID, OrderID, WorkflowID, RunID       string
    CurrentStep, StepStatus                         string
    Attempts                                        int
    LastError                                        string
    SagaHistory                                     []SagaHistoryEntry
    CreatedUserID, UpdatedUserID                    string
    CreatedAt, UpdatedAt                            time.Time
}

Step constants (StepReserveInventory, StepProcessPayment, StepCreateShipment, StepReleaseInventory, StepConsumeInventory, StepRefundPayment, StepCompleted, StepLatePaymentReconciliation) and status constants (StepStatusInProgress, StepStatusCompleted, StepStatusFailed) give every SagaHistory entry a small, closed vocabulary — a reader (or a future reconciliation job) never has to interpret a free-text status string.

Why this satisfies the audit requirement directly:

  • One document per order, one ordered array, no correlation needed. order_orchestrations is keyed by OrderID, and SagaHistory is already in chronological order — reconstructing “what happened to this order’s checkout” is reading one array, not joining logs across inventory-service, payment-service, and shipment-service independently.
  • The record is separate from the order itself. order_orchestrations is a dedicated collection, distinct from the immutable order document — the saga’s own bookkeeping (attempt counts, in-progress markers, transient failures that were later retried successfully) never leaks into or mutates the customer-facing order record.
  • Reconciliation reads the same record it writes to. reconcileLatePaymentCapture and listenForLateShipmentConfirmation both work by reading CurrentStep/SagaHistory off the same order_orchestrations document AppendStepTransitionActivity writes to — there is no separate “state” to keep in sync with the “history.”
  • Every write carries the standard five audit columns. order_orchestrations follows the platform-wide mandatory audit-fields contract (tenant_id, created_user_id, updated_user_id, created_at, updated_at) like every other collection in this monorepo — TenantID is never omitted from a saga record, consistent with the platform’s multi-tenancy rule.

Relationship to Temporal’s own execution history. Temporal’s server independently persists a full workflow execution history (every activity attempt, retry, and signal received) for its own crash-recovery and replay purposes — see ADR-00034. order_orchestrations’ SagaHistory is a separate, deliberately simplified, business-facing projection of “what happened to this order” — queryable directly from MongoDB by any service or support tool without needing access to (or familiarity with) the Temporal cluster itself. The two are complementary, not duplicates: one is the SDK’s own replay mechanism, the other is this platform’s audit/statement-of-record for a human or another service to read.


C. order_status — the customer-facing order-lifecycle timeline (distinct from order_orchestrations)

order_orchestrations (Section B) is the saga’s own internal bookkeeping — step names, attempt counts, errors — meant for engineering/support diagnosis of the coordination mechanism itself. order_status is a separate MongoDB collection holding the order-lifecycle timeline a customer-facing surface would actually render:

type OrderStatus struct {
    ID, TenantID, OrderID, UserID   string
    Status                          string   // coarse current state
    StatusUpdatedAt                 time.Time
    ProcessStatus                   []ProcessStatusEntry   // append-only fine-grained timeline
    CreatedUserID, UpdatedUserID    string
    CreatedAt, UpdatedAt            time.Time
}

type ProcessStatusEntry struct {
    Status    string
    Reason    string
    UpdatedAt time.Time
}

ProcessStatus is drawn from the same closed-vocabulary discipline as SagaHistory: ORDER_PLACED, INVENTORY_RESERVED, PAYMENT_PROCESSING, PAYMENT_COMPLETED, SHIPMENT_PROCESSING, SHIPMENT_PICKED, SHIPMENT_IN_TRANSIT, SHIPMENT_OUT_FOR_DELIVERY, SHIPMENT_DELIVERED, INVENTORY_RELEASED, PAYMENT_REFUNDED, and the failure variants INVENTORY_RESERVATION_FAILED/PAYMENT_FAILED/SHIPMENT_CREATION_FAILED/PAYMENT_REFUND_FAILED/INVENTORY_RELEASE_FAILED.

Two write sites, two different processes:

  • OrderCreateService.CreateOrder (cmd/api) seeds ORDER_PLACED synchronously, as part of the same request that creates the order document and starts the saga.
  • CheckoutSagaWorkflow’s recordOrderStatus helper (cmd/worker) appends every subsequent entry — PaymentProcessing, PaymentCompleted, ShipmentProcessing, and every failure variant — at the same points the workflow is already deciding order_orchestrations’ SagaHistory transitions, but written to the separate collection.

Keeping these as two collections, not one, means a UI or support tool reading “what is this order’s status” never has to understand saga-internal concepts (workflow IDs, attempt counts, Temporal-specific error strings) — it reads a vocabulary scoped to what a customer or operator actually needs to know. Both collections carry the platform’s standard five audit columns independently.


D. Real-time progress — SSE, Pub/Sub, and the in-process broker

A client that wants live checkout progress opens GET /api/v1/order/:id/stream against order-service’s cmd/api. This is a separate channel from the saga itself — the saga runs to completion in cmd/worker regardless of whether any client is listening; the stream only delivers a view of it.

Delivery chain, end to end:

  1. Publish (cmd/worker) — at each meaningful workflow transition, the workflow calls a publishEvent helper, which invokes PublishOrderStreamEventActivity. This activity calls OrderStreamEventPublisher.Publish, a real Google Cloud Pub/Sub client, which marshals a message.MessageHeader{TenantID, CorrelationID, TraceParent} + Event envelope to JSON and publishes it to topic order-saga-events (PUBSUB_TOPIC_ORDER_SAGA_EVENTS).
  2. Receive (cmd/api) — RegisterOrderStreamEventReceiver subscribes to PUBSUB_SUBSCRIPTION_ORDER_SAGA_EVENTS and, on every message, calls broker.Publish(event.OrderID, event) — pure forward, no persistence at this hop.
  3. Fan-out (OrderStreamBroker, in-process, cmd/api) — a mutex-guarded map[orderID]map[chan Event]struct{}. Each SSE subscriber gets its own buffered channel (chan Event, capacity 8); publishing to a subscriber is non-blocking (select/default) so one slow or disconnected SSE client can never stall the shared Pub/Sub receive loop or any other subscriber.
  4. Stream (OrderStreamController.Stream → OrderStreamService.StreamEvents) — on connect, the service first checks for a catch-up condition (ResolveCatchUpEvent, reading order_orchestrations via FindByOrderID — handles the case where the saga already reached a terminal state before the client connected at all), then falls through to broker.Subscribe(orderID) for live events. A select loop writes data: <json>\n\n for each real event, or a bare : heartbeat\n\n comment line every 15 seconds (heartbeatInterval) to keep the connection alive through intermediate proxies/load balancers.

Event types (closed set, mirrors the workflow’s own decision points): payment_ready (after payment order creation succeeds), payment_captured (after the signal is received), shipment_created (after shipment creation succeeds, or after a late/duplicate webhook confirmation arrives post-success), saga_failed (at every compensation branch), plus a synthetic heartbeat that is never published to Pub/Sub — it exists only inside the SSE write loop itself.

This channel is best-effort by design. PublishOrderStreamEventActivity always returns nil, even if the Pub/Sub publish itself fails (the error is logged, never propagated) — a dropped progress event can never fail, retry, or stall the saga. order_orchestrations (and, for the customer-facing view, order_status) remain the sole authoritative state; SSE is a convenience projection on top, not a source of truth. A client that never connects, disconnects mid-saga, or misses an event can always reconstruct the true current state by querying the order and its status directly — nothing is only knowable through the stream.


E. Temporal client/server topology — who talks to whom

Two separate order-service processes each hold their own Temporal client, used for entirely different purposes:

Process Temporal client used for Never does
cmd/api ExecuteWorkflow (start a new saga run on order creation), SignalWorkflow (deliver payment_captured/shipment_created into a running instance, from the gRPC signal servers) Never executes workflow or activity code — it only starts and signals runs that execute elsewhere
cmd/worker The Temporal Worker SDK’s own polling/dispatch of task queue checkout-queue Never starts a saga on its own initiative — it only executes work the server hands it once cmd/api has scheduled it

Both processes connect to the same Temporal server/cluster, which is the actual intermediary for every cross-process interaction described above — cmd/api never talks to cmd/worker directly, by RPC or otherwise. ExecuteWorkflow and SignalWorkflow are both calls to the Temporal server; the server is what matches a SignalWorkflow call to the correct, currently-suspended workflow execution (keyed by the deterministic workflow ID "checkout-saga-" + orderID), and what hands queued work to whichever worker instance polls checkout-queue next.

This split is why cmd/worker must be running for the saga to make any progress at all (per ADR-00034’s NFR-01), while cmd/api alone is sufficient to accept new orders and relay webhook signals — those two responsibilities fail independently, not as a single point of failure.


F. End-to-end flow, step by step

Matches the numbered flow in the diagram above.

Happy path

  1. Client sends POST /api/v1/order. OrderController.Create → OrderCreateService.CreateOrder: idempotency check, resolve checkout session, resolve address snapshots via pii-service, generate order code, persist the order document, seed order_status with ORDER_PLACED.
  2. CreateOrder calls CheckoutSagaService.StartSaga: temporalClient.ExecuteWorkflow(...) schedules CheckoutSagaWorkflow under workflow ID checkout-saga-<orderID> (this only enqueues the run — it does not execute anything yet), then synchronously writes the initial order_orchestrations document (StepReserveInventory/IN_PROGRESS).
  3. OrderController.Create responds 201 Created immediately. No part of this response waited on any saga activity.
  4. The client separately opens GET /api/v1/order/:id/stream for live progress.
  5. cmd/worker’s poller picks up the scheduled run. CheckoutSagaWorkflow executes ReserveInventoryActivity → inventory-service, then CreatePaymentOrderActivity → payment-service; on success it records the step transition, writes order_status: PAYMENT_PROCESSING, and publishes payment_ready (→ Pub/Sub → cmd/api’s receiver → broker → SSE: data: {"type":"payment_ready",...}).
  6. The workflow blocks on waitForPaymentCaptured, racing the payment_captured signal channel against a 15-minute durable timer.
  7. The customer completes payment on the Razorpay side; payment-service’s webhook handler calls order-service’s gRPC PaymentSignalService.SignalPaymentCaptured (cmd/api, port 50051) → CheckoutSagaService.SignalPaymentCaptured → temporalClient.SignalWorkflow(..., "payment_captured", ...). The Temporal server routes this into the specific suspended workflow instance in cmd/worker.
  8. The selector’s signal branch fires: the workflow records the transition, writes order_status: PAYMENT_COMPLETED, and publishes payment_captured (→ SSE).
  9. executeCreateShipment runs CreateShipmentActivity → shipment-service; on success it writes order_status: SHIPMENT_PROCESSING and publishes shipment_created (→ SSE).
  10. ConsumeInventoryActivity runs best-effort (never fails the workflow regardless of outcome); the workflow records StepCompleted/COMPLETED and returns.

Scenario — payment never captured (15-minute timeout)

The durable timer branch fires before any signal arrives: the workflow compensates with ReleaseInventoryActivity, records StepProcessPayment/FAILED in order_orchestrations, writes order_status: PAYMENT_FAILED (reason "timeout"), and publishes saga_failed (→ SSE). The workflow then returns, closing the run. If the webhook signal still arrives afterward (a late or delayed Razorpay callback), SignalWorkflow returns a not-found error because the run has already closed; CheckoutSagaService catches this and falls back to LatePaymentReconciliationService.Reconcile, which starts LatePaymentReconciliationWorkflow under a distinct ID (checkout-saga-reconcile-<orderID>). That workflow re-attempts ReserveInventoryActivity; if stock is no longer available, it refunds the payment via RefundPaymentActivity and records the outcome as "refunded"; if stock is still available, it proceeds through shipment creation and inventory consumption and records "reconfirmed_and_shipped".

Scenario — shipment creation fails after payment was already captured

Inside executeCreateShipment (shared by both workflows), CreateShipmentActivity fails. Because payment has already been captured, the workflow must undo two prior steps, in order: RefundPaymentActivity first, then ReleaseInventoryActivity. It records StepCreateShipment/FAILED in order_orchestrations, writes order_status: SHIPMENT_CREATION_FAILED, and publishes saga_failed (→ SSE) before returning. This is the concrete case ADR-00033 argues only a single coordinator holding full transaction context can decide correctly — the decision to run both compensations, in that specific order, depends on knowing both prior steps already succeeded.

Scenario — a duplicate/late shipment_created webhook after the saga already completed

A background listener (listenForLateShipmentConfirmation, started at the top of the workflow) keeps watching the shipment_created signal channel even after the main sequence has moved past it. A duplicate or delayed delivery is reconciled against CurrentStep rather than reprocessed, and still publishes a shipment_created SSE event (tagged source: "webhook_confirmation") so a still-connected client sees the final confirmation even if it arrived after the workflow’s own happy-path step already published one.


Why this is reliable

  • The workflow function is the one place the full step sequence and every compensation branch are defined — understanding what can happen to a checkout means reading one function, not reconstructing behavior scattered across three services’ independent event handlers (see ADR-00033).
  • Retries, the payment-wait timeout, and crash recovery are SDK-guaranteed, not bespoke application logic — a worker restart mid-saga resumes from Temporal’s own persisted history rather than losing track of progress (see ADR-00034).
  • SagaHistory is append-only and keyed by a closed set of step/status constants — there is no free-text drift between what actually happened and what the audit record says happened.
  • Dual compensation (refundPayment + releaseInventory) is an explicit, testable branch in the workflow’s own code, not an inferred reaction two independent services would each have to separately arrive at.
  • The real-time SSE channel is strictly best-effort and cannot affect saga correctness. PublishOrderStreamEventActivity always returns success even if the underlying Pub/Sub publish fails — a lost progress notification never retries, never blocks, and never fails the workflow; order_orchestrations and order_status stay authoritative regardless of whether any client was ever listening.
  • Internal saga bookkeeping and the customer-facing status timeline are two different collections, not one dual-purpose one. order_orchestrations can accumulate saga-internal detail (attempt counts, Temporal error strings) without ever leaking into what a customer-facing surface reads from order_status, and vice versa.
  • Starting and executing a workflow run are deliberately split across two processes (cmd/api, cmd/worker), both talking only to the Temporal server, never to each other directly — cmd/api stays able to accept new orders and relay webhook signals even if cmd/worker is temporarily down (those runs simply queue until a worker resumes polling), rather than the two being a single combined point of failure.