Inventory Management System

Difficulty: Intermediate Patterns: Repository, Service Layer, Factory Asked at: Amazon, Flipkart, Walmart, Swiggy


Functional Requirements

  1. Add products - register products with SKU, name, category, and price
    💡 SKU (stock keeping unit) = the unique code for one sellable product variant, like one shirt in one size and colour. Stock is counted per SKU per warehouse here.
  2. Multi-warehouse stock - track stock quantities per product per warehouse
  3. Add/Remove stock - thread-safe stock level mutations with validation
  4. Query stock - get total stock or stock at a specific warehouse
  5. Atomic transfers - move stock between warehouses as a single atomic operation
    💡 Atomic = the whole transfer happens or none of it does. No other thread may ever see the units as having left the source warehouse but not yet arrived at the destination.

Non-Functional Requirements

  1. Thread-safety - concurrent stock mutations must not corrupt data (per-item locks)
    💡 Thread-safety = the code stays correct even when several threads run it at the same instant. A lock makes threads take turns through the read-then-write of a stock count, which is the step that otherwise loses updates.
  2. Deadlock prevention - lock ordering by warehouse ID for multi-lock operations
    💡 Deadlock = two threads each holding one lock and each waiting for the lock the other holds, so neither ever moves again. Taking locks in one fixed global order makes that circular wait impossible.
  3. Extensibility - repository interfaces allow swapping storage without changing logic
    💡 Depending on an interface rather than on a concrete database is the “D” of SOLID — dependency inversion: the business logic states what it needs and the storage choice plugs in underneath it.
  4. Validation - custom exceptions for clear error semantics
    💡 Custom exceptions = your own named error types (InsufficientStockException) instead of one generic failure, so a caller can catch precisely the case it knows how to handle. Learn more →

Core Entities

Entity Description
Product Immutable product info - SKU, name, category, price
Warehouse Storage location with ID, name, and physical location
InventoryItem Stock record for a product at a warehouse, with per-item lock
ProductRepository Interface for product CRUD operations
WarehouseRepository Interface for warehouse CRUD operations
InventoryRepository Interface for inventory item storage and queries
InventoryService Facade orchestrating all stock operations with thread-safety

💡 Immutable = once constructed, the object never changes. An immutable Product can be handed to any number of threads with no lock at all, because there is nothing in it for them to corrupt.

💡 Facade = one simple front door in front of several collaborating objects. Callers use InventoryService and never have to know that three repositories and a per-item lock sit behind it.


Class Diagram

classDiagram
    class Product {
        -String sku
        -String name
        -String category
        -long pricePaise
        +getSku() String
        +getName() String
        +getCategory() String
        +getPricePaise() long
    }

    class Warehouse {
        -String id
        -String name
        -String location
        +getId() String
        +getName() String
    }

    class InventoryItem {
        -String sku
        -String warehouseId
        -int quantity
        -ReentrantLock lock
        +addStock(int quantity)
        +removeStock(int quantity)
        +getQuantity() int
    }

    class ProductRepository {
        <<interface>>
        +save(Product)
        +findBySku(String) Product
        +existsBySku(String) boolean
    }

    class WarehouseRepository {
        <<interface>>
        +save(Warehouse)
        +findById(String) Warehouse
        +existsById(String) boolean
    }

    class InventoryRepository {
        <<interface>>
        +save(InventoryItem)
        +find(String sku and String warehouseId) InventoryItem
        +findAllBySku(String) List of InventoryItem
    }

    class InventoryService {
        -ProductRepository productRepo
        -WarehouseRepository warehouseRepo
        -InventoryRepository inventoryRepo
        +addProduct(String sku and String name and String category and long pricePaise)
        +addStock(String sku and String warehouseId and int qty)
        +removeStock(String sku and String warehouseId and int qty)
        +getStock(String sku) int
        +getStockByWarehouse(String sku and String warehouseId) int
        +transferStock(String sku and String from and String to and int qty)
    }

    class InsufficientStockException {
        -String sku
        -String warehouseId
        -int requested
        -int available
    }

    class ProductNotFoundException {
        -String sku
    }

    class WarehouseNotFoundException {
        -String warehouseId
    }

    InventoryService --> ProductRepository
    InventoryService --> WarehouseRepository
    InventoryService --> InventoryRepository
    InventoryRepository --> InventoryItem
    ProductRepository --> Product
    WarehouseRepository --> Warehouse
    InventoryItem --> Product
    InventoryItem --> Warehouse

💡 In a class diagram the plain arrow (-->) means “holds a reference to” and <<interface>> marks a type that declares operations without implementing them. Learn more →

Key classes:

  • Product — catalog information only (SKU, name, category, price) and no stock. Keeping it immutable and stock-free means the catalog can be cached or shared freely.
  • Warehouse — a physical storage location. Its ID is also what decides lock order during a transfer, so it is more than a label.
  • InventoryItem — the real workhorse: the quantity of one SKU at one warehouse, together with its own lock. Stock only ever moves through its addStock/removeStock, which is what makes the locking enforceable.
  • ProductRepository / WarehouseRepository / InventoryRepository — the storage interfaces, offering CRUD (create, read, update, delete) operations plus the few lookups the service needs. In-memory implementations ship with the code; a database implementation would satisfy the same interface.
  • InventoryService — the single entry point. It validates that products and warehouses exist, picks the lock order, performs the two-sided transfer under both locks, and translates failures into the custom exceptions.
  • InsufficientStockException — carries the SKU, warehouse, requested quantity and available quantity, so the caller can report the shortfall without re-querying.

Design Patterns

Pattern Where Why
Repository ProductRepository, WarehouseRepository, InventoryRepository Abstracts storage; swap in-memory for DB without changing business logic
Service Layer InventoryService Single entry point for all operations; encapsulates validation, locking, and coordination
Factory Product and InventoryItem creation Centralized construction ensures valid state

💡 Service layer = one class that owns the multi-step business operations and the order they run in, keeping those rules out of both the domain models and the storage code. transferStock lives here and not on InventoryItem because it spans two items.