Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 40 ยท Cart and Checkout

The Order Lifecycle and State Machines

Model e-commerce orders with explicit states and legal transitions. Learn separate payment and fulfillment statuses, event history and order snapshots.

An order is not a row you insert once. It is a long-lived record that changes for days or months: it gets paid, packed, shipped, partly returned, maybe refunded. The code that changes it is spread across many places: a checkout request, a payment webhook, a warehouse integration, an admin screen, a customer support tool. If each place sets a status column however it likes, you will eventually ship unpaid orders and refund cancelled ones.

The cure is to treat the order as a state machine: a fixed set of states, a fixed set of legal transitions, and a single place in the code that enforces them. This lesson shows how to design that, why one "status" is rarely enough, and how to keep an honest history. The order is created from a cart when checkout completes.

One status is not enough

A single status field tries to describe three different stories at once:

  • Order state: is the order still open, finished, or cancelled?
  • Payment state: unpaid, authorized, paid, partly refunded, refunded?
  • Fulfillment state: not shipped, partly shipped, shipped, delivered, returned?

Cramming these into one list creates values such as paid_partially_shipped_refund_requested. The combinations multiply and nobody can reason about them.

Instead, give the order several independent status fields:

Field Typical values
status (lifecycle) open, completed, cancelled
payment_status pending, authorized, paid, partially_refunded, refunded, failed
fulfillment_status unfulfilled, partially_fulfilled, fulfilled, returned

Each field has its own small state machine, and some rules connect them: you cannot complete an order that is unpaid, and you cannot fulfill a cancelled order. Many platforms use exactly this split. Payments get their own deeper model in Authorization, Capture, Refunds and Chargebacks, and shipping in Fulfillment, Returns and Refunds.

A simple state machine

Start with the lifecycle a small shop might use:

stateDiagram-v2
    [*] --> pending
    pending --> paid: payment succeeds
    pending --> cancelled: cancel or expire
    paid --> fulfilled: all items shipped
    paid --> refunded: full refund
    paid --> cancelled: cancel and refund
    fulfilled --> refunded: return and refund
    cancelled --> [*]
    refunded --> [*]
    fulfilled --> [*]

Each arrow is a legal transition. Anything not drawn, such as cancelled to paid, is forbidden.

Writing the machine down as data has three benefits: you can see every legal move at a glance, tests can walk the whole table, and the code that applies a change has one rule: look up the current state, and refuse if the target is not listed.

Transitions are triggered by events

States do not change by themselves. Something happens: the payment provider sends a webhook, a worker marks a parcel as shipped, a support agent clicks cancel. Name these events (payment_succeeded, shipment_created, cancel_requested) and let the machine decide what each does in each state.

This makes it easy to handle messy reality:

  • Duplicates. A webhook can arrive twice. If payment_succeeded hits an order that is already paid, it should be a harmless no-op, not an error and not a second payment record (Webhooks and Signature Verification).
  • Out-of-order events. A "refunded" event can arrive before "paid" is processed. Decide whether to queue it, retry later, or record it and reconcile.
  • Illegal events. An admin tries to cancel a shipped order. The machine rejects it with a clear error, and the interface can offer "create a return" instead.

Keep a history, not only the latest state

The current status answers "where is the order now?". Support, finance and fraud teams also need "how did it get here, and who did it?". Write an append-only history every time something changes:

  • the order id,
  • the old and new state,
  • the event name,
  • a timestamp,
  • the actor (customer, system, staff member id),
  • an optional note or reference, such as a payment id.

Never edit or delete history rows. If something was done by mistake, add a new row that corrects it. This gives you an audit trail for disputes and makes bugs much easier to trace.

The same list of facts can drive timeline views ("Packed on Tuesday") and customer emails (Transactional Email and Customer Lifecycle).

Snapshots at order time

Everything that determined the price and the contents of the order must be copied into the order at creation, not looked up later:

  • product title, SKU and options at the time of purchase,
  • unit price, discounts applied and the tax rates used,
  • shipping method name and cost,
  • billing and shipping address (as text, not a pointer to a customer address that may be edited),
  • currency and, for foreign currency, the exchange rate used,
  • the terms and policies shown.

If the order only stored product_id, then renaming a product, changing its price or deleting it would rewrite history and break invoices and refunds. Store references for navigation and snapshots for truth.

A runnable state machine

The Python example below encodes the legal transitions as a dictionary, applies events through one function, records history, and rejects illegal moves. It treats a repeated event as a no-op, which is the behavior you want for duplicate webhooks.

Python An order state machine with history

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 input()), it gets the next line from this box.

In a real database you would run the transition inside a transaction, lock the order row (or use a version column for optimistic locking) so two events cannot interleave, and store the processed event ids in a table with a unique index.

Separate machines for payment and fulfillment

Now extend the idea. The order keeps three small machines, and the checks between them live in one place. This second example shows payment_status and fulfillment_status evolving independently, with a rule that you cannot ship an unpaid order and that an order is completed only when it is both paid and fulfilled:

Python Independent payment and fulfillment states

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 input()), it gets the next line from this box.

Notice that status here is derived from the other two fields. Derived values cannot disagree with their sources, which is the same idea as computing a cart total from its lines.

Design checklist

  • List the states and the legal transitions in one table before writing code.
  • Make transitions go through one function or class. No other code sets the status.
  • Make every event idempotent, using an event id or a natural key.
  • Lock the order (row lock or version) while transitioning.
  • Append to a history table in the same transaction as the change.
  • Trigger side effects (emails, stock release, accounting) from committed state changes, using a queue or an outbox (Idempotency and Reliable Payments).
  • Give staff tools only for legal transitions. Provide an audited override path rather than a free-form status dropdown.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why do many shops keep separate payment and fulfillment statuses?

    An order can be paid but not shipped, or partly shipped and partly refunded. Independent fields avoid a combinatorial explosion of single status values.
  2. 2. A payment webhook for the same event arrives twice. What should the order do the second time?

    Webhook delivery is at-least-once. Recording processed event ids lets the second delivery change nothing.
  3. 3. Which data should be copied into the order at creation?

    Later catalog or address edits must not rewrite a past order. Snapshots keep invoices, refunds and disputes accurate.
  4. 4. How should corrections to the status history be made?

    History is append-only so it works as an audit trail. Mistakes are fixed by adding more history, not erasing it.

Summary

  • Model an order as state machines with explicit states, events and legal transitions in one table.
  • Keep lifecycle, payment and fulfillment as separate statuses and derive combined views.
  • Make events idempotent, handle duplicates and out-of-order delivery deliberately, and lock the order while changing it.
  • Append-only history records who changed what, when and why.
  • Snapshot prices, taxes, titles and addresses on the order so the past never changes.

Next, look at the money side in detail: How Online Payments Work.