Bird
Raised Fist0
LLDsystem_design~7 mins

Inventory management in LLD - System Design Guide

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Problem Statement
Without a proper inventory management system, businesses face stockouts or overstock situations that lead to lost sales or increased holding costs. Manual tracking causes errors and delays, making it hard to respond quickly to demand changes or supply disruptions.
Solution
An inventory management system tracks stock levels, orders, sales, and deliveries in real time. It updates inventory counts automatically when items are added or sold, enabling accurate forecasting and timely replenishment. This system helps maintain optimal stock levels and reduces human errors.
Architecture
User System
Inventory API
Supplier API
Notification

This diagram shows how user requests flow through the Inventory API to the database, while the Order Service manages supplier interactions and notifications.

Trade-offs
✓ Pros
Automates stock tracking, reducing human errors.
Improves demand forecasting with real-time data.
Enables timely reorder alerts to prevent stockouts.
Supports integration with suppliers and sales channels.
✗ Cons
Requires initial setup and integration effort.
Complexity increases with multiple warehouses or SKUs.
Real-time updates may add load to the database.
Use when managing hundreds or more SKUs with frequent sales and replenishment cycles, especially if manual tracking causes errors or delays.
Avoid if inventory is very small (under 50 SKUs) and changes infrequently, where manual tracking is simpler and cost-effective.
Real World Examples
Amazon
Amazon uses inventory management to track millions of products across warehouses, ensuring fast fulfillment and accurate stock levels.
Shopify
Shopify provides inventory management tools to merchants to synchronize stock across online and physical stores.
Walmart
Walmart uses inventory management systems to optimize stock levels and automate replenishment across its vast retail network.
Code Example
The before code shows manual stock decrement without alerts. The after code adds automatic stock updates and triggers reorder alerts when stock falls below a threshold, improving reliability and responsiveness.
LLD
### Before: No inventory management, manual stock update
class Store:
    def __init__(self):
        self.stock = {}

    def sell_item(self, item, quantity):
        if item in self.stock and self.stock[item] >= quantity:
            self.stock[item] -= quantity
            print(f"Sold {quantity} of {item}")
        else:
            print("Not enough stock")

### After: Inventory management with automatic stock update and reorder alert
class InventoryManager:
    def __init__(self, reorder_threshold=5):
        self.stock = {}
        self.reorder_threshold = reorder_threshold

    def add_stock(self, item, quantity):
        self.stock[item] = self.stock.get(item, 0) + quantity

    def sell_item(self, item, quantity):
        if self.stock.get(item, 0) >= quantity:
            self.stock[item] -= quantity
            print(f"Sold {quantity} of {item}")
            self.check_reorder(item)
        else:
            print("Not enough stock")

    def check_reorder(self, item):
        if self.stock.get(item, 0) <= self.reorder_threshold:
            print(f"Reorder alert: {item} stock is low ({self.stock[item]})")
OutputSuccess
Alternatives
Manual Inventory Tracking
Relies on human input and spreadsheets instead of automated systems.
Use when: Choose when inventory is very small and changes are rare, making automation unnecessary.
Periodic Inventory System
Updates inventory counts at fixed intervals rather than real-time.
Use when: Choose when real-time accuracy is not critical and cost savings are prioritized.
Summary
Inventory management prevents stockouts and overstock by tracking stock levels automatically.
It improves accuracy and responsiveness by updating inventory in real time and alerting for reorders.
This system is essential for businesses with many products and frequent sales to optimize operations.

Practice

(1/5)
1. What is the primary purpose of an inventory management system?
easy
A. To track product quantities and prevent stock issues
B. To design product packaging
C. To manage employee schedules
D. To create marketing campaigns

Solution

  1. Step 1: Understand inventory management goals

    Inventory management focuses on tracking product quantities to avoid running out or overstocking.
  2. Step 2: Eliminate unrelated options

    Options about packaging, schedules, and marketing do not relate to inventory tracking.
  3. Final Answer:

    To track product quantities and prevent stock issues -> Option A
  4. Quick Check:

    Inventory management = tracking stock [OK]
Hint: Inventory systems track stock levels, not unrelated tasks [OK]
Common Mistakes:
  • Confusing inventory with marketing or HR tasks
  • Thinking inventory manages packaging design
  • Assuming inventory handles employee schedules
2. Which of the following is the correct way to check if an item exists in an inventory dictionary named stock in Python?
easy
A. if stock.has_key('item'):
B. if 'item' in stock:
C. if stock.contains('item'):
D. if stock.exists('item'):

Solution

  1. Step 1: Recall Python dictionary syntax

    To check if a key exists in a dictionary, use the in keyword.
  2. Step 2: Identify correct syntax

    stock.has_key() is deprecated, and contains or exists are invalid methods.
  3. Final Answer:

    if 'item' in stock: -> Option B
  4. Quick Check:

    Use 'in' to check keys in dict [OK]
Hint: Use 'in' keyword to check keys in Python dicts [OK]
Common Mistakes:
  • Using deprecated has_key() method
  • Using non-existent methods like contains()
  • Confusing method names for key checks
3. Given the Python code below, what will be the output?
stock = {'apple': 10, 'banana': 5}
stock['apple'] -= 3
print(stock['apple'])
medium
A. Error
B. 13
C. -3
D. 7

Solution

  1. Step 1: Understand the initial stock

    Initially, 'apple' has quantity 10.
  2. Step 2: Apply the subtraction operation

    Subtracting 3 from 10 results in 7.
  3. Final Answer:

    7 -> Option D
  4. Quick Check:

    10 - 3 = 7 [OK]
Hint: Subtract quantity correctly to find updated stock [OK]
Common Mistakes:
  • Adding instead of subtracting
  • Confusing keys or values
  • Expecting an error due to subtraction
4. Identify the error in the following inventory update code snippet:
stock = {'apple': 5}
stock['banana'] -= 2
print(stock)
medium
A. No error, banana quantity becomes -2
B. SyntaxError due to invalid subtraction
C. KeyError because 'banana' does not exist in stock
D. TypeError because stock is not a list

Solution

  1. Step 1: Check if 'banana' key exists

    'banana' is not in the stock dictionary initially.
  2. Step 2: Understand dictionary behavior on missing keys

    Subtracting from a missing key causes a KeyError in Python.
  3. Final Answer:

    KeyError because 'banana' does not exist in stock -> Option C
  4. Quick Check:

    Missing key access = KeyError [OK]
Hint: Accessing missing dict keys causes KeyError [OK]
Common Mistakes:
  • Assuming missing keys default to zero
  • Expecting negative values without initialization
  • Confusing error types
5. You are designing an inventory system that must handle multiple warehouses. Which design approach best ensures accurate stock counts across warehouses and prevents overselling?
hard
A. Maintain separate stock counts per warehouse and use transactions to update atomically
B. Keep a single global stock count without warehouse details
C. Update stock counts asynchronously without locking
D. Allow negative stock counts to handle overselling

Solution

  1. Step 1: Consider multi-warehouse stock tracking

    Each warehouse should have its own stock count to track inventory accurately.
  2. Step 2: Ensure atomic updates to prevent overselling

    Using transactions or locks ensures stock updates are consistent and prevent race conditions.
  3. Final Answer:

    Maintain separate stock counts per warehouse and use transactions to update atomically -> Option A
  4. Quick Check:

    Atomic updates + per-warehouse stock = accurate inventory [OK]
Hint: Use atomic transactions and per-warehouse counts [OK]
Common Mistakes:
  • Using global stock ignores warehouse differences
  • Updating asynchronously causes race conditions
  • Allowing negative stock hides overselling problems