0
0
LLDsystem_design~7 mins

Order tracking state machine in LLD - System Design Guide

Choose your learning style9 modes available
Problem Statement
When an order moves through multiple stages like placement, payment, shipping, and delivery, tracking its current state can become confusing and error-prone. Without a clear system, the order might jump to invalid states or miss important transitions, causing customer frustration and operational mistakes.
Solution
A state machine defines all valid states an order can be in and the allowed transitions between them. It enforces rules so the order can only move from one valid state to another, preventing invalid changes. This makes tracking order progress reliable and easier to manage.
Architecture
Placed
Cancelled

This diagram shows the order states as boxes and arrows as allowed transitions between states.

Trade-offs
✓ Pros
Prevents invalid order state transitions, reducing bugs.
Makes order flow explicit and easier to understand.
Simplifies debugging by knowing exactly which states are possible.
Facilitates adding new states or transitions in a controlled way.
✗ Cons
Adds complexity to simple order flows with few states.
Requires upfront design and maintenance of state rules.
Can be rigid if business processes change frequently.
Use when order processing involves multiple distinct stages and transitions, especially if state validation or complex flows are needed. Suitable for systems handling thousands of orders daily.
Avoid if order processing is very simple with only one or two states, or if the system is a prototype where flexibility is more important than strict state control.
Real World Examples
Amazon
Amazon uses order state machines to track orders from placement through payment, packaging, shipping, and delivery, ensuring customers see accurate status updates.
Uber Eats
Uber Eats tracks food orders through states like placed, accepted by restaurant, prepared, picked up by driver, and delivered, preventing invalid status updates.
Shopify
Shopify implements order state machines to manage order lifecycle events and trigger notifications or actions at each valid state transition.
Code Example
The before code allows any status update, risking invalid states. The after code defines allowed transitions and raises an error if an invalid move is attempted, enforcing correct order state flow.
LLD
### Before: No state machine, just free status updates
class Order:
    def __init__(self):
        self.status = 'placed'

    def update_status(self, new_status):
        self.status = new_status


### After: Using a state machine to enforce valid transitions
class OrderStateMachine:
    allowed_transitions = {
        'placed': ['paid', 'cancelled'],
        'paid': ['shipped', 'cancelled'],
        'shipped': ['delivered'],
        'delivered': [],
        'cancelled': []
    }

    def __init__(self):
        self.state = 'placed'

    def transition(self, new_state):
        if new_state in self.allowed_transitions[self.state]:
            self.state = new_state
        else:
            raise ValueError(f"Invalid transition from {self.state} to {new_state}")


# Usage
order = OrderStateMachine()
order.transition('paid')  # valid
order.transition('shipped')  # valid
# order.transition('placed')  # raises error
OutputSuccess
Alternatives
Event-driven architecture
Instead of enforcing strict states, the system reacts to events and updates order status accordingly without a fixed state model.
Use when: Choose when order flows are highly dynamic or when integrating many external systems that emit events asynchronously.
Simple status flags
Use a single status field updated freely without enforced transitions.
Use when: Choose when order processing is very simple and strict state validation is not required.
Summary
Order tracking state machines prevent invalid state changes by defining allowed transitions.
They make order flows explicit and easier to maintain or extend.
They are best used when order processing involves multiple stages and strict validation is needed.