The Order Management Service (OMS) is a Core Bounded Context within the PakLog fulfillment platform that orchestrates the complete order lifecycle from creation through fulfillment. Built with Saga pattern and state machine architecture, it coordinates complex distributed transactions across inventory, warehouse, shipping, and financial systems while maintaining order integrity and customer experience.
Strategic Importance: CRITICAL - Central hub for all fulfillment operations Architecture Pattern: Saga Orchestration with State Machines Technology Stack: Java 21, Spring Boot 3.2, PostgreSQL, Apache Kafka, Spring State Machine Domain Complexity: VERY HIGH - Complex orchestration with compensating transactions
Core Purpose: Centralized orchestration of order lifecycle management, coordinating all fulfillment activities across distributed services while maintaining transactional integrity and optimal customer experience.
Responsibilities (Whatβs IN the Context):
External Dependencies (Whatβs OUT of the Context):
| Term | Definition | Business Context |
|---|---|---|
| Order | Customerβs request for products with delivery commitment | Core entity |
| Order Line | Individual product and quantity within an order | Order component |
| Fulfillment | Process of picking, packing, and shipping an order | Core process |
| Orchestration | Coordination of distributed services for order processing | Key capability |
| Saga | Long-running transaction with compensating actions | Pattern implementation |
| Allocation | Assignment of inventory and warehouse for fulfillment | Resource assignment |
| Wave | Batch of orders released for warehouse processing | Fulfillment optimization |
| Split Shipment | Order fulfilled from multiple locations | Fulfillment strategy |
| Backorder | Order held pending inventory availability | Exception handling |
| SLA | Service Level Agreement for order processing time | Performance commitment |
| Hold | Temporary suspension of order processing | Risk management |
| Release | Authorization to proceed with fulfillment | Process control |
graph TB
subgraph "Order Management Bounded Context"
Core1[Core: Order Orchestration]
Core2[Core: Fulfillment Coordination]
Core3[Core: State Management]
Support1[Supporting: Order Validation]
Support2[Supporting: SLA Management]
Support3[Supporting: Notification Management]
Generic1[Generic: Event Publishing]
Generic2[Generic: External Integration]
end
Core1 --> Core2
Core1 --> Core3
Core2 --> Support1
Core3 --> Support2
Classification: CORE DOMAIN Strategic Value: CRITICAL - Heart of fulfillment operations Investment Priority: HIGHEST - Continuous improvement required
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
@SagaOrchestrationService
public class OrderOrchestrationService {
@StartSaga
public OrderSaga startOrderFulfillment(Order order) {
return OrderSaga.builder()
.orderId(order.getId())
.customerId(order.getCustomerId())
.items(order.getLineItems())
.shippingAddress(order.getShippingAddress())
.paymentMethod(order.getPaymentMethod())
.build()
.start();
}
@SagaStep(compensate = "releaseInventory")
public ReservationResult reserveInventory(OrderSaga saga) {
return inventoryService.reserve(
saga.getItems(),
saga.getOrderId(),
Duration.ofMinutes(30)
);
}
@SagaStep(compensate = "cancelPayment")
public PaymentResult authorizePayment(OrderSaga saga) {
return paymentService.authorize(
saga.getPaymentMethod(),
saga.getTotalAmount(),
saga.getOrderId()
);
}
}
Classification: CORE DOMAIN Strategic Value: CRITICAL - Enables efficient operations Investment Priority: HIGHEST - Direct impact on costs
Classification: CORE DOMAIN Strategic Value: HIGH - Ensures order integrity Investment Priority: HIGH - Foundation for operations
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
@Configuration
@EnableStateMachine
public class OrderStateMachineConfig extends StateMachineConfigurerAdapter<OrderState, OrderEvent> {
@Override
public void configure(StateMachineStateConfigurer<OrderState, OrderEvent> states) {
states
.withStates()
.initial(OrderState.CREATED)
.state(OrderState.VALIDATED)
.state(OrderState.PAYMENT_AUTHORIZED)
.state(OrderState.INVENTORY_RESERVED)
.state(OrderState.RELEASED_TO_WAREHOUSE)
.state(OrderState.IN_FULFILLMENT)
.state(OrderState.PACKED)
.state(OrderState.SHIPPED)
.end(OrderState.DELIVERED)
.end(OrderState.CANCELLED);
}
@Override
public void configure(StateMachineTransitionConfigurer<OrderState, OrderEvent> transitions) {
transitions
.withExternal().source(OrderState.CREATED).target(OrderState.VALIDATED)
.event(OrderEvent.VALIDATION_COMPLETED)
.withExternal().source(OrderState.VALIDATED).target(OrderState.PAYMENT_AUTHORIZED)
.event(OrderEvent.PAYMENT_AUTHORIZED)
.withExternal().source(OrderState.PAYMENT_AUTHORIZED).target(OrderState.INVENTORY_RESERVED)
.event(OrderEvent.INVENTORY_RESERVED)
.withExternal().source(OrderState.INVENTORY_RESERVED).target(OrderState.RELEASED_TO_WAREHOUSE)
.event(OrderEvent.RELEASED_FOR_FULFILLMENT);
}
}
Classification: SUPPORTING DOMAIN Strategic Value: MEDIUM - Prevents downstream issues Investment Priority: MEDIUM - Important but not differentiating
Classification: SUPPORTING DOMAIN Strategic Value: MEDIUM - Customer satisfaction Investment Priority: MEDIUM - Service quality
classDiagram
class Order {
<<Aggregate Root>>
-OrderId id
-CustomerId customerId
-List~OrderLine~ lineItems
-ShippingAddress shippingAddress
-BillingAddress billingAddress
-OrderStatus status
-PaymentInfo payment
-FulfillmentInfo fulfillment
-OrderDates dates
-Money totalAmount
+create()
+validate()
+authorize()
+allocate()
+release()
+cancel()
+modify()
+ship()
+complete()
}
class OrderLine {
<<Entity>>
-LineId id
-SKU sku
-Quantity quantity
-Money unitPrice
-Money lineTotal
-LineStatus status
-FulfillmentDetails fulfillment
+reserve()
+allocate()
+cancel()
+ship()
}
class FulfillmentPlan {
<<Entity>>
-PlanId id
-OrderId orderId
-List~Shipment~ shipments
-RoutingStrategy strategy
-LocalDateTime plannedDate
+optimize()
+execute()
+modify()
}
class OrderSaga {
<<Saga>>
-SagaId id
-OrderId orderId
-SagaState state
-List~SagaStep~ steps
-CompensationStack compensations
+execute()
+compensate()
+retry()
}
Order --> OrderLine
Order --> FulfillmentPlan
OrderSaga --> Order
classDiagram
class OrderId {
<<Value Object>>
-String value
-OrderIdType type
+generate()
+validate()
}
class ShippingAddress {
<<Value Object>>
-String line1
-String line2
-String city
-String state
-String postalCode
-String country
+validate()
+geocode()
}
class OrderStatus {
<<Value Object>>
-StatusCode code
-String description
-LocalDateTime timestamp
-String updatedBy
+canTransitionTo()
}
class ServiceLevel {
<<Value Object>>
-String code
-String name
-Duration sla
-Money cost
+calculateDeadline()
}
class OrderPriority {
<<Value Object>>
-Integer score
-PriorityType type
-String reason
+compareTo()
}
| Event | Trigger | Consumers | Purpose |
|---|---|---|---|
OrderCreatedEvent |
New order placed | Inventory, Payment, WMS | Start fulfillment |
OrderValidatedEvent |
Validation passed | Payment Service | Proceed to payment |
PaymentAuthorizedEvent |
Payment approved | Inventory Service | Reserve inventory |
InventoryAllocatedEvent |
Stock allocated | WMS | Start picking |
OrderReleasedEvent |
Released to warehouse | WMS | Begin fulfillment |
OrderPackedEvent |
Packing complete | Shipping Service | Generate label |
OrderShippedEvent |
Shipment created | Customer Service | Send notification |
OrderDeliveredEvent |
Delivery confirmed | Finance, Analytics | Close order |
OrderCancelledEvent |
Order cancelled | All services | Compensate actions |
OrderModifiedEvent |
Order changed | Affected services | Update processing |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
L1: Order Management
βββ L2: Order Processing
β βββ L3: Order Creation & Validation
β βββ L3: Order Enrichment
β βββ L3: Fraud Detection
β βββ L3: Tax Calculation
β βββ L3: Pricing & Promotions
βββ L2: Fulfillment Orchestration
β βββ L3: Inventory Allocation
β βββ L3: Warehouse Assignment
β βββ L3: Order Routing
β βββ L3: Split Shipment Logic
β βββ L3: Wave Management
βββ L2: Order Lifecycle
β βββ L3: State Management
β βββ L3: Status Tracking
β βββ L3: SLA Management
β βββ L3: Escalation Handling
β βββ L3: Exception Management
βββ L2: Modification & Cancellation
β βββ L3: Order Modification
β βββ L3: Cancellation Processing
β βββ L3: Return Initiation
β βββ L3: Refund Processing
β βββ L3: Compensation Management
βββ L2: Integration & Communication
βββ L3: Service Orchestration
βββ L3: Event Publishing
βββ L3: Notification Management
βββ L3: External System Integration
βββ L3: Reporting & Analytics
Business Goal: Process 100% of orders accurately with optimal fulfillment paths
Key Business Outcomes:
Purpose: Accept and validate new orders from multiple channels
Business Rules:
Implementation:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
@Service
@Transactional
public class OrderCreationService {
public Order createOrder(CreateOrderRequest request) {
// Validate request
ValidationResult validation = orderValidator.validate(request);
if (!validation.isValid()) {
throw new OrderValidationException(validation.getErrors());
}
// Enrich order data
Order order = orderEnricher.enrich(
Order.builder()
.customerId(request.getCustomerId())
.lineItems(request.getItems())
.shippingAddress(request.getShippingAddress())
.build()
);
// Check fraud score
FraudCheckResult fraudCheck = fraudService.check(order);
if (fraudCheck.isHighRisk()) {
order.hold(HoldReason.FRAUD_REVIEW);
}
// Calculate pricing
order.applyPricing(pricingService.calculate(order));
// Save and publish event
Order saved = orderRepository.save(order);
eventPublisher.publish(new OrderCreatedEvent(saved));
return saved;
}
}
Purpose: Identify and prevent fraudulent orders
Detection Criteria:
Risk Levels:
1
2
3
4
5
6
7
8
public enum FraudRiskLevel {
LOW(0, 30), // Auto-approve
MEDIUM(31, 70), // Additional verification
HIGH(71, 100); // Manual review required
private final int minScore;
private final int maxScore;
}
Purpose: Determine optimal fulfillment path for each order
Routing Algorithm:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
@Component
public class OrderRoutingEngine {
public FulfillmentPlan route(Order order) {
// Get candidate warehouses
List<Warehouse> candidates = warehouseService
.findWarehousesWithInventory(order.getItems());
// Score each option
List<RoutingOption> options = candidates.stream()
.map(warehouse -> scoreOption(order, warehouse))
.sorted(Comparator.comparing(RoutingOption::getScore))
.collect(Collectors.toList());
// Select optimal strategy
RoutingStrategy strategy = selectStrategy(options);
return FulfillmentPlan.builder()
.orderId(order.getId())
.strategy(strategy)
.shipments(planShipments(order, strategy))
.estimatedCost(calculateCost(strategy))
.build();
}
private RoutingScore scoreOption(Order order, Warehouse warehouse) {
return RoutingScore.builder()
.distanceScore(calculateDistance(order.getShippingAddress(), warehouse))
.inventoryScore(calculateInventoryFit(order.getItems(), warehouse))
.capacityScore(warehouse.getAvailableCapacity())
.costScore(estimateFulfillmentCost(order, warehouse))
.slaScore(canMeetSLA(order, warehouse))
.build()
.aggregate();
}
}
Routing Strategies:
Purpose: Batch orders for efficient warehouse processing
Wave Planning:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
@Component
public class WavePlanningService {
@Scheduled(cron = "0 */15 * * * *") // Every 15 minutes
public void planWaves() {
// Get pending orders
List<Order> pendingOrders = orderRepository
.findByStatusAndWarehouse(
OrderStatus.RELEASED_TO_WAREHOUSE,
currentWarehouse
);
// Group by criteria
Map<WaveCriteria, List<Order>> groups = pendingOrders.stream()
.collect(Collectors.groupingBy(this::determineWaveCriteria));
// Create waves
groups.forEach((criteria, orders) -> {
if (orders.size() >= criteria.getMinimumSize() ||
criteria.isUrgent()) {
Wave wave = Wave.builder()
.warehouseId(currentWarehouse)
.orders(orders)
.priority(criteria.getPriority())
.targetCompletion(criteria.getDeadline())
.build();
waveRepository.save(wave);
warehouseService.releaseWave(wave);
}
});
}
}
Purpose: Maintain consistent order state across distributed system
State Transitions:
stateDiagram-v2
[*] --> CREATED
CREATED --> VALIDATED: Validation Success
CREATED --> CANCELLED: Validation Failure
VALIDATED --> PAYMENT_PENDING: Start Payment
PAYMENT_PENDING --> PAYMENT_AUTHORIZED: Payment Success
PAYMENT_PENDING --> CANCELLED: Payment Failure
PAYMENT_AUTHORIZED --> INVENTORY_RESERVED: Inventory Available
PAYMENT_AUTHORIZED --> BACKORDER: Inventory Unavailable
INVENTORY_RESERVED --> RELEASED: Release to Warehouse
RELEASED --> IN_FULFILLMENT: Start Picking
IN_FULFILLMENT --> PACKED: Packing Complete
PACKED --> SHIPPED: Label Created
SHIPPED --> DELIVERED: Delivery Confirmed
DELIVERED --> [*]
BACKORDER --> INVENTORY_RESERVED: Stock Available
CANCELLED --> [*]
Purpose: Ensure orders meet delivery commitments
SLA Monitoring:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
@Component
public class SLAMonitor {
@Scheduled(fixedDelay = 60000) // Every minute
public void checkSLAs() {
List<Order> activeOrders = orderRepository.findActive();
activeOrders.forEach(order -> {
SLAStatus status = calculateSLAStatus(order);
if (status.isAtRisk()) {
// Escalate
escalationService.escalate(
EscalationRequest.builder()
.orderId(order.getId())
.reason(status.getRiskReason())
.deadline(order.getSLADeadline())
.suggestedAction(status.getSuggestedAction())
.build()
);
}
if (status.isBreached()) {
// Alert and compensate
alertService.sendSLABreachAlert(order);
compensationService.initiate(order);
}
});
}
}
Purpose: Handle changes to orders before fulfillment
Modification Rules:
Implementation:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
@Service
public class OrderModificationService {
public Order modifyOrder(
OrderId orderId,
ModificationRequest request
) {
Order order = orderRepository.findById(orderId);
// Check if modification allowed
if (!order.canModify(request.getType())) {
throw new ModificationNotAllowedException(
order.getStatus(),
request.getType()
);
}
// Start saga for complex modifications
if (request.requiresSaga()) {
return modificationSaga.execute(order, request);
}
// Simple modifications
order.apply(request);
orderRepository.save(order);
eventPublisher.publish(
new OrderModifiedEvent(order, request)
);
return order;
}
}
Purpose: Handle order cancellations with proper cleanup
Cancellation Flow:
graph LR
CART[Shopping Cart] -->|Order Placement| OMS[Order Management]
CS[Customer Service] -->|Order Inquiries| OMS
MARKET[Marketplace] -->|External Orders| OMS
style CART fill:#f9f,stroke:#333,stroke-width:2px
style CS fill:#f9f,stroke:#333,stroke-width:2px
style MARKET fill:#f9f,stroke:#333,stroke-width:2px
style OMS fill:#bbf,stroke:#333,stroke-width:4px
graph LR
OMS[Order Management] -->|Orchestrates| INV[Inventory]
OMS -->|Orchestrates| PAY[Payment]
OMS -->|Orchestrates| WMS[Warehouse]
OMS -->|Orchestrates| SHIP[Shipping]
style OMS fill:#bbf,stroke:#333,stroke-width:4px
style INV fill:#f9f,stroke:#333,stroke-width:2px
style PAY fill:#f9f,stroke:#333,stroke-width:2px
style WMS fill:#f9f,stroke:#333,stroke-width:2px
style SHIP fill:#f9f,stroke:#333,stroke-width:2px
Inventory Service (Orchestration):
Payment Service (Orchestration):
Warehouse Service (Choreography):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Order Management Service β
β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β Saga Orchestrator β β
β β β β
β β ββββββββββββ ββββββββββββ ββββββββββββ β β
β β β Order β β Payment β βInventory β β β
β β β Saga β β Saga β β Saga β β β
β β ββββββ¬ββββββ ββββββ¬ββββββ ββββββ¬ββββββ β β
β β β β β β β
β β ββββββΌββββββββββββββΌββββββββββββββΌββββββ β β
β β β Saga State Machine β β β
β β β βββββββββββββββββββββββββββββββ β β β
β β β β States & Transitions β β β β
β β β βββββββββββββββββββββββββββββββ β β β
β β β βββββββββββββββββββββββββββββββ β β β
β β β β Compensation Stack β β β β
β β β βββββββββββββββββββββββββββββββ β β β
β β βββββββββββββββββββββββββββββββββββββββββ β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β Service Adapters β β
β β β β
β β ββββββββββββ ββββββββββββ ββββββββββββ β β
β β βInventory β β Payment β βWarehouse β β β
β β β Adapter β β Adapter β β Adapter β β β
β β ββββββββββββ ββββββββββββ ββββββββββββ β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β Persistence & Events β β
β β β β
β β ββββββββββββββββ ββββββββββββββββ β β
β β β PostgreSQL β β Kafka β β β
β β β (Orders) β β (Events) β β β
β β ββββββββββββββββ ββββββββββββββββ β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
| Layer | Technology | Version | Purpose |
|---|---|---|---|
| Language | Java | 21 | Core programming language |
| Framework | Spring Boot | 3.2.0 | Application framework |
| State Machine | Spring State Machine | 3.2.0 | Order state management |
| Database | PostgreSQL | 15.0 | Order persistence |
| Cache | Redis | 7.2 | Session and cache |
| Messaging | Apache Kafka | 3.5 | Event streaming |
| Saga Framework | Eventuate Tram | 0.32.0 | Saga orchestration |
| API Gateway | Spring Cloud Gateway | 4.1.0 | API routing |
| Circuit Breaker | Resilience4j | 2.2.0 | Fault tolerance |
| Monitoring | Micrometer + Prometheus | Latest | Metrics |
| Metric | Target | Actual | Status |
|---|---|---|---|
| Order Creation | <2 sec | 1.2 sec | β |
| Status Query | <100ms | 45ms | β |
| Throughput | 1000 orders/min | 1500/min | β |
| Saga Completion | <30 sec | 18 sec | β |
| Error Rate | <0.1% | 0.05% | β |
| Availability | 99.99% | 99.995% | β |
| KPI | Description | Target | Current | Impact |
|---|---|---|---|---|
| Order Accuracy | % orders without errors | 99.9% | 99.92% | Customer satisfaction |
| Fulfillment Speed | Avg time to ship | <24 hrs | 18 hrs | Competitive advantage |
| On-time Delivery | % meeting SLA | 98% | 98.5% | Customer retention |
| Order Modification Rate | % orders modified | <5% | 3.2% | Operational efficiency |
| Cancellation Rate | % orders cancelled | <2% | 1.5% | Revenue retention |
| Cost per Order | Total fulfillment cost | $8.50 | $7.25 | Profitability |
| Risk | Probability | Impact | Mitigation Strategy |
|---|---|---|---|
| Saga Failure | Medium | High | Compensation logic, retry mechanisms |
| Service Timeout | Medium | High | Circuit breakers, fallback strategies |
| Data Inconsistency | Low | Critical | Event sourcing, audit logs |
| Performance Degradation | Medium | High | Auto-scaling, caching |
| Risk | Probability | Impact | Mitigation Strategy |
|---|---|---|---|
| SLA Breach | Low | High | Proactive monitoring, escalation |
| Inventory Discrepancy | Medium | High | Real-time sync, reconciliation |
| Payment Failure | Low | Medium | Multiple payment providers |
| Fraud | Medium | High | ML-based detection, manual review |
Document Version: 1.0.0 Last Updated: 2025-01-20 Status: APPROVED Next Review: 2025-04-20