We are going to design a domain-driven architecture refactor. We'll map bounded contexts, aggregate boundaries, and anti-corruption layers. However, note that without a specific domain or existing system, we'll have to create a hypothetical example. Let's assume we are refactoring a monolithic e-commerce system into a more modular, domain-driven design.
Steps:
Identify the core domains and subdomains (bounded contexts).
Define aggregates within each bounded context and their boundaries.
Identify points of integration between bounded contexts and design anti-corruption layers (ACLs) to protect each context from external models.
Hypothetical E-commerce Monolith:
It has features: User Management, Product Catalog, Shopping Cart, Order Processing, Inventory, Shipping, Payment, and Notifications.
We can break this into bounded contexts:
Identity and Access Management (IAM): Handles user registration, authentication, authorization.
Product Catalog: Manages product information, categories, pricing (maybe separate from inventory).
Inventory: Tracks stock levels, reservations, and restocking.
Shopping Cart: Manages the user's shopping cart (session-based or persistent).
Order Management: Handles order creation, modification, and history.
Payment: Processes payments, integrates with payment gateways.
Shipping: Calculates shipping costs, tracks shipments, integrates with carriers.
Now, let's define aggregates for each bounded context:
1. IAM Bounded Context
Aggregate: User (with credentials, profile, roles/permissions).
The User aggregate might include related entities like Address, but if addresses are used in multiple contexts (e.g., shipping, billing) we might extract them to a separate context or share via ACL.
Note: Pricing might be a value object or a separate aggregate if it has its own lifecycle (e.g., price history). But for simplicity, let's include price in Product.
Aggregate: Category (if categories have behavior beyond being a simple hierarchy).
We might have a separate aggregate for Reservation if reservations are complex, but let's keep it simple.
Aggregate: Warehouse (if multiple warehouses and we need to manage stock per warehouse).
4. Shopping Cart Context
Aggregate: Cart (with cart items, user id, status).
The Cart aggregate might contain CartItem value objects (productId, quantity, price at time of adding?).
5. Order Management Context
Aggregate: Order (with order items, shipping address, billing address, order status, total).
The Order might be composed of OrderItem value objects.
Note: The order might need to reference product information (like product name) which is in the Product Catalog context. We should not store a copy that gets out of sync? But for historical accuracy, we might want to store the product name and price at the time of order. So we can copy that data from Product Catalog when creating the order. This is a common pattern.
Aggregate: ShippingRate (if we need to calculate rates based on weight, destination, etc.).
8. Notification Context
This context might not have aggregates in the traditional sense, but we can consider a Notification aggregate that represents a notification to be sent (with recipient, content, type, status). However, often notifications are just side effects and might not need an aggregate. But if we need to track notifications (e.g., for retries or auditing) then we can have an aggregate.
Now, we need to consider the interactions between these contexts. We'll use anti-corruption layers (ACLs) to translate between contexts.
Example interactions:
When a user adds a product to the cart (Shopping Cart context), we need to get the product price from the Product Catalog context. The Shopping Cart context should not call the Product Catalog context directly. Instead, it should use an ACL (a facade or adapter) that provides the necessary product data in a shape that the Shopping Cart context understands.
When the user checks out (from Shopping Cart to Order Management), we create an order. The Order Management context will need:
User details (from IAM context) for billing and shipping? But note: the user might have multiple addresses. We might have an Address aggregate in IAM, but then the Order Management context needs to copy the address at the time of order? Or we can have the IAM context provide an address via ACL and then the Order Management context stores a copy in the Order aggregate (so that order history remains even if the user changes their address later).
Product details (from Product Catalog) for each cart item. Again, we copy the product name and price at the time of order into the OrderItem value object.
Inventory context: we need to reserve the items. The Order Management context, after creating the order, will send a command to the Inventory context to reserve the items. This should be done via an ACL (maybe a domain event or a service call).
Payment: After order is created, we initiate payment. The Order Management context might emit an event (OrderCreated) that the Payment context listens to and then creates a Payment aggregate. Or the Order Management context might call the Payment context via an ACL to process payment.
Shipping: Once payment is confirmed, we might create a shipment. The Payment context (or Order Management context) emits an event (PaymentConfirmed) and the Shipping context listens and creates a Shipment.
Notification: Various events (OrderCreated, PaymentConfirmed, ShipmentCreated) trigger notifications. The Notification context listens to these events and sends notifications.
ACLs can be implemented in various ways: as a separate module (or layer) that translates calls between contexts, or as a set of services that act as intermediaries. In a microservices architecture, each bounded context might be a separate service, and then the ACL would be implemented within the service (as an adapter to another service) or as a separate integration service.
Let's map the ACLs:
Shopping Cart -> Product Catalog:
The Shopping Cart context needs to get product details (id, name, price) to display and to add to the cart.
ACL: ProductCatalogACL in Shopping Cart context that calls the Product Catalog service (via REST, gRPC, etc.) and translates the Product Catalog's product model to a product DTO that the Shopping Cart context uses.
Order Management -> IAM:
When creating an order, we need the user's default address (or a selected address).
ACL: IAMACL in Order Management that fetches the user's address from IAM and converts it to an address value object for the order.
Order Management -> Product Catalog:
When creating an order from cart items, we need to get the current product details (name, price) to store in the order.
ACL: ProductCatalogACL in Order Management that fetches product details for a list of product IDs and returns the necessary information.
Order Management -> Inventory:
After order is created, we need to reserve the items.
ACL: InventoryACL in Order Management that sends a command (ReserveItems) to the Inventory context. This could be a synchronous call (if we need immediate response) or an asynchronous message (event). If synchronous, we might have a ReserveItemsRequest and ReserveItemsResponse. If asynchronous, we publish an event (OrderCreated) and the Inventory context handles it.
Payment -> Order Management:
The Payment context needs to know the order amount and currency. It might get this from the Order Management context when processing payment.
Alternatively, the Order Management context might publish an event (OrderCreated) and the Payment context listens and then asks for order details via an ACL? But that would create a circular dependency? Actually, the Payment context would have an ACL to the Order Management context to get order details by order id. So when the Payment context receives an OrderCreated event, it uses the OrderManagementACL to fetch the order details and then processes payment.
Shipping -> Order Management:
Similar to payment, the Shipping context might need order details (shipping address, items, weight) to calculate shipping.
It can listen to an event (OrderCreated or PaymentConfirmed) and then use an ACL to fetch order details.
Notification -> Various:
The Notification context listens to events (OrderCreated, PaymentConfirmed, ShipmentCreated) and then uses the event data to compose a notification. It might need additional data (like user email) which it can get from IAM via an ACL? Or the event might include the necessary data (like user email) so that the Notification context doesn't have to call IAM. This is a design decision: include enough data in the event to avoid additional calls, or keep events small and let the consumer fetch additional data.
Given the above, we can draw a diagram of bounded contexts and the ACLs between them. However, since this is text, I'll describe:
Bounded Contexts:
IAM
ProductCatalog
Inventory
ShoppingCart
OrderManagement
Payment
Shipping
Notification
ACLs (arrows from consumer to provider, but ACL is on the consumer side):
ShoppingCart has ACL to ProductCatalog.
OrderManagement has ACL to IAM and to ProductCatalog and to Inventory.
Payment has ACL to OrderManagement.
Shipping has ACL to OrderManagement.
Notification might have ACL to IAM (if it needs to get user contact info and the event doesn't have it) and to OrderManagement (if it needs order details) but ideally events carry the necessary data.
Alternatively, we can use domain events to propagate information and avoid synchronous ACL calls. For example, when an order is created, the Order Management context publishes an OrderCreated event that contains:
orderId
userId
shippingAddress (as a value object)
billingAddress
orderItems (each with productId, productName, quantity, unitPrice)
totalAmount
Then the Payment, Shipping, and Notification contexts can all use this event without having to call Order Management. But note: if the event becomes too big and contains data that is already in other contexts (like productName) then we are duplicating data. This is acceptable for event-driven architectures because events are facts and we want to avoid runtime dependencies.
So, we can design:
For data that is needed at the time of an operation and might change (like product price) we use ACL to fetch the current state and then store a copy in the aggregate that needs it (like order). Then we publish events with that copied data.
For data that is static or doesn't change (like product name) we can also copy it, but note that product names might change. However, for historical orders we want the name at the time of order, so we copy.
For data that is owned by another context and we need to reference it (like userId) we store the id and then if we need more information we either copy it (if it's small and unlikely to change) or we use an ACL to fetch it when needed (but then we have runtime coupling). Usually, for aggregates that are part of a transaction, we copy the necessary data. For queries, we might use ACLs or separate read models.
Given the complexity, let's stick to the following:
When creating an order (Order Management context):
It gets the cart from Shopping Cart context (maybe by cartId, and the Shopping Cart context returns the cart with productIds and quantities).
Then, for each product, it uses the ProductCatalogACL to get the current product details (name, price) and also checks availability? Actually, inventory reservation should happen after order creation? Or we might check inventory during checkout? Let's assume we check inventory when adding to cart? But inventory can change. So typically, we reserve inventory at checkout.
So the process:
User clicks checkout -> Shopping Cart context sends a command to Order Management context to create an order from the cart.
Order Management context:
Fetches the cart (via Shopping Cart ACL? or the command includes the cart items? Let's assume the command includes the cartId and the user id, and the Order Management context uses an ACL to fetch the cart details from Shopping Cart context).
For each cart item, uses ProductCatalogACL to get product details (name, price) and also to validate that the product is still available (if we have a boolean in product catalog? or we check inventory? Actually, product catalog might not have inventory. So we might need to check inventory separately. But let's assume the Product Catalog context tells us if the product is active and the Inventory context tells us about stock. So we might need to check both? Alternatively, the Shopping Cart context might have already validated the product is available when adding to cart? But that might be outdated.
This is getting complex. Let's simplify by assuming:
The Shopping Cart context, when adding an item, calls the Product Catalog ACL to get the product and also the Inventory ACL to check stock? But then we are coupling Shopping Cart to both. Alternatively, we can have a separate "Availability" context? But let's not overcomplicate.
Alternatively, we can design the system to use eventual consistency and domain events. For example:
When a product is added to the cart, the Shopping Cart context adds the item and publishes a CartItemAdded event. Then the Inventory context (or a separate validation service) listens and checks if the product is in stock? But then we might have to remove the item if out of stock? This is event-driven and asynchronous.
Given the time, let's stick to a more traditional approach for the refactor:
We'll design the bounded contexts and aggregates as above, and for synchronous operations we use ACLs. For asynchronous, we use domain events.
But note: the question asks for mapping bounded contexts, aggregate boundaries, and anti-corruption layers. So we should produce:
A list of bounded contexts with their responsibilities.
For each bounded context, the aggregates and their boundaries (what entities and value objects they contain).
The ACLs between bounded contexts (which context uses an ACL to talk to which other context, and what is the purpose).
Let's write it in a structured way.
Bounded Contexts:
IAM
Responsibility: Manage users, roles, permissions, and user addresses (if we decide to keep addresses here).
Aggregates:
User: root entity, with credentials, profile, roles, and a list of addresses (if addresses are part of IAM). Alternatively, addresses might be a separate aggregate (Address) with a lifecycle? But typically, addresses are part of the user. However, if we have multiple contexts needing addresses (like shipping and billing) we might want to have an Address aggregate that is shared? But sharing aggregates across contexts is not recommended. Instead, we copy the address data when needed (like in Order). So we can keep addresses as part of User aggregate.
Product Catalog
Responsibility: Manage product information, categories, and pricing (but not inventory).
Category: if we have a category hierarchy with behavior, then it's an aggregate root. Otherwise, category might be a value object in Product.
Inventory
Responsibility: Track stock levels, reservations, and restocking.
Aggregates:
StockItem: root entity, identified by productId (or SKU) and warehouseId (if multiple warehouses). It holds the available quantity and reserved quantity.
Reservation: if we need to track reservations separately, then Reservation might be an aggregate root, but typically reservations are part of StockItem.
Shopping Cart
Responsibility: Manage the user's shopping cart.
Aggregates:
Cart: root entity, with cartId, userId, status (active, ordered, abandoned), and a list of CartItems. Each CartItem is a value object with productId, quantity, and the price at the time of adding (to avoid price changes while in cart? But we might want to show the current price? Typically, we show the current price but lock the price at checkout? So we don't store price in CartItem? Let's store the productId and quantity, and when displaying we get the current price from Product Catalog. But then at checkout, we use the current price. So we don't need to store price in cart. However, if we want to show the price at the time of adding, we store it. Let's assume we don't store price in cart, we always get the current price from Product Catalog. So CartItem has productId and quantity.
Order Management
Responsibility: Manage orders, order history, and order status.
Anti-Corruption Layers (ACLs):
We'll define ACLs as interfaces or adapters that one context uses to communicate with another. They are located in the client context (the one initiating the call) and translate the client's model to the server's model and vice versa.
Shopping Cart Context uses:
ProductCatalogACL: to get product details (for displaying product info in the cart). The Shopping Cart context calls getProductDetails(productIds: List<String>): List<ProductDTO>.
Order Management Context uses:
IAMACL: to get user details (especially addresses) when creating an order. Interface: getUserAddresses(userId: String): List<AddressDTO>.
ProductCatalogACL: to get product details (name, price) for the products in the cart when creating an order. Interface: getProducts(productIds: List<String>): List<ProductDTO>.
InventoryACL: to reserve items for an order. Interface: reserveItems(orderId: String, items: List<OrderItem>): ReservationResult. This is a synchronous call because we need to know immediately if the reservation succeeded.
Payment Context uses:
OrderManagementACL: to get order details (amount, currency) when processing payment. Interface: getOrder(orderId: String): OrderDTO.
Shipping Context uses:
OrderManagementACL: to get order details (shipping address, items, weight) when calculating shipping or creating a shipment. Interface: getOrder(orderId: String): OrderDTO.
Notification Context uses:
IAMACL: to get user contact information (email, phone) if the event does not contain it. Interface: getUserContactInfo(userId: String): ContactInfoDTO.
Alternatively, we can design events to carry the necessary contact info so that Notification doesn't need to call IAM. This is preferable to avoid runtime coupling.
Note: We might also have ACLs for querying data from other contexts for read models or UI. But the above are for core domain operations.
Event-Driven Interactions:
In addition to synchronous ACL calls, we have domain events:
ShoppingCartContext: publishes CartItemAdded, CartCheckoutInitiated (or we can have the OrderManagement context handle the checkout command).
NotificationContext: listens to these events and sends notifications.
These events are published in a common format (like JSON) and each event contains the minimum necessary data to trigger the next step. For example, OrderCreated event might contain:
orderId
userId
shippingAddress (as a value object)
billingAddress
orderItems (each with productId, productName, quantity, unitPrice)
totalAmount
Then the Payment, Shipping, and Notification contexts can use this event without having to call Order Management.
But note: if the Shipping context needs to calculate shipping rates, it might need more details (like weight of each item) which might not be in the event. Then it would have to call ProductCatalogACL to get product weight? Or we can include weight in the OrderCreated event? We have to decide what data to copy into the event.
This is a trade-off between event size and coupling. We want to avoid having to call other contexts synchronously after receiving an event, because then we are back to synchronous communication and potential failures. So we should try to include all necessary data in the event.
Alternatively, we can design the event to have references (like productIds) and then the Shipping context uses its own local cache or calls ProductCatalogACL to get product details. But that would be a synchronous call after an event, which might be acceptable if it's a query and not a command. However, if we are in a microservices architecture, we might have independent services and we want to avoid synchronous calls between services for scalability. So we should try to make events rich enough.
Given the complexity, we might decide:
For the OrderCreated event, include:
orderId
userId
shippingAddress (with all fields)
billingAddress
orderItems: each with productId, productName, quantity, unitPrice, and maybe weight (if we have it in Product Catalog). But weight might be in Product Catalog. So we have two options:
a) When creating the order, the Order Management context fetches the product details (including weight) from Product Catalog and includes weight in the OrderItem in the event.
b) The Shipping context, when processing the OrderCreated event, fetches the product details (weight) from Product Catalog via its own ACL.
Option (a) means Order Management context must know about weight (which is a product catalog concern) and we are copying more data. But it avoids a synchronous call from Shipping to Product Catalog. Option (b) means Shipping must call Product Catalog, which might be acceptable if Shipping is a separate service and we are okay with that dependency.
This is a decision that depends on the team's preference and the system's requirements. In event-driven architectures, we often try to make events self-contained for the downstream services to act without further lookups. So we go with option (a): when creating the order, the Order Management context gets the product details (including weight) from Product Catalog and includes them in the OrderCreated event.
Similarly, for user contact info, we can include it in the OrderCreated event (by fetching from IAM) so that Notification doesn't have to call IAM.
So, the Order Management context, when creating an order, does:
Get the cart from Shopping Cart (synchronous call via ACL? or by an event? Let's assume we have a command CreateOrderFromCart that is handled by OrderManagement, and it uses ShoppingCartACL to get the cart).
For each cart item, use ProductCatalogACL to get product details (name, price, weight, etc.).
Use IAMACL to get the user's default shipping and billing addresses (or the addresses selected in the cart?).
Then create the order (with all the copied data) and reserve items by calling InventoryACL.
If reservation succeeds, then publish OrderCreated event with all the data (order, items, addresses, user contact info?).
But note: the user contact info (email, phone) might be in IAM. We can fetch it via IAMACL and include in the event. Alternatively, we can have the Notification context fetch it from IAM if needed. But to avoid that, we include it.
So, the Order Management context becomes a kind of orchestrator for the order creation process. This is acceptable because order creation is a complex transaction that spans multiple contexts.
Now, let's write the mapping in a structured format.
Since we are to "design a domain-driven architecture refactor mapping", we can present it as:
Bounded Contexts:
IAM
ProductCatalog
Inventory
ShoppingCart
OrderManagement
Payment
Shipping
Notification
Aggregates per Bounded Context:
IAM: User (with credentials, profile, addresses)
ProductCatalog: Product, Category (if separate)
Inventory: StockItem (by product and warehouse)
ShoppingCart: Cart (with CartItems)
OrderManagement: Order (with OrderItems)
Payment: Payment
Shipping: Shipment
Notification: Notification
Aggregate Boundaries:
Each aggregate is a cluster of domain objects that are treated as a unit for data changes. The root entity is the only member that external objects can hold references to. For example:
In OrderManagement, the Order aggregate root has a list of OrderItem value objects. The OrderItem is not an entity and only exists within the Order.
In ShoppingCart, the Cart aggregate root has CartItem value objects.
Anti-Corruption Layers (ACLs):
We list the ACLs by the client context and the server context, and the interface they provide.
ShoppingCart -> ProductCatalog
Interface: ProductCatalogACL with method getProductDetails(productIds: List<String>): List<ProductDTO>
Purpose: To display product information in the cart and to validate product availability? (But note: availability is in Inventory, so maybe we need an InventoryACL too? Let's assume the ShoppingCart context also checks inventory when adding to cart? Then we need an InventoryACL in ShoppingCart as well. But we didn't list that above. Let's adjust:)
Actually, when adding an item to the cart, we might want to check if the product is available. So:
ShoppingCart uses:
ProductCatalogACL: to get product details (name, price) and also to check if the product is active? But availability (stock) is in Inventory. So we need:
InventoryACL: to check if the product is in stock. Interface: checkAvailability(productId: String, quantity: Int): Boolean
OrderManagementACL: getOrder(orderId: String): OrderDTO (with total amount, currency, etc.)
Shipping Context ACLs:
OrderManagementACL: getOrder(orderId: String): OrderDTO (with shipping address, items, and weight per item? or we calculate weight from product details? If we included weight in the OrderCreated event, then Shipping might not need to call OrderManagement again. But if we didn't, then we need to get the order details. Let's assume we included weight in the OrderCreated event, then Shipping doesn't need to call OrderManagement. But if we need more details (like the shipping address) we have it in the event. So maybe we don't need an ACL from Shipping to OrderManagement? Then how does Shipping know which orders to ship? It listens to OrderCreated and PaymentConfirmed events. So it doesn't need to call OrderManagement.
But if we want to get the order details for some reason (like to recalculate shipping because of a change) then we might need an ACL. Typically, once an order is created, the shipping details are fixed. So we can rely on the event.
So let's remove the Shipping->OrderManagement ACL and rely on events.
Similarly, Notification can rely on events (OrderCreated, PaymentConfirmed, ShipmentCreated) and if it needs user contact info and the event doesn't have it, then it can use IAMACL. But we can include user contact info in the events? Then we don't need that ACL.
So to minimize ACLs, we should try to include all necessary data in the events. Then the only ACLs we need are for the synchronous operations during the order creation process.
Let's list the necessary ACLs for the order creation process:
ShoppingCart uses ProductCatalogACL and InventoryACL when adding items to cart? Actually, when adding to cart, we might not need to check inventory? But if we do, then we need InventoryACL in ShoppingCart.
OrderManagement uses:
ShoppingCartACL: to get the cart items when creating an order. Interface: getCart(cartId: String): CartDTO
IAMACL: to get user addresses and contact info.
ProductCatalogACL: to get product details (name, price, weight) for the cart items.
InventoryACL: to reserve the items.
So we have:
ShoppingCartACL (from OrderManagement to ShoppingCart)
IAMACL (from OrderManagement to IAM)
ProductCatalogACL (from OrderManagement to ProductCatalog and also from ShoppingCart to ProductCatalog)
InventoryACL (from OrderManagement to Inventory and also from ShoppingCart to Inventory)
But note: the ProductCatalogACL and InventoryACL are used by multiple contexts. So we might define these ACLs as shared libraries? Or each context has its own implementation? Typically, each context has its own ACL implementation that translates to the server context's API. So we might have:
In ShoppingCart: a ProductCatalogACL that calls the ProductCatalog service and converts the response to ShoppingCart's DTO.
In OrderManagement: a ProductCatalogACL that does the same but might convert to a different DTO (because OrderManagement needs weight, but ShoppingCart doesn't). So they are different interfaces even though they call the same service.
But to avoid duplication, we can have a common library that defines the service client and then each context maps to its own DTO. Or we can have the server context (ProductCatalog) define a client library that both ShoppingCart and OrderManagement can use? But that would create a dependency from ShoppingCart and OrderManagement to ProductCatalog, which we want to avoid. So each context should have its own ACL that translates the server's model to its own model.
Therefore, we have separate ACLs for each client-server pair, even if they call the same server.
But to simplify the mapping, we can list:
ACLs by Client Context:
ShoppingCart Context:
ProductCatalogACL: getProductDetails(productIds: List<String>): List<ProductSummaryDTO> (with name and price)
(none, if events are sufficient) or if not, then OrderManagementACL: getOrderForShipping(orderId: String): OrderShippingDTO
Notification Context:
(none, if events include contact info) or IAMACL: getUserContactInfo(userId: String): ContactInfoDTO
But note: the Payment and Shipping contexts might need to fetch order details only if the events don't contain the necessary data. So we can design events to contain:
OrderCreated: contains orderId, userId, shippingAddress, billingAddress, orderItems (with productId, productName, quantity, unitPrice, weight), totalAmount, userContactInfo (email, phone). Then Payment and Shipping and Notification all have what they need.
Then Payment and Shipping don't need ACLs to OrderManagement. But what about when a payment is created? The Payment context might need to update the order status? Then we have a problem: the Payment context cannot directly update the Order aggregate because they are in different bounded contexts. We can do:
Payment processes payment and then publishes a PaymentProcessed event. The OrderManagement context listens and updates the order status. So Payment doesn't call OrderManagement. Similarly, Shipping publishes ShipmentCreated and OrderManagement listens to update the order with shipmentId.
So we can have a fully event-driven interaction between OrderManagement, Payment, Shipping, and Notification. Then the only synchronous calls are during order creation (from OrderManagement to the other contexts) because order creation is a transaction that must reserve inventory and get product details and user details. And also when adding to cart (from ShoppingCart to ProductCatalog and Inventory).
So the ACLs are only for:
ShoppingCart to ProductCatalog and Inventory (for adding items to cart).
OrderManagement to ShoppingCart (to get the cart), to IAM (to get user details), to ProductCatalog (to get product details for order items), and to Inventory (to reserve items).
Then after the order is created, everything else is event-driven.
This reduces the number of ACLs and makes the system more decoupled.
Let's finalize:
Bounded Contexts and Aggregates:
IAM
Aggregate: User (with credentials, profile, addresses)
ShipmentCreated (by Shipping) - contains shipmentId, orderId, tracking number, etc.
NotificationRequested (by Notification? Actually, Notification listens to events and sends notifications, so it doesn't publish events? Or it might publish NotificationSent events for auditing.)
But note: the order creation process is synchronous because we need to reserve inventory before creating the order. So we have a synchronous call from OrderManagement to Inventory. That's acceptable because it's a single transaction (within the order creation) and we need immediate feedback.
Alternatively, we can make the reservation asynchronous: OrderManagement creates the order in a pending state and then sends a ReserveItems command to Inventory. Then if reservation fails, we cancel the order. But that would require compensating actions. So it's simpler to do it synchronously.
Summary:
We have defined the bounded contexts, aggregates, and ACLs. We also considered event-driven interactions for the rest.
This is a high-level design. In practice, we would need to define the exact DTOs and events, and consider transactional boundaries, eventual consistency, and error handling.
But for the purpose of the question, this should suffice.
Based on a hypothetical monolithic e-commerce system, here's a domain-driven design refactor mapping bounded contexts, aggregates, and anti-corruption layers (ACLs). The design emphasizes ** autonomy**, explicit contracts, and isolation between contexts.
Event Design Principle: Include all data needed by downstream contexts to avoid synchronous ACL calls after the initial transaction. This ensures eventual consistency and loose coupling.
Cache: ACLs may cache read-only data (e.g., product names) to reduce calls.
Circuit Breaker: Protect against downstream failures.
Event-Driven Integration:
Events should be versioned (e.g., OrderCreated_v2).
Use a message broker (Kafka, RabbitMQ) for event distribution.
Downstream contexts handle idempotency (e.g., by orderId).
Transactional Boundaries:
Each aggregate’s invariants are enforced within its own transaction.
Cross-context transactions use saga pattern (orchestrated by Order Management for order creation).
7. Example: Order Creation Flow
User checks out → ShoppingCart emits CartCheckedOut (or OrderManagement calls ShoppingCartACL).
OrderManagement:
Calls ShoppingCartACL to fetch cart.
Calls IAMACL for user addresses/contact.
Calls ProductCatalogACL for product details (price, weight).
Calls InventoryACL.reserveStock() (synchronous; if fails, abort).
Creates Order aggregate → publishes OrderCreated.
Payment listens to OrderCreated, calls OrderManagementACL (optional) or uses event data, processes payment → publishes PaymentConfirmed.
Shipping listens to PaymentConfirmed, uses OrderCreated data (or calls OrderManagementACL), creates Shipment → publishes ShipmentDispatched.
Notification listens to all events, uses embedded contact data (or calls IAMACL), sends notifications.
This design ensures each bounded context can evolve independently, with clear contracts via ACLs and events. The aggregates protect their invariants, and anti-corruption layers prevent model leakage.
Aggregates:
Order: root entity, with orderId, userId, shippingAddress (value object), billingAddress (value object), orderStatus, orderDate, and a list of OrderItems. Each OrderItem is a value object with productId, productName (copied from Product Catalog at the time of order), quantity, unitPrice (at the time of order), and total.
Note: The Order aggregate might also have a reference to the Payment aggregate (paymentId) and Shipment (shipmentId) but these are by identity.
Payment
Responsibility: Process payments and track payment status.
Aggregates:
Payment: root entity, with paymentId, orderId, amount, currency, paymentMethod, status, transactionId, and paymentDate.
Shipping
Responsibility: Manage shipments and shipping rates.
Aggregates:
Shipment: root entity, with shipmentId, orderId, carrier, trackingNumber, shippingAddress (value object), status, estimatedDelivery, and actualDelivery.
ShippingRate: if we need to calculate rates dynamically, this might be a service rather than an aggregate. If we have fixed rates, then it might be an aggregate. But typically, rates are calculated based on rules. So we might not have a ShippingRate aggregate.
Notification
Responsibility: Send notifications to users.
Aggregates:
Notification: root entity, with notificationId, userId, type (email, SMS, etc.), content, status (pending, sent, failed), and timestamps. This aggregate is used to track notifications that need to be sent and their status.