Beginner LLD Practice: Order Management System in Python
Beginner LLD Practice: Order Management System in Python
A step-by-step approach covering requirements, classes, implementation, SOLID principles, and interview follow-ups.
1. Problem statement
Design an order management system where customers can:
- Place an order containing products and quantities.
- View an order.
- Cancel an order before shipment.
Each product has a name, price, and available stock.
Example:
Book: price 100, available stock 2
Place an order for 1 book:
Total = 100
Stock = 1
Status = PLACED
Cancel the order:
Stock = 2
Status = CANCELLED
Cancel again:
No additional stock restorationScope: an in-memory application handling requests sequentially. Database persistence, authorization, and concurrency are discussed as follow-ups.
2. Clarify requirements first
Ask:
- Can an order contain multiple products?
- Should the entire order fail if any product has insufficient stock?
- When is cancellation allowed?
- Are payments and shipping integration included?
Assumptions for this implementation:
- Multiple products are allowed.
- The entire order fails if any requested product is unavailable.
- Only
PLACEDorders can be cancelled. - Payments and shipping integration are outside scope.
- Quantities are positive integers.
- Prices use integer minor currency units, such as paise, in one currency.
What the interviewer learns: you establish the rules before choosing classes.
3. Identify the entities
| Class | Represents | Important fields |
|---|---|---|
Customer | Who orders | customer_id, name |
Product | Inventory information | product_id, name, price, stock_quantity |
OrderItem | A product within one order | product_id, quantity, unit_price |
Order | The purchase record | order_id, customer_id, items, total, status |
OrderService | Coordinates operations | Products, customers, and stored orders |
Why separate Product and OrderItem?
They describe different quantities:
Product.stock_quantity = 10 books available
OrderItem.quantity = 2 books purchasedOrderItem.unit_price preserves the price at purchase. A later product price change must not change an existing order.
An order can contain many order items. A product can appear in many different orders.
A class diagram helps show the structure. They may ask you to draw one or explain the relationships through your code. You don’t need elaborate UML unless requested.
This matches our latest design:
How to explain it:
“A customer can place many orders. Each order contains one or more order items. Each item references a product and saves the quantity and purchase price. OrderService coordinates the operations and updates inventory.”
Symbols to know:
| Symbol | Meaning |
|---|---|
1 | Exactly one |
0..* | Zero or more |
1..* | One or more |
*-- | Composition: the order owns its order items |
--> | A reference or dependency |
In the interview: clarify requirements → sketch these classes and relationships → walk through the main methods. Then add detail where the interviewer asks.
4. Naming conventions
Python generally uses:
# Classes and enums: PascalCase
OrderService
OrderStatus
# Variables, methods, parameters: snake_case
customer_id
stock_quantity
place_order()
# Enum members and constants: UPPER_SNAKE_CASE
OrderStatus.PLACEDPrefer names that explain meaning:
product.stock_quantityis clearer than:
p.qtyShort loop variables can be fine, but descriptive names help when several related objects are involved.
5. Plan the operations
Place an order
- Validate the customer and request.
- Combine quantities for repeated product IDs.
- Validate every product and its available stock.
- Create order items using trusted product prices.
- Calculate the total.
- Deduct stock and store the order.
View an order
Find it using its order ID.
Cancel an order
- Find the order.
- Check its current status.
- Restore stock.
- Mark it cancelled.
- Keep its record.
Why validate everything before deducting stock?
Suppose an order requests:
1 shampoo: available stock 5
3 books: available stock 2If shampoo stock is deducted first and the books then fail, the order is rejected but shampoo stock has incorrectly changed.
First validate all items. Then apply changes.
This prevents validation failures from causing partial deductions. Full crash recovery requires stronger mechanisms, discussed later.
6. Python implementation
This version uses dictionaries for lookups and simple classes for the domain.
from enum import Enum
class OrderStatus(Enum):
PLACED = "Placed"
SHIPPED = "Shipped"
CANCELLED = "Cancelled"
class Customer:
def __init__(self, customer_id, name):
self.customer_id = customer_id
self.name = name
class Product:
def __init__(self, product_id, name, price, stock_quantity):
self.product_id = product_id
self.name = name
self.price = price
self.stock_quantity = stock_quantity
class OrderItem:
def __init__(self, product_id, quantity, unit_price):
self.product_id = product_id
self.quantity = quantity
self.unit_price = unit_price # price at purchase
@property
def subtotal(self):
return self.unit_price * self.quantity
class Order:
def __init__(self, order_id, customer_id, items):
self.order_id = order_id
self.customer_id = customer_id
self.items = items
self.total = sum(item.subtotal for item in items)
self.status = OrderStatus.PLACED
class OrderService:
def __init__(self, products, customers):
# Store by ID for O(1) average lookup.
self.products = {
product.product_id: product
for product in products
}
self.customers = {
customer.customer_id: customer
for customer in customers
}
self.orders = {}
self.next_order_id = 1
def place_order(self, customer_id, requested_items):
"""
requested_items: list of (product_id, quantity) tuples
Example: [(2, 1), (1, 2)]
"""
if customer_id not in self.customers:
raise ValueError("Customer not found.")
if not requested_items:
raise ValueError("Order cannot be empty.")
# Combine repeated products before checking total demand.
quantities = {}
for product_id, quantity in requested_items:
if type(quantity) is not int or quantity <= 0:
raise ValueError(
"Quantity must be a positive integer."
)
quantities[product_id] = (
quantities.get(product_id, 0) + quantity
)
# Validate everything before changing inventory.
for product_id, quantity in quantities.items():
product = self.products.get(product_id)
if product is None:
raise ValueError(
f"Product {product_id} not found."
)
if quantity > product.stock_quantity:
raise ValueError(
f"Insufficient stock for {product.name}."
)
# Build order items using trusted inventory prices.
order_items = []
for product_id, quantity in quantities.items():
product = self.products[product_id]
order_items.append(
OrderItem(
product_id=product_id,
quantity=quantity,
unit_price=product.price,
)
)
order = Order(
order_id=self.next_order_id,
customer_id=customer_id,
items=order_items,
)
# Sequential in-memory update; not a DB transaction.
for product_id, quantity in quantities.items():
self.products[product_id].stock_quantity -= quantity
self.orders[order.order_id] = order
self.next_order_id += 1
return order.order_id
def view_order(self, order_id):
order = self.orders.get(order_id)
if order is None:
raise ValueError("Order not found.")
return order
def cancel_order(self, order_id):
order = self.view_order(order_id)
# A retry has no additional effect.
if order.status == OrderStatus.CANCELLED:
return
if order.status != OrderStatus.PLACED:
raise ValueError(
"Only placed orders can be cancelled."
)
for item in order.items:
self.products[item.product_id].stock_quantity += (
item.quantity
)
order.status = OrderStatus.CANCELLED
def print_order(order):
print(
f"Order {order.order_id} | "
f"Customer {order.customer_id} | "
f"Total {order.total} | "
f"Status {order.status.value}"
)
for item in order.items:
print(
f"Product {item.product_id} | "
f"Quantity {item.quantity} | "
f"Unit price {item.unit_price} | "
f"Subtotal {item.subtotal}"
)
products = [
Product(1, "Shampoo", 20000, 5),
Product(2, "Book", 10000, 2),
Product(3, "Hair gel", 15000, 9),
]
customers = [
Customer(1, "Anna"),
Customer(2, "Sunny"),
]
order_service = OrderService(products, customers)
# Failure: three books requested, but only two available.
try:
order_service.place_order(
customer_id=1,
requested_items=[(2, 3)],
)
except ValueError as error:
print(error)
print(order_service.products[2].stock_quantity) # 2
# Success: one book and two shampoos.
order_id = order_service.place_order(
customer_id=1,
requested_items=[(2, 1), (1, 2)],
)
order = order_service.view_order(order_id)
print_order(order) # total 50000 paise = Rs 500
print(order_service.products[2].stock_quantity) # 1
order_service.cancel_order(order_id)
print_order(order) # Cancelled
print(order_service.products[2].stock_quantity) # 2
# Repeated cancellation does not restore stock again.
order_service.cancel_order(order_id)
print(order_service.products[2].stock_quantity) # still 2Small implementation choices explained
Why are requested items tuples?
[(2, 1), (1, 2)]
# product 2, quantity 1
# product 1, quantity 2The caller supplies product IDs and quantities. The service creates the actual OrderItem objects and supplies trusted purchase prices.
What does @property do?
It lets us access a calculated value like a field:
item.subtotalinstead of calling:
item.subtotal()Why return objects instead of printing inside the service?
The service handles business operations. A caller can decide whether to print the result, return JSON, or display it in a UI.
Why raise an exception instead of returning -1?
Both are possible conventions. Exceptions make the failure reason explicit and keep it separate from successful return values. A web controller would translate these failures into suitable HTTP responses.
Why no NOT_PLACED status?
This design creates an Order only after validation succeeds. Draft orders are outside scope. Add a draft status if the requirements include creating and editing orders before placement.
7. Dry run
Initial inventory:
Book stock = 2
Shampoo stock = 5| Action | Result | Book stock | Shampoo stock |
|---|---|---|---|
| Request 3 books | Rejected | 2 | 5 |
| Request 1 book and 2 shampoos | Order 1, total 50000 paise | 1 | 3 |
| Cancel order 1 | Status becomes Cancelled | 2 | 5 |
| Cancel order 1 again | No additional effect | 2 | 5 |
8. SOLID principles in beginner language
SOLID is a set of design guidelines for keeping code understandable and adaptable. It is not a requirement to create many classes or use every principle visibly in every solution.
S: Single Responsibility Principle
A class should have one coherent responsibility.
In this design:
Productrepresents inventory information.Orderrepresents a purchase record.OrderServicecoordinates order operations.print_orderhandles presentation.
A service that also formats HTML emails, implements SQL queries, and handles HTTP responses would mix unrelated responsibilities.
Important: single responsibility does not mean one method per class. Placing and cancelling orders can belong to one coherent order service.
O: Open Closed Principle
Make useful variations extendable without repeatedly rewriting stable code.
Suppose the system later supports email, SMS, and push notifications. Each channel could implement the same send() contract.
The order workflow can use that contract instead of knowing every provider’s details.
In this exercise: there is no need to invent notification abstractions before notifications are required.
L: Liskov Substitution Principle
A replacement implementation should keep the promises its callers depend on.
Suppose all notification senders promise:
send(notification) returns a provider message ID
or raises a documented delivery error.A replacement that silently drops the message and reports success breaks that contract.
Matching method names alone is not enough; behavior matters too.
In this exercise: there is no inheritance hierarchy to justify. Do not add one simply to demonstrate Liskov.
I: Interface Segregation Principle
Do not force components to support operations they do not need.
A simple sender may need only:
send(notification)It should not necessarily be forced to implement campaign analytics, bulk scheduling, and template management.
Split contracts around meaningful client needs.
Important: this does not mean creating an interface for every method.
D: Dependency Inversion Principle
Business logic should depend on suitable abstractions rather than being tightly coupled to infrastructure details.
In a larger system, OrderService could depend on repository contracts:
OrderRepository
ProductRepositorySQL-backed repositories would implement those contracts.
This allows business rules to be tested with fake repositories.
Our current service still stores data directly in dictionaries. It does not fully implement this separation.
Dependency injection versus dependency inversion
Our constructor receives its dependencies:
OrderService(products, customers)That is a simple form of dependency injection.
- Injection: how a component receives what it needs.
- Inversion: what abstractions the code depends on.
They are related, but they are not the same thing.
9. Other important design concepts
Encapsulation
Keep state and the rules governing it together.
An improvement would be preventing arbitrary external changes to order items or status. This educational implementation returns mutable order objects, so callers must treat them as read-only.
Composition
An order has order items. A service uses products and orders.
These are composition relationships. OrderService should not inherit from Order, because a service is not a type of order.
Enum versus state transitions
An enum names the available statuses:
OrderStatus.PLACED
OrderStatus.CANCELLEDIt does not automatically enforce valid transitions. The cancellation method checks which transitions are allowed.
Do we need design patterns?
The current scope does not require Strategy, Factory, or State objects.
They become useful when requirements introduce meaningful variation or complexity:
| Pattern | Potential use |
|---|---|
| Strategy | Different discount or payment behaviors |
| Factory | Choosing the appropriate implementation |
| Repository | Separating persistence from business logic |
| State | Substantial behavior that differs by order status |
Explain the problem a pattern solves before naming the pattern.
10. Interview follow-ups
Why validate in the backend if the UI already checks?
The UI can be bypassed, and its stock information can become outdated.
“UI validation improves usability. Backend validation enforces the business rules.”
Why combine quantities for repeated products?
Stock might be 2, while the request contains two separate entries requesting 2 each.
Each entry alone appears valid, but the combined request for 4 must fail.
What is idempotency?
Repeating an operation has the same intended effect as doing it once.
For cancellation:
First request: restore stock and mark cancelled.
Repeated request: no additional stock restoration.What if two customers buy the last product simultaneously?
Both can read stock as 1 and both accept the purchase.
“I would coordinate the stock check and deduction using database concurrency controls, such as row locks inside a transaction or atomic conditional updates.”
The current sequential implementation does not implement this protection.
What if two cancellations happen simultaneously?
Both might read PLACED before either changes it, restoring stock twice.
Protect the status check, inventory restoration, and status update together. For example, lock the order row within a transaction.
Why use a database transaction?
Stock deductions and order creation form one logical operation.
If a required write fails, all related writes should roll back.
Checking everything first prevents normal validation failures from causing partial deductions. It does not protect this in-memory code against a crash or unexpected error during updates.
What if the client retries order creation after a timeout?
The order may already exist even though the client did not receive the response.
Use an idempotency key, persist its request identity and outcome, and enforce uniqueness atomically. A retry should receive the existing result instead of creating another order.
Why preserve the purchase price?
Current product prices may change. Historical order prices must remain stable.
What changes when adding a database?
Use:
customers
customer_id, name
products
product_id, name, price, stock_quantity
orders
order_id, customer_id, total, status, created_at
order_items
order_id, product_id, quantity, unit_priceAdd keys, foreign keys, constraints, appropriate indexes, and transaction handling.
With repeated products combined, (order_id, product_id) can identify an order-item row in this model.
How do you prevent customers accessing someone else’s order?
Use the authenticated customer identity to check order ownership or permissions when viewing or cancelling.
Knowing an order ID is not authorization.
What APIs would you expose?
POST /orders
GET /orders/{order_id}
POST /orders/{order_id}/cancelThe server determines prices and verifies access. The service layer contains business rules; a controller handles HTTP input and responses.
How would you generate IDs in production?
The local counter is scoped to one service instance and resets after restart.
Use a suitable persistent or distributed identifier mechanism, such as a database-generated ID or UUID, according to the requirements.
What tests matter?
- Valid single-item and multi-item orders.
- Missing customer or product.
- Empty order and invalid quantities.
- Insufficient stock leaves all inventory unchanged.
- Repeated product entries exceeding combined stock.
- Correct totals and historical purchase prices.
- Unknown order lookup.
- Cancellation restores the correct quantities.
- Repeated cancellation has no additional effect.
- Shipped orders cannot be cancelled.
- Concurrent operations when concurrency support is implemented.
11. Complexity
Let:
p= number of products.c= number of customers.k= number of request entries.u= number of distinct products in the order.
| Operation | Average time |
|---|---|
| Initialize service | O(p + c) |
| Place order | O(k) |
| Look up an order | O(1) |
| Print an order | O(u) |
| Cancel a placed order | O(u) |
Placement uses O(u) additional space for combined quantities and saved order items.
Stored orders require space proportional to the total number of stored orders and their items. Dictionary operations are O(1) on average.
12. Short interview answer
“I separated inventory products from order items because available stock and purchased quantity represent different things. OrderService validates the entire request, saves purchase prices, deducts stock, and stores the order by ID. Cancellation restores stock once and retains the record. This is a sequential in-memory design. For production, I would add database transactions, concurrency control, authorization, and retry-safe creation.”
Key takeaway: Start with clear rules and responsibilities, implement the main flow, then explain failures and tradeoffs.

