This system manages the lifecycle of an order in an e-commerce platform. It tracks the order status from creation to completion, ensuring valid state transitions and handling failures gracefully.
Order state machine in LLD - Architecture Diagram
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
System Overview - Order state machine
Architecture Diagram
User | v Order Service | v State Machine Engine | v Order Database | v Notification Service
Components
User
actor
Initiates order actions like create, cancel, or update
Order Service
service
Receives user requests and forwards them to the state machine
State Machine Engine
service
Manages order state transitions and validates state changes
Order Database
database
Stores order details and current state
Notification Service
service
Sends updates to users about order status changes
Request Flow - 5 Hops
User → Order Service
Order Service → State Machine Engine
State Machine Engine → Order Database
State Machine Engine → Notification Service
Notification Service → User
Failure Scenario
Component Fails:Order Database
Impact:Order state updates fail, new orders cannot be saved, but notifications and validations continue for existing cached states
Mitigation:Use database replication and fallback cache to serve read requests; queue write requests for retry when DB recovers
Architecture Quiz - 3 Questions
Test your understanding
Which component validates and manages order state transitions?
Design Principle
Practice
1.
What is the main purpose of an Order State Machine in a system?
easy
Solution
Step 1: Understand the role of state machines
State machines define allowed states and transitions for an entity, ensuring valid progress.Step 2: Apply to order lifecycle
For orders, the state machine controls stages like 'Pending', 'Shipped', 'Delivered', preventing invalid jumps.Final Answer:
To track and control the valid states an order can be in during its lifecycle -> Option AQuick Check:
Order state machine = control order states [OK]
Hint: State machines control valid order stages only [OK]
Common Mistakes:
- Confusing state machine with payment processing
- Thinking it calculates prices
- Mixing with user session management
2.
Which of the following is the correct way to represent a state transition in an order state machine?
class OrderStateMachine:
def __init__(self):
self.state = 'Pending'
def ship(self):
# Transition from Pending to Shipped
?
easy
Solution
Step 1: Understand valid state change syntax
Assign new state only if current state allows it; else raise error.Step 2: Check each option
if self.state == 'Pending': self.state = 'Shipped' else: raise Exception('Invalid transition') correctly assigns 'Shipped' if current is 'Pending', else raises exception.Final Answer:
if self.state == 'Pending': self.state = 'Shipped' else: raise Exception('Invalid transition') -> Option AQuick Check:
Valid transition check = if self.state == 'Pending': self.state = 'Shipped' else: raise Exception('Invalid transition') [OK]
Hint: Assign new state only if current state matches [OK]
Common Mistakes:
- Using comparison (==) instead of assignment (=)
- Assigning wrong state based on condition
- Changing method name instead of state
3.
Given the following code snippet for an order state machine, what will be the output after calling cancel() twice?
class OrderStateMachine:
def __init__(self):
self.state = 'Pending'
def cancel(self):
if self.state in ['Pending', 'Shipped']:
self.state = 'Cancelled'
else:
print('Cannot cancel from', self.state)
order = OrderStateMachine()
order.cancel()
order.cancel()
print(order.state)
medium
Solution
Step 1: Trace first cancel call
Initial state is 'Pending', so state changes to 'Cancelled'.Step 2: Trace second cancel call
State is now 'Cancelled', so print message 'Cannot cancel from Cancelled' and state stays 'Cancelled'.Final Answer:
Cannot cancel from Cancelled\nCancelled -> Option CQuick Check:
Second cancel prints message, state remains Cancelled [OK]
Hint: Check state before transition; print if invalid [OK]
Common Mistakes:
- Assuming second cancel changes state again
- Ignoring printed message
- Expecting error instead of print
4.
Identify the bug in this order state machine method that allows invalid state transitions:
def deliver(self):
if self.state == 'Shipped' or 'Out for Delivery':
self.state = 'Delivered'
else:
raise Exception('Invalid transition');
medium
Solution
Step 1: Analyze the condition logic
The condition uses 'if self.state == 'Shipped' or 'Out for Delivery'', which always evaluates True because non-empty strings are truthy.Step 2: Correct the condition
It should be 'if self.state == 'Shipped' or self.state == 'Out for Delivery'' to check both states properly.Final Answer:
The condition always evaluates to True due to incorrect or usage -> Option DQuick Check:
Incorrect or condition causes always True [OK]
Hint: Check boolean conditions carefully for correct comparisons [OK]
Common Mistakes:
- Using 'or' with string literals incorrectly
- Forgetting to compare both sides explicitly
- Assuming condition works as intended
5.
You are designing an order state machine for an online store. The order states are Pending, Confirmed, Shipped, Delivered, and Cancelled. Which design ensures scalability and prevents invalid transitions?
Choose the best approach:
- Use a dictionary mapping each state to allowed next states.
- Hardcode all transitions in if-else blocks.
- Allow any state to transition to any other state.
- Use a single variable without validation.
hard
Solution
Step 1: Evaluate scalability and validation needs
Hardcoding transitions is error-prone and hard to maintain; allowing any transition breaks rules.Step 2: Choose dictionary mapping
Mapping states to allowed next states centralizes rules, making it easy to update and validate transitions.Final Answer:
Use a dictionary mapping each state to allowed next states -> Option BQuick Check:
Dictionary mapping = scalable, validated transitions [OK]
Hint: Map states to allowed next states for clean validation [OK]
Common Mistakes:
- Hardcoding transitions everywhere
- Skipping validation of transitions
- Allowing invalid state jumps
