Bird
Raised Fist0
LLDsystem_design~25 mins

Inventory management in LLD - System Design Exercise

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
Design: Inventory Management System
Includes product and warehouse management, stock tracking, alerts, and query APIs. Excludes order processing, payment, and shipping logistics.
Functional Requirements
FR1: Track stock levels for multiple products across multiple warehouses
FR2: Support adding new products and warehouses
FR3: Update stock quantities on product purchase, return, or restock
FR4: Provide real-time stock availability queries
FR5: Generate alerts when stock for any product falls below a threshold
FR6: Support concurrent updates without data loss or inconsistency
Non-Functional Requirements
NFR1: Handle up to 10,000 concurrent users querying stock
NFR2: API response time p99 under 200ms for stock queries
NFR3: System availability 99.9% uptime
NFR4: Data consistency for stock updates must be strong to avoid overselling
Think Before You Design
Questions to Ask
❓ Question 1
❓ Question 2
❓ Question 3
❓ Question 4
❓ Question 5
Key Components
API Gateway for client requests
Authentication and Authorization service
Inventory Service to handle stock logic
Database for storing product, warehouse, and stock data
Cache layer for fast stock queries
Alerting service for low stock notifications
Message queue for handling asynchronous updates
Design Patterns
CQRS (Command Query Responsibility Segregation) for separating reads and writes
Event sourcing for tracking stock changes
Caching strategies to reduce database load
Distributed locking or transactions for concurrency control
Reference Architecture
Client
  |
  v
API Gateway
  |
  v
Authentication Service
  |
  v
Inventory Service <--> Cache Layer
  |
  v
Database
  |
  v
Alerting Service
  
Message Queue (for async stock updates and alerts)
Components
API Gateway
Nginx or AWS API Gateway
Handle client requests, route to services, enforce rate limiting
Authentication Service
OAuth 2.0 / JWT
Authenticate users and authorize access to inventory APIs
Inventory Service
Node.js / Python microservice
Process stock updates, queries, and business logic
Database
PostgreSQL
Store product, warehouse, and stock data with strong consistency
Cache Layer
Redis
Cache stock levels for fast read access
Alerting Service
Custom microservice or AWS SNS
Send notifications when stock falls below threshold
Message Queue
RabbitMQ or AWS SQS
Handle asynchronous stock update events and alert triggers
Request Flow
1. Client sends stock query or update request to API Gateway
2. API Gateway forwards request to Authentication Service for user validation
3. Authenticated requests reach Inventory Service
4. For stock queries, Inventory Service first checks Cache Layer
5. If cache miss, Inventory Service queries Database and updates cache
6. For stock updates, Inventory Service writes to Database within transaction
7. Inventory Service publishes stock update event to Message Queue
8. Alerting Service consumes events from Message Queue to check thresholds
9. Alerting Service sends notifications if stock is low
Database Schema
Entities: - Product (product_id PK, name, description, category) - Warehouse (warehouse_id PK, location, name) - Stock (stock_id PK, product_id FK, warehouse_id FK, quantity, last_updated) Relationships: - Product to Stock: 1 to many - Warehouse to Stock: 1 to many Stock table stores current quantity per product per warehouse.
Scaling Discussion
Bottlenecks
Database write contention on stock updates
Cache invalidation and consistency challenges
Message queue overload with high update volume
API Gateway rate limiting under heavy load
Solutions
Use database sharding by warehouse or product to distribute writes
Implement cache with TTL and write-through or write-back strategies
Scale message queue horizontally and partition topics
Deploy multiple API Gateway instances with load balancing
Interview Tips
Time: 10 minutes for requirements and clarifications, 15 minutes for architecture and data flow, 10 minutes for scaling and trade-offs, 10 minutes for Q&A
Clarify consistency needs and scale targets early
Explain choice of database for strong consistency
Describe caching strategy to meet latency goals
Discuss concurrency control to prevent overselling
Highlight asynchronous alerting for scalability
Mention how to handle failures and retries

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