Book › DDD

Drawing bounded contexts and mapping their integrations

Define bounded contexts for a shop, compare REST and messaging, and use context maps, open host services, and an anti-corruption layer in Kotlin.

Drawing bounded contexts and mapping their integrations

A catalog product and an order line refer to the same underlying item, but they answer different questions. In these notes on Chapter 9 of Getting Started with Domain-Driven Development, I use that distinction to draw bounded contexts and decide how their models should meet.

The examples use Kotlin 1.9, Java 21, Spring Boot 3.x, and Spring Data JPA with Hibernate 6. The REST adapter uses Spring’s RestClient, available with Spring Boot 3.2 and later.

Let the meaning of a term change at a boundary

A shop can start with one Member and one Product entity and reuse both everywhere. Over time, the catalog needs product names and variants, orders need a snapshot of purchase prices, inventory needs quantities, and shipping needs weight and tracking information. Each view of the product changes for a different reason.

Customers have the same split. The authentication context sees a Member. An order keeps an Orderer. For a review, the relevant role might be Writer. A universal JPA entity can accumulate fields and relationships that only make sense in some of those contexts. It also gives changes to one policy a path to affect unrelated queries and lifecycle rules.

A bounded context defines where a model and its vocabulary have a consistent meaning. One context can align with one subdomain, while team ownership or legacy constraints can lead to a different grouping. I look for a model whose rules and lifecycle can be described together, then identify who owns it and how other teams use its data.

Keep ownership visible in a modular application

A complex order context can protect invariants through Spring Data JPA and DDD aggregates. A catalog search context may need mainly projections through CQRS or MyBatis. A modular monolith lets those choices coexist in one deployment. It also gives the team a way to test package boundaries before taking on network and deployment costs.

In this example, the order context uses its own Orderer and keeps a MemberId reference. It can represent the customer information needed by an order while the membership model continues to serve authentication and profile changes. The aggregate reference example covers how the ID keeps object navigation explicit.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// com/example/shop/order/domain/Orderer.kt
package com.example.shop.order.domain

import com.example.shop.member.domain.MemberId
import jakarta.persistence.AttributeOverride
import jakarta.persistence.Column
import jakarta.persistence.Embeddable
import jakarta.persistence.Embedded

@Embeddable
data class Orderer(
    @Embedded
    @AttributeOverride(name = "id", column = Column(name = "orderer_id"))
    val memberId: MemberId,

    @Column(name = "orderer_name", nullable = false)
    val name: String,
)
flowchart TD
    M["Membership (Member)"] -->|"Look up member"| O["Orders (Order / Orderer)"]
    C["Catalog (Product)"] -->|"Read price and state"| O
    R["Recommendations (OHS)"] -->|"REST response"| A["Anti-corruption layer (ACL)"]
    A -->|"Map to ProductId"| C
    O -.->|"Order completed event"| C

Choose an integration by when the answer is needed

ConcernDirect REST integrationIndirect integration through messages
ContractDepends on the endpoint and responseDepends on the broker and message schema
VisibilityCan query the upstream state during the requestDownstream state can lag behind the event
FailuresLatency or an error can propagate to the callerA broker can buffer work while a consumer recovers
Common useImmediate lookups and validationState notifications and recommendation or analytics refreshes

For a screen that needs an immediate recommendation response, the catalog declares a domain-facing interface. The infrastructure adapter makes the request and maps external item codes to local product IDs.

1
2
3
4
5
6
// com/example/shop/catalog/domain/ProductRecommendationService.kt
package com.example.shop.catalog.domain

interface ProductRecommendationService {
    fun getRecommendationsOf(productId: ProductId): List<ProductId>
}
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
41
42
43
44
45
// com/example/shop/catalog/infra/RecSystemClient.kt
package com.example.shop.catalog.infra

import com.example.shop.catalog.domain.ProductId
import com.example.shop.catalog.domain.ProductRecommendationService
import org.springframework.core.ParameterizedTypeReference
import org.springframework.http.client.JdkClientHttpRequestFactory
import org.springframework.stereotype.Component
import org.springframework.web.client.RestClient
import java.net.http.HttpClient
import java.time.Duration

@Component
class RecSystemClient(
    builder: RestClient.Builder,
) : ProductRecommendationService {

    private val restClient: RestClient = builder
        .baseUrl("https://rec.internal.example.com")
        .requestFactory(
            JdkClientHttpRequestFactory(
                HttpClient.newBuilder()
                    .connectTimeout(Duration.ofSeconds(1))
                    .build()
            ).apply {
                setReadTimeout(Duration.ofSeconds(2))
            }
        )
        .build()

    override fun getRecommendationsOf(productId: ProductId): List<ProductId> {
        val items = restClient.get()
            .uri("/api/v1/recommendations/{id}", productId.id)
            .retrieve()
            .body(object : ParameterizedTypeReference<List<RecItemResponse>>() {})
            ?: emptyList()

        return items.map { ProductId(it.itemCode) }
    }
}

data class RecItemResponse(
    val itemCode: String,
    val score: Double,
)

RestClient sends a synchronous request through its ClientHttpRequestFactory and uses message converters to deserialize the response. The sample configures a one-second connection timeout and a two-second read timeout. With retrieve(), HTTP error statuses raise exceptions by default. The empty-list expression handles an absent body. A fallback for a failed or timed-out request needs its own policy. Spring REST clients

Map upstream and downstream relationships

A context map records which context supplies a model or contract and which consumes it. I use the map to discuss coordination with the upstream and downstream teams. The integration pattern is a choice about ownership as much as a choice about protocols.

PatternRelationshipTrade-off
Open host service (OHS)An upstream provides a common contract to several downstreamsConsumers can integrate predictably, and the upstream must manage compatibility
Anti-corruption layer (ACL)A downstream translates the upstream model at its boundaryKeeps outside vocabulary out of the local model, with mapping and testing cost
Shared kernelTeams jointly own a small common modelA shared value can remove duplication, and a change needs coordination
Separate waysContexts avoid integrationEach can evolve independently, accepting duplication or a manual handoff

RecSystemClient is an ACL because it translates an external itemCode into the catalog’s ProductId. The upstream response DTO can change without spreading through local services and controllers. For a shared kernel, I keep the scope small. A stable Money value may fit. A large entity graph tends to give every team a stake in every change.

1
2
3
4
5
6
7
// com/example/shop/common/model/Money.kt
package com.example.shop.common.model

data class Money(val value: Int) {
    operator fun plus(other: Money): Money = Money(value + other.value)
    operator fun times(multiplier: Int): Money = Money(value * multiplier)
}

Check failure isolation before splitting deployment

If a product detail page calls a recommendation service synchronously, an outage can slow the core product page. For an optional feature, define a timeout, a fallback response, and a circuit breaker policy so the page can still serve the product.

  • Use an internal module boundary to verify vocabulary, ownership, and integration contracts before extracting a service.
  • Test adapter translation with an upstream response that has extra or missing fields so external contract changes stay visible at that boundary.
  • Inject timeout and error responses for optional calls. Confirm that the core read still works.
  • For an asynchronous integration, make freshness expectations explicit and test what a downstream user sees while an event is delayed.
This post is licensed under CC BY 4.0 by the author.