Order Management System

Difficulty: Intermediate Patterns: State, Builder, Observer, Strategy Asked at: Amazon, Flipkart, Swiggy, Razorpay, PhonePe


Functional Requirements

  1. Place orders - create orders with stock validation and atomic deduction
    💡 Atomic = the step either happens completely or not at all, with no half-finished version visible to anyone else. Without it two shoppers can both pass the stock check and both deduct the last unit.
  2. Cancel orders - cancel with stock restoration (only from PLACED/CONFIRMED)
  3. Status transitions - validated state machine (PLACED→CONFIRMED→SHIPPED→DELIVERED)
    💡 A finite state machine (FSM) = a fixed set of states plus the only moves allowed between them. An order may go PLACED→CONFIRMED but never PLACED→DELIVERED, and that rulebook lives in one object instead of being scattered through if-checks. Learn more →
  4. Notifications - observers fire on every state change
    💡 An observer is a listener that registers interest once and is then called back on every change. The order code announces “status changed” without knowing whether anyone is sending email, SMS or nothing at all. Learn more →
  5. Query orders - retrieve by ID or by customer

Non-Functional Requirements

  1. Thread-safety - order placement and cancellation lock stock deductions
    💡 Thread-safety = the code stays correct even when several threads run it at the same instant. A lock makes threads take turns through the stock-deduction section so no two of them read the same stock value and both decide it is sufficient.
  2. State integrity - invalid transitions are rejected (no skipping states)
  3. Extensibility - new discount strategies and notification channels without modifying service
    💡 This is the open–closed principle from SOLID: new behaviour arrives as a new class, and the classes that already work are left untouched.
  4. Correctness - stock deducted on place, restored on cancel, always consistent

Core Entities

Entity Description
OrderStatus Enum - PLACED, CONFIRMED, SHIPPED, DELIVERED, CANCELLED
Customer Immutable - id, name, email
Product SKU with price and thread-safe stock management
OrderItem Links a product to a quantity with price snapshot at order time
Order Aggregates customer, items, status, total; built via Builder pattern
OrderStateValidator Encodes valid state transitions as a directed graph
OrderObserver Interface for notification on status changes
DiscountStrategy Interface for pluggable pricing/discount logic
OrderService Facade - orchestrates placement, cancellation, transitions, queries

💡 Immutable = once constructed, the object never changes. An immutable Customer can be shared across every thread in the service with no lock at all, because there is nothing for a thread to corrupt.

💡 SKU (stock keeping unit) = the unique code for one sellable product variant, like one shoe in one size and colour. Stock is counted per SKU, which is why it is the product’s identity here.

💡 Directed graph = nodes joined by one-way arrows. The statuses are the nodes and the legal transitions are the arrows, so “may this order move from SHIPPED to CANCELLED?” becomes “is there an arrow?”.

💡 Facade = one simple front door in front of several collaborating objects. Callers talk to OrderService and never have to know that a validator, a discount strategy, a builder and a list of observers exist behind it.


Class Diagram

classDiagram
    class OrderStatus {
        <<enumeration>>
        PLACED
        CONFIRMED
        SHIPPED
        DELIVERED
        CANCELLED
    }

    class Customer {
        -String id
        -String name
        -String email
        +getId() String
        +getName() String
        +getEmail() String
    }

    class Product {
        -String sku
        -String name
        -double price
        -int stock
        +deductStock(int qty)
        +restoreStock(int qty)
        +getStock() int
    }

    class OrderItem {
        -Product product
        -int quantity
        -double priceAtOrder
        +getSubtotal() double
    }

    class Order {
        -String id
        -Customer customer
        -List~OrderItem~ items
        -OrderStatus status
        -double totalAmount
        -LocalDateTime createdAt
        -LocalDateTime updatedAt
        +getStatus() OrderStatus
        +transitionTo(OrderStatus newStatus)
    }

    class OrderStateValidator {
        +canTransition(OrderStatus from to OrderStatus to) boolean
        +getValidTransitions(OrderStatus from) Set of OrderStatus
    }

    class OrderObserver {
        <<interface>>
        +onStatusChange(Order order and OrderStatus oldStatus and OrderStatus newStatus)
    }

    class EmailNotifier {
        +onStatusChange(Order and OrderStatus and OrderStatus)
    }

    class SMSNotifier {
        +onStatusChange(Order and OrderStatus and OrderStatus)
    }

    class DiscountStrategy {
        <<interface>>
        +applyDiscount(double amount) double
    }

    class NoDiscount {
        +applyDiscount(double amount) double
    }

    class PercentageDiscount {
        -double percentage
        +applyDiscount(double amount) double
    }

    class OrderService {
        -Map~String and Order~ orders
        -List~OrderObserver~ observers
        -OrderStateValidator validator
        -DiscountStrategy discountStrategy
        -ReentrantLock lock
        +placeOrder(Customer and List~OrderItem~) Order
        +cancelOrder(String orderId)
        +updateStatus(String orderId and OrderStatus newStatus)
        +getOrder(String orderId) Order
        +getOrdersByCustomer(String customerId) List~Order~
    }

    Order --> OrderStatus
    Order --> Customer
    Order --> OrderItem
    OrderItem --> Product
    OrderService --> Order
    OrderService --> OrderStateValidator
    OrderService --> OrderObserver
    OrderService --> DiscountStrategy
    OrderObserver <|.. EmailNotifier
    OrderObserver <|.. SMSNotifier
    DiscountStrategy <|.. NoDiscount
    DiscountStrategy <|.. PercentageDiscount

💡 In a class diagram the dashed hollow-headed arrow (<|..) means “implements this interface” and the plain arrow (-->) means “holds a reference to”; <<interface>> marks a type with no implementation of its own. Learn more →

Key classes:

  • Order — the aggregate at the centre of the design. It owns the item list, the current OrderStatus, the computed total and the timestamps, and transitionTo is the only way its status ever moves.
  • OrderItem — one product and a quantity, plus priceAtOrder: a snapshot of the price when the order was placed, so a later price change can never rewrite the history of a past order.
  • Product — the sellable thing, identified by SKU, and the owner of its own stock counter and its own lock. Stock changes go through deductStock/restoreStock rather than being edited from outside.
  • OrderStateValidator — holds the rulebook of legal status moves and nothing else. It answers canTransition(from, to) and never mutates an order, which is what keeps the lifecycle rules in one readable place.
  • OrderObserver — the listener interface. EmailNotifier and SMSNotifier implement it; a new channel is a new class that the service never has to be told about individually.
  • DiscountStrategy — the pricing rule, chosen at runtime. OrderService calls applyDiscount(amount) and stays ignorant of which rule is in force.
  • OrderService — the orchestrator and the only lock holder. It validates stock, deducts it, builds the order, stores it, and fans the status change out to the observers.

Design Patterns

Pattern Where Why
State OrderStateValidator encodes transitions Enforces valid lifecycle paths - no illegal state jumps
Builder Order.Builder Assembles complex orders fluently with validation on build()
Observer OrderObserver with Email/SMS notifiers Decouple notifications from order logic; add channels without modifying service
Strategy DiscountStrategy with NoDiscount/PercentageDiscount Swap pricing logic at runtime without changing placement code

💡 State pattern = let the object’s current state decide which operations are legal, instead of guarding every method with a pile of if-checks. This page uses the lighter table-driven form — an enum plus a map of allowed next states — which is usually the right call until each state needs behaviour of its own.