Order-Service — Order Creation From Cached Checkout & Checkout Saga
Responsibility
order-service turns a reviewed checkout quote into an immutable order, then drives that order through fulfillment.
- Order creation (
POST /api/v1/order) — resolvesshop-service’s cached checkout session exactly once, snapshots shipping/billing addresses intopii-service, generates a human-readable order code, and persists an immutableorderdocument. Idempotent: a retried submission with the sameidempotency_keyreturns the original order rather than creating a duplicate. - Checkout saga orchestration — a separate
cmd/workerTemporal-worker binary runsCheckoutSagaWorkflow, sequencing inventory reservation, payment, and shipment creation after the order is created; saga progress is tracked inorder_orchestrations, never on theorderdocument itself (which has nostatusfield). - Real-time saga progress —
GET /api/v1/order/:id/streamstreams saga progress to the client as Server-Sent Events, fed by a Pub/Sub → in-process-broker pipeline. - Order detail retrieval & order history/listing —
OrderQueryService.GetOrder/ListOrders(gRPC), consumed byshop-serviceto serve the mobile app’s My Orders list and Order Details screen.GetOrderreturns the same not-found result whether an order doesn’t exist or belongs to a different shopper in the same tenant (anti-enumeration by design);ListOrdersis unconditionally scoped to the caller’s own user ID. See SR-031. - Cancellation and refund are future scope.
Tech Stack
| Concern | Choice |
|---|---|
| Language | Go |
| Data store | MongoDB |
| REST framework | Echo |
| gRPC | Server (checkout saga signal RPCs) and client (pii-service, inventory-service, payment-service, shipment-service, tenant-service) |
| Workflow orchestration | Temporal — the sole Go host of a Temporal workflow/activity pair in this monorepo (no Rust/Node equivalent exists; see the platform’s cross-cutting principles) |
| Dependency injection | Uber Fx |
| Template | @templates/go-mongo-microservice, gRPC layer composed from @templates/go-grpc-microservice |
Ports
| Gateway | HTTP (host → container) | gRPC (host → container) | Service Name |
|---|---|---|---|
8000 (Nginx /order/api/v1/*) |
8093 → 8080 |
50061 → 50051 |
order-service |
50061→50051 serves PaymentSignalService/ShipmentSignalService (checkout saga webhook relays) and is also a gRPC client of pii-service, inventory-service, payment-service, shipment-service, and tenant-service.
Data Model — MongoDB
| Collection | Purpose |
|---|---|
order |
One immutable document per order — address references (never raw PII), shipment_options_shown[], selected_courier_id, price_summary (copied verbatim from the checkout session), payment_method, order_items[], the 5 mandatory audit fields. No status field — see below. |
order_code_counters |
Atomic per-tenant-per-year sequence producing ORD-{TENANT_CODE}-{YEAR}-{SEQ} order codes; {tenant_id}:{year} composite _id, FindOneAndUpdate + $inc + upsert, no read-then-write race. |
order_orchestrations |
The sole saga-state record — CurrentStep/SagaHistory, written by the Temporal worker’s activities. Never the order document itself. |
checkout_session (not owned by this service — read-only) |
shop-service’s own cache collection, read directly via this service’s already-injected MongoDB connection. See below. |
Why order has no status field. CreateOrder inserts the document only after every upstream step (address snapshotting, order-code generation) has already succeeded — there is no intermediate/partial state to track on the document itself. The REST response still reports a fixed status: "ORDER_CREATED" for client-contract compatibility; everything that happens after creation (inventory reservation, payment, shipment) is tracked in order_orchestrations.
Implementation Notes
PriceSummary is copied verbatim from the cached checkout session, never recomputed here. order_create_imp_svc.go persists snapshot.PriceSummary (shipping fee, cash-on-delivery charges, round-off, grand total included) exactly as shop-service last computed it — directly implementing SR-012 FR-12 and ADR-00025’s decision. Re-deriving free-delivery thresholds, cash-on-delivery surcharges, or rounding a second time here would risk this service’s logic drifting out of sync with shop-service’s and silently charging a different total than what the customer reviewed.
checkout_session read — a flagged, temporary direct-Mongo-access exception. This collection belongs to shop-service; order-service resolves it directly via its own already-injected *mongo.Database handle, since both services point at the same physical MongoDB server — no second client, no new env var. repository/checkoutsession/ bson-mirrors shop-service’s writer struct field-for-field by hand; nothing enforces the two staying in sync since they live in separate Go modules (tracked as TD-03). FindByToken filters on _id and tenant_id and created_user_id together, so a token can never resolve another tenant’s or shopper’s session. This is explicitly temporary — expected to move to a dedicated cache service (e.g. Redis) once that infrastructure exists — and is not a precedent for any other cross-service read, per SR-012 NFR-05.
Why this cache is MongoDB, not Redis. Reading checkout_session directly off a shared MongoDB connection (rather than through a dedicated cache-service API) is a direct consequence of a cost-conscious, staged decision: reuse the MongoDB server every service already depends on today, and move to a Redis-backed cache service once traffic or latency pressure justifies the new infrastructure. See ADR-00026 for the full rationale, including the same pattern already in production for OTP codes.
The checkout session’s real time-to-live is 1 hour, not 15 minutes. This file previously stated the TTL as 15 minutes; the authoritative value is shop-service’s CheckoutSessionTTL = 1 * time.Hour (checkoutsession_mapper.go:10), confirmed by shop-service’s own CLAUDE.md. Tracked and corrected as TD-02 — the implementation is authoritative over any module documentation that disagrees with it, per SR-012 NFR-08.
One mapped snapshot, reused for everything that needs it. At order-creation time, the resolved session is mapped exactly once into an in-memory CheckoutSessionSnapshot, then reused for the persisted order’s price/tax/warehouse fields, the PII-address-snapshot inputs, and the Temporal checkout-saga input — never re-derived separately per destination. This is the architectural core of SR-012 FR-11.
No raw address content ever persists in the checkout session or the order. The session stores only address references (an entity ID into pii-service’s encrypted attribute store); order-service resolves actual address content from pii-service at order-creation time, using the same generic attribute-store mechanism user-preference-service already uses to hydrate a saved address. The resolved content then feeds pii-service’s CreateAddressSnapshots — the order document itself only ever stores a {snapshot_id, type} reference, per SR-012 FR-14.
Address snapshot is created before the order insert, deliberately. A failed order insert after a successful PII snapshot leaves only a harmless, already-content-hash-deduplicated orphan snapshot; the reverse order would risk an order with no resolvable address — SR-012 NFR-07.
Idempotency is a storage guarantee, not just a service-level check. A unique, sparse Mongo index on idempotency_key is the real guarantee; the service-level FindByIdempotencyKey pre-check is a latency optimization only. A duplicate-key error from the insert triggers a re-fetch-and-return-existing-order fallback rather than failing the retried request — SR-012 FR-13, NFR-06.
Two binaries. cmd/api serves REST/gRPC; cmd/worker is a separate Temporal-worker process polling the checkout-saga task queue — without it, the saga is scheduled but nothing ever executes an activity. Saga signal RPCs (PaymentSignalService.SignalPaymentCaptured, ShipmentSignalService.SignalShipmentCreated) let payment-service’s and shipment-service’s webhook relays push a verified provider callback into the running saga.
Related Documents
- BRD-030 — My Orders, Order Details & Shipment Tracking
- SR-031 — My Orders, Order Details & Shipment Tracking: System Requirements
- ADR-00047 — Order Query and Tracking Channel Strategy for My Orders
- Architecture-00026 — My Orders, Order Details & Track Shipment Component Topology and Data Flow
- Technical Debt — My Orders, Order Details & Track Shipment Gaps
- BRD-015 — Payment Capture & Confirmation — the saga receives the
PaymentSignalService.SignalPaymentCapturedrelay this scopes - SR-016 — Payment Capture & Confirmation System Requirements
- BRD-013 — Checkout Completion: Real Payment Capture and Reliable Fulfillment Handoff
- SR-014 — Checkout Completion: Payment Capture & Fulfillment Handoff System Requirements
- BRD-016 — Payment Transaction Ledger, Refund Guarantee & Data Security — the saga’s
RefundPaymentActivitycompensation call is this document’s refund guarantee (BR-03) - SR-017 — Payment Transaction Ledger & Security System Requirements
- ADR-00028 — Append-Only, Webhook-Anchored Ledger vs. Synchronous or Mutable-Balance Alternatives for Payment Transaction Records
- Architecture — Payment Transaction Ledger, Refund Compensation & Gateway Audit Trail
- Technical Debt — Payment Transaction Ledger & Refund Audit Gaps
- BRD-011 — Reusable Product-to-Order Journey With Trustworthy Totals
- SR-012 — Reusable Checkout Orchestration: System Requirements
- ADR-00025 — Cached Checkout-Session Snapshot vs. Recompute at Order Creation
- ADR-00026 — MongoDB TTL Collection vs. Redis for the Checkout-Session Cache
- Architecture: Reusable Product-to-Order Orchestration
- Technical Debt — Reusable Checkout Orchestration Gaps
- shop-service
- pii-service
- payment-service
Full service reference: order-service/CLAUDE.md.