Real-Time Inventory & WMS System Design

CK CK 3788 
Created at
Updated at  
240 0 0

1. Architectural Foundation & CAP Theorem Trade-offs

In a high-traffic e-commerce environment, a traditional monolithic database configuration faces severe bottlenecks. When designing a distributed inventory and Warehouse Management System (WMS), we must navigate the trade-offs defined by the CAP Theorem (Consistency, Availability, Partition Tolerance).

Real-Time Inventory & WMS System Design

 

The Trade-off: AP over CP

While financial transactions require strict CP (Consistency & Partition Tolerance), real-time inventory systems for massive web traffic must prioritize AP (Availability & Partition Tolerance).

  • The Problem with Strong Consistency (CP): Utilizing distributed locks (e.g., Two-Phase Commit) to ensure physical warehouse stock matches the website stock in real-time results in high latency, database blocking, and potential system-wide cascading failures during peak traffic (e.g., flash sales).
  • The Solution (AP with Eventual Consistency): We decouple the front-end presentation inventory from the back-end physical WMS inventory. Users interact with a highly available, high-performance caching layer, while asynchronous processes reconcile the data in the background.

 

Hybrid Consistency Model Architecture

To balance user experience and data integrity, we implement a hybrid model:

Real-Time Inventory & WMS System Design

1. In-Memory Reservation (Temporary Consistency):

  • Redis is used as the first line of defense. Inventory deduction is executed atomically using Redis Lua scripts to prevent race conditions.
  • This provides sub-millisecond response times, ensuring high availability (A) and partition tolerance (P).

2. Asynchronous Write-Back (Eventual Consistency):

  • Once reserved in Redis, an event is published to a message queue (e.g., Apache Kafka) to update the persistent relational database (RDBMS) and notify the WMS asynchronously.
  • The physical warehouse inventory catch up with the logical online inventory within seconds, achieving Eventual Consistency.

 

 

2. Distributed Transaction Management: Saga Pattern

In a microservices architecture, a single customer order spans multiple services: Order Service, Inventory Service, and Payment Service. Since we cannot use blocking distributed transactions, we implement the Saga Pattern to manage distributed transactions and handle exceptions.

Real-Time Inventory & WMS System Design

 

Orchestrator-Based Saga Design

We utilize an Orchestrator-based Saga (using tools like Temporal or AWS Step Functions) to centrally manage the transaction flow and execute compensating transactions if a failure occurs.

 

Step-by-Step Transaction Workflow

  1. Order Created: The Orchestrator initiates the workflow and changes the order status to PENDING_PAYMENT.
  2. Inventory Reserved: The Orchestrator calls the Inventory Service to reserve stock.
    • State change: Stock status becomes RESERVED (not yet permanently deducted).
  3. Payment Processing: The Orchestrator calls the Payment Service.
  4. Success Path: If payment succeeds, the Orchestrator notifies the Inventory Service to commit the reservation (RESERVED → DEDUCTED) and changes the order status to PAID.

 

Handling Exceptions via Compensating Transactions

If the payment fails (e.g., insufficient funds, network timeout), the Orchestrator initiates the Compensating (Reverse) Transactions:

StepExecuting ServicePrimary ActionCompensating Action (On Failure)
1Order ServiceCreate Order (PENDING)Update Order Status to FAILED/CANCELLED
2Inventory ServiceReserve Stock (RESERVED)Release Reserved Stock (STOCK + 1)
3Payment ServiceProcess PaymentN/A (Point of Failure)

 

Ensuring Idempotency

To prevent duplicate processing caused by network retries in a distributed system, all endpoints in the Saga flow must be idempotent.

  • Idempotency Key: Every request carries a unique Idempotency-Key (typically the order_id).
  • De-duplication Mechanism: The Inventory Service checks a distributed lock or a unique database constraint on the order_id before executing any stock reservation. If the key has already been processed, it returns the cached previous response without re-processing.

 

 

3. High-Performance Multi-Region Data Synchronization (CDC)

To synchronize inventory data between the physical WMS databases located in regional fulfillment centers and the global cloud-based web application, we implement a Change Data Capture (CDC) pipeline.

Real-Time Inventory & WMS System Design

 

CDC Pipeline Architecture

Instead of resource-intensive batch queries (SELECT * FROM table WHERE updated_at > ...), the system captures low-level database transaction logs in real time.

 

1. Source Capture:

  • Debezium (running on Kafka Connect) monitors the transaction logs (e.g., MySQL Binlog, PostgreSQL WAL) of the local WMS databases.
  • Every INSERT, UPDATE, or DELETE on the inventory tables is immediately captured as an event document.

2. Event Streaming Backbone:

  • Captured events are streamed to Apache Kafka.
  • Topics are partitioned by product_id to guarantee that messages regarding the same item are processed in strict chronological order.

3. Stream Processing & Aggregation:

  • Apache Flink or KSQL processes the raw events to calculate aggregate stock levels across different regions.

4. Target Synchronization (Sink):

  • The processed inventory updates are consumed by multi-region synchronization workers, which update the localized Redis cache clusters in different cloud regions.

 

Conflict Resolution Strategy

In multi-region environments, network latency can lead to out-of-order data delivery. We implement conflict resolution mechanisms to prevent overwriting newer updates with older ones:

  • Version/Timestamp-based Ordering (Last-Write-Wins): Each DB update includes an incremental version number or a microsecond-precision physical timestamp. The sink workers only update the target cache if the incoming event's version is higher than the currently stored version.
  • Vector Clocks: For complex scenarios involving multi-master writes, vector clocks are implemented to detect and flag logical concurrent conflicts for human intervention or automated rule-based resolution.

 

The overall architecture will be like:

Real-Time Inventory & WMS System Design

 

If we convert above diagram in AWS Architect style:

Real-Time Inventory & WMS System Design

Tags CAP Theorem CDC Change Data Capture Data Synchronization Distributed Systems Distributed Transactions E-Commerce Architecture Eventual Consistency Real-Time Inventory Saga Pattern WMS WMS System Design Warehouse Management System 쇼핑몰 Facebook X
Comments 0
Similar posts
  1. Enterprise-Scale 100k+ TPS Order Tracking System Architecture
    198
  2. Designing Resilient Infrastructure to Prevent Order Data Loss During Kafka Failures
    151
  3. Enterprise-Scale 100k+ TPS Order Processing System Architecture
    174
  4. Large-Scale Concurrency Control: Solving the DB Bottleneck from a Flood of “Likes”
    268
  5. System Design: High-Traffic Time-Deal Promotion System
    171
  6. Cadence Programming Model - A Distributed, Fault-Tolerant, Stateful Workflow Orchestration Framework
    285
  7. Optimize the performance of a search results page that experiences high traffic
    139
  8. Temporal Programming Model - Robust, Long-Running, Fault-Tolerant Applications as WorkFlows
    349
  9. Ad Indexing at Hyperscale: 100,000 Campaigns in Under 5ms
    289
  10. Predictable Ad Spend: Architecting Pacing at Hyperscale
    419
  11. Ad Tech Idempotency: Engineering for Reliability and Scale
    357
  12. Observer Pattern
    2,389
  13. Learning about Firestore: Architecture, Pros, Cons, and Real-World Deployments
    165
  14. Key Metrics Track to Ensure the Health and Performance of a Distributed System
    172
  15. Collecting Proof-of-Play from 100,000 Screens
    141
  1. The Blueprint of Success: Why System Design and Architecture Matter?
    395
  2. Software Design Patterns Cheat Sheet
    3,315
  3. Various naming for the Software Architecture - I can't find Component-based Architecture, Functional Architecture
    3,325
  4. Builder Pattern - offering pre-defined Interfaces to set Individual Parts
    1,429
  5. Abstract Factory Pattern - Commonly Used for UI Themes or Objects
    1,465
  6. Software Design Patterns
    1,430
  7. Observer Pattern
    2,389
  8. Factory Method Pattern allows overriding to return different concrete object types
    1,524
  9. Optimize the performance of a search results page that experiences high traffic
    139
  10. System Design: High-Traffic Time-Deal Promotion System
    171
  11. Designing Resilient Infrastructure to Prevent Order Data Loss During Kafka Failures
    151
  12. Enterprise-Scale 100k+ TPS Order Tracking System Architecture
    198
  13. Enterprise-Scale 100k+ TPS Order Processing System Architecture
    174
  14. Architecting Dynamic Scale-Out and Scale-In with Docker Containers
    130
  15. How to Design Redis Caching in Infrastructure Architecture
    154
  16. Architecture Design - Database Partitioning vs. Sharding
    149
Recently updated
  1. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    27
  2. Why SPF and DKIM Are Essential for Linux Email Servers?
    24
  3. How do I create animated background for Google Meet?
    19,707
  4. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    217
  5. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    85
  6. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    153
  7. Array of arguments passed to script in PHP
    85
  8. Invalid Auction Storms in Ad Tech
    93
  9. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    197
  10. The Two Clocks of Ad Server Architecture
    63
  11. Frequency Cap Architecture Overview
    508
  12. Collecting Proof-of-Play from 100,000 Screens
    141
  13. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    280
  14. What is RedisVL?
    105
  15. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    224
  16. TPU & GPU Cluster Management Tools
    232
  17. The Concept of Scaffolding in AI Agents
    221
  18. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    575
  19. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    252
  20. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    326
  21. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    197
  22. Machine Learning: Training vs. Ranking
    213
  23. The Continuous Learning Machine: Designing a Loop That Actually Turns
    217
  24. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    189
  25. Designing a Data Curation System Around a Vector Database
    215
  26. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    229
  27. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    649
  28. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    185
  29. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    207
  30. Understanding Data Lineage
    252