Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 37 ยท Real-World Projects

Project: E-commerce with Orders, Payments and Stock

Build a small e-commerce backend as four cooperating services behind a gateway, with a saga, events, idempotency and compensation, in one runnable Node file.

This project pulls the earlier chapters together. You will build the backbone of an online shop: a gateway that authenticates requests, an orders service that coordinates a purchase, an inventory service that owns stock, a payments service that owns money, and a notifications service that reacts to events. Each service keeps its own private data, and the only things they share are messages and small request/response contracts.

The program runs in one Node file, because the site cannot start four servers. That is the honest limit: everything below is plain functions in one process. To keep the behaviour realistic, calls between services go through a wire() helper that serialises data to JSON and back, so a service can never reach into another's objects. Moving each block into its own process is mostly a matter of replacing those calls with HTTP and the in-memory bus with a real broker (Synchronous Communication with HTTP APIs, Asynchronous Messaging and Events).

The design

Five parts

Gateway API keys, validation, routing.
Orders Owns orders. Runs the saga.
Inventory Owns stock and reservations.
Payments Owns wallets and charges.

Notifications is a fifth service that only listens to events.

1 / 2

The purchase flow is a saga (Sagas: Distributed Transactions Without 2PC), orchestrated by the orders service:

sequenceDiagram
    participant C as Client
    participant G as Gateway
    participant O as Orders
    participant I as Inventory
    participant P as Payments
    participant N as Notifications
    C->>G: POST /orders (API key)
    G->>O: place order
    O->>I: reserve stock
    I-->>O: ok
    O->>P: charge
    alt payment declined
        P-->>O: declined
        O->>I: release stock (compensation)
        O-->>N: OrderCancelled event
    else payment ok
        P-->>O: ok
        O-->>N: OrderConfirmed event
    end
    O-->>G: order result
    G-->>C: 201 or 409

The saga: stock is reserved first, and released again if the payment fails.

Why this order? Reserving stock is cheap to undo (put it back), while charging a card is costly to undo (a refund). Put the easily reversible step first and the hard-to-reverse one last, so the compensation path stays simple.

The complete program

Read the code top to bottom: bus and wire helper, then one block per service, then the gateway, then eight scenarios that exercise the interesting paths. The scenarios cover missing credentials, validation, a successful purchase, a retried request with the same idempotency key, an out-of-stock order, a payment failure (which triggers compensation), and access control on reads.

Node.js Four services, a gateway, a saga and events

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Study the output. The retried request (replayed: true) returned the same order 1 and charged nobody twice: stock and Ada's wallet show a single purchase (keyboard 5 to 3, mouse 1 to 0, wallet 500 to 315). Order 2 failed at the first saga step, so nothing needed to be undone. Order 3 passed the stock step, failed on payment, and the compensation put the monitor back: stock still shows monitor: 2. The event log has exactly one entry per outcome, and the notification service wrote its emails from events alone, knowing nothing about orders internals.

What is real and what is simulated

Real: the service boundaries, the saga order and compensation, idempotency keys, the gateway's responsibilities, the event-driven notifications, and the rule that each service owns its data. Simulated: the network (JSON round-trips inside one process), the broker (a loop that calls handlers), persistence (Maps in memory), and failure (nothing crashes). In production, each of these changes the story, which is what the next sections address.

What happens when a service crashes mid-saga?

The saga above runs inside one function call, so it cannot be interrupted halfway. In reality the orders process can die right after the inventory reserved stock but before payment was attempted. The reservation then stays forever and the item looks sold out.

Two fixes work together. First, persist the saga state (an orders row with status pending) so a recovery job can find unfinished orders and either continue or compensate them. Second, give reservations a time to live: stock held for an order that never completes is released automatically. The stand-in below shows the second mechanism with a virtual clock, so the timing is deterministic.

Node.js Expiring reservations with a reaper job

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Order A was confirmed in time and kept its stock. Order B's service crashed after holding three keyboards; the early reaper run at t=10 left it alone (not expired), and the run at t=31 gave the stock back, so order C could buy it. A real implementation stores the expiry in the inventory database and runs the reaper on a schedule.

Extending the project

Try these changes, in this order, to practise what you learned:

  1. Pricing in its own service. Move catalog out of orders into a catalog service. Decide what orders stores: a copy of the price at purchase time (it should!) or a reference.
  2. Make the bus unreliable. Let some handlers throw and add retries with backoff (Timeouts, Retries and Exponential Backoff); the notifications service must then handle duplicates.
  3. Use the outbox. Publishing OrderConfirmed after the order row changes is a dual write; fix it with The Transactional Outbox and Idempotent Consumers.
  4. Add a circuit breaker around payments (Circuit Breakers, Bulkheads and Fallbacks) and decide what the shop does when payments is down: queue the order, or refuse it with a clear message.
  5. Add contract tests between orders and payments (Testing Microservices).

Design decisions such as "reserve before charging" belong in the design notes next to the code. Future teammates will otherwise reverse them without knowing why.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the saga reserve stock before charging the customer?

    Ordering steps so the hard-to-reverse one comes last keeps the compensation path simple.
  2. 2. What did the repeated request with the same Idempotency-Key do?

    The orders service remembers the key and replays the stored result, so retries by clients are safe.
  3. 3. Which data does the notifications service use to send emails?

    Services own their data. Notifications works purely from events, so orders can change internally without breaking it.
  4. 4. Why give stock reservations an expiry time?

    A crashed saga would otherwise leave items reserved forever; an expiry plus a reaper job heals it.

Summary

  • Each service owns its data and exposes a small contract; the gateway handles authentication, validation and routing.
  • The orders service runs an orchestrated saga: reserve stock, charge, confirm, and compensate when a step fails.
  • Idempotency keys make client retries safe; idempotent service operations make internal retries safe.
  • Events let notifications (and later loyalty, analytics) react without orders knowing about them.
  • Crashes mid-saga need persisted state, expiring reservations and recovery jobs, which the single-process demo only hints at.

Next: Project: Event-Driven Notification System.