0
0
LLDsystem_design~7 mins

Order state machine in LLD - System Design Guide

Choose your learning style9 modes available
Problem Statement
Without a clear control of order states, systems can process orders incorrectly, causing issues like shipping canceled orders or accepting payments for already delivered items. This leads to inconsistent order handling, customer dissatisfaction, and operational errors.
Solution
An order state machine enforces valid transitions between order states by defining allowed moves explicitly. It ensures the order progresses through states like 'Created', 'Paid', 'Shipped', and 'Delivered' in a controlled manner, preventing invalid or out-of-sequence actions.
Architecture
Created
Paid
Canceled

This diagram shows the allowed states of an order and the valid transitions between them, including payment, shipping, delivery, cancellation, and return.

Trade-offs
✓ Pros
Prevents invalid order state transitions, reducing errors.
Makes order processing logic explicit and easier to maintain.
Improves system reliability by enforcing business rules.
Facilitates debugging by clearly showing allowed state flows.
✗ Cons
Adds complexity to the order processing codebase.
Requires careful design to cover all valid transitions.
May need updates when business rules change, increasing maintenance.
Use when order processing involves multiple states with strict rules, especially in e-commerce systems handling thousands of orders daily.
Avoid if the order lifecycle is very simple (e.g., only 'Created' and 'Completed') or if the system handles fewer than 100 orders per day where manual checks suffice.
Real World Examples
Amazon
Amazon uses order state machines to ensure orders move correctly from placement to delivery, preventing shipping of canceled or unpaid orders.
Uber Eats
Uber Eats applies state machines to track food order statuses like 'Order Placed', 'Preparing', 'Picked Up', and 'Delivered' to coordinate between restaurants and drivers.
Shopify
Shopify implements order state machines to manage order fulfillment stages and handle returns or cancellations systematically.
Code Example
The before code allows changing order states without checks, risking invalid flows. The after code defines allowed transitions and enforces them, preventing invalid state changes and making order processing safer and clearer.
LLD
### Before: No state machine, direct state changes without checks
class Order:
    def __init__(self):
        self.state = 'Created'

    def pay(self):
        self.state = 'Paid'

    def ship(self):
        self.state = 'Shipped'

    def deliver(self):
        self.state = 'Delivered'

### After: Using state machine to enforce valid transitions
class OrderStateMachine:
    allowed_transitions = {
        'Created': ['Paid', 'Canceled'],
        'Paid': ['Shipped', 'Canceled'],
        'Shipped': ['Delivered', 'Canceled'],
        'Delivered': ['Returned'],
        'Canceled': [],
        'Returned': []
    }

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

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

    def pay(self):
        self.transition('Paid')

    def ship(self):
        self.transition('Shipped')

    def deliver(self):
        self.transition('Delivered')

    def cancel(self):
        self.transition('Canceled')

    def return_order(self):
        self.transition('Returned')
OutputSuccess
Alternatives
Event-driven architecture
Uses events to trigger state changes asynchronously rather than enforcing strict state transitions in a single flow.
Use when: Choose when you need high scalability and loose coupling between order processing components.
Workflow engine
Uses a configurable engine to define and execute order workflows, allowing dynamic changes without code updates.
Use when: Choose when business rules change frequently and non-developers need to modify order flows.
Summary
Order state machines prevent invalid order processing by enforcing allowed state transitions.
They make order flows explicit and easier to maintain, reducing operational errors.
They are best used in systems with multiple order states and strict business rules.