Strategic DDD: Splitting a Monolith into Services
On this page
Learning Objective
Identify bounded contexts and draw a context map, choose seams for extracting services from a modular monolith, use an anti-corruption layer and a gateway, keep data ownership per service, and propagate identity between services without weakening security.
Concept Explanation
Day 62 covered the tactical building blocks of domain-driven design: entities, value objects, aggregates. Strategic design is about the larger boundaries. A bounded context is the area within which a model and its language are consistent. The word customer means one thing to billing, which cares about payment methods and invoices, and something else to support, which cares about tickets and history. Trying to have one Customer class serve every team produces a model that fits none of them. Drawing contexts explicitly, agreeing on a ubiquitous language within each, and mapping how they relate is the most valuable early architectural work, and it is what tells you where a boundary between modules or services belongs.
A context map records the relationships between contexts. In a customer-supplier relationship the downstream team depends on the upstream one and negotiates its needs. When the upstream model is messy, such as a legacy system or a third-party API, the downstream context protects itself with an anti-corruption layer that translates the foreign model into its own terms, so the mess does not leak in. A shared kernel is a small, jointly owned piece of model, and should be tiny and expensive to change. The aggregate, from Day 62, is the unit of consistency, and the rule of thumb is to keep aggregates small and refer to other aggregates by identifier, since transactions should not span them.
Microservices are one way to deploy bounded contexts independently. The honest questions are why and whether. They help when separate teams need to release independently, when parts of the system have very different scaling or reliability needs, or when isolation is a requirement. They cost you a network in every call, distributed data, versioned contracts, and much heavier operations, and a system split along the wrong lines becomes a distributed monolith, which combines the disadvantages of both. Amazon's Prime Video team described in 2023 how one monitoring component built with distributed serverless pieces became expensive and moved back into a single process, reducing its infrastructure cost dramatically. The practical path is the one Day 70 started: build a modular monolith with enforced boundaries, and extract a module into a service only when a concrete need appears, using the strangler fig approach of routing traffic gradually to the new service while the old code is retired.
Data ownership is the rule that makes services independent: each service owns its data and other services access it only through its API or events, never by reading its tables. Sharing a database couples services more tightly than any code dependency. A gateway, such as YARP, can present a single front door, route requests, and apply cross-cutting policies, but it must not become the only place where authorization happens. Each service still authenticates and authorizes every request, since an attacker who reaches the internal network sees no gateway. Identity across services follows one of two patterns: pass the user's token onward when the downstream service must act as the user, taking care that it is intended for that audience, or exchange it for a new token with an on-behalf-of flow, and use the service's own workload identity when it acts for itself. Never trust identity headers set by another service unless the channel is authenticated, and never let a client supply them.
| Concept | Meaning | Use |
|---|---|---|
| Bounded context | A boundary where a model and its language are consistent | Find module and service boundaries |
| Context map | How contexts depend on each other | Decide integration style and ownership |
| Anti-corruption layer | Translation between a foreign model and yours | Isolate legacy and third-party APIs |
| Aggregate | The unit of transactional consistency | Keep small, reference others by id |
| Strangler fig | Gradually replace parts of a system behind a router | Safe extraction and migration |
| Data ownership | Each service is the only writer and reader of its tables | Access others only through APIs or events |
Worked Example: A Context Map, an Anti-Corruption Layer and a Gateway with Policy
The map documents relationships. The C# translates a third-party model, and the YARP configuration routes requests with authentication and rate limiting.
CONTEXT MAP: Task Board product
[Identity] (upstream, supplies UserId and roles)
| open host service: OIDC + claims contract
v
[Projects and Tasks] <--- customer/supplier ---> [Notifications]
| ^
| published events (TaskAssigned, TaskDone) | consumes events, owns delivery preferences
v |
[Billing] ---- anti-corruption layer ----> [Payment provider (third party model)]
Ownership: each box owns its tables. No cross-context joins. Cross-context reads go through APIs or events.// Anti-corruption layer: the payment provider's vocabulary stops at this class. The domain never sees it.
public sealed class PaymentProviderAdapter(IProviderClient provider) : IPaymentGateway
{
public async Task<PaymentOutcome> ChargeAsync(Money amount, CustomerRef customer, IdempotencyKey key, CancellationToken ct)
{
var res = await provider.CreateChargeAsync(new ProviderChargeRequest
{
AmountMinor = amount.MinorUnits, Currency = amount.Currency.Code, CustomerToken = customer.ProviderToken, Reference = key.Value,
}, ct);
// Translate the provider's statuses and errors into the domain's small, stable set.
return res.Status switch
{
"succeeded" => PaymentOutcome.Paid(res.Id),
"requires_action" => PaymentOutcome.NeedsCustomerAction(res.NextActionUrl),
"card_declined" or "insufficient_funds" => PaymentOutcome.Declined(res.DeclineCode),
_ => PaymentOutcome.Failed(res.Id),
};
}
}// YARP gateway configuration: routes with authentication policy at the edge. Each service still validates tokens itself.
{
"ReverseProxy": {
"Routes": {
"tasks": { "ClusterId": "tasks", "AuthorizationPolicy": "authenticated", "RateLimiterPolicy": "perUser",
"Match": { "Path": "/api/tasks/{**rest}" } },
"billing": { "ClusterId": "billing", "AuthorizationPolicy": "billing-admin",
"Match": { "Path": "/api/billing/{**rest}" } }
},
"Clusters": {
"tasks": { "Destinations": { "d1": { "Address": "http://tasks.internal/" } } },
"billing": { "Destinations": { "d1": { "Address": "http://billing.internal/" } } }
}
}
}// On-behalf-of: the tasks service needs to call billing as the signed-in user, so it exchanges the incoming token.
var result = await confidentialClient
.AcquireTokenOnBehalfOf(new[] { "api://billing/.default" }, new UserAssertion(incomingAccessToken))
.ExecuteAsync(ct); // a new token for the billing audience, with the user's identity
http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
// A background job has no user. It uses its own workload identity and states that it acts as the system.
var systemToken = await credential.GetTokenAsync(new TokenRequestContext(new[] { "api://billing/.default" }), ct);The context map fits on one page and should be reviewed when teams change. It is also the natural input for the architecture tests of Day 70: each context becomes a module, and a test fails when one references another's internals.
Real-World Examples
- Eric Evans introduced bounded contexts and the other strategic patterns in his 2003 book Domain-Driven Design. The strategic chapters, not the tactical patterns, are what most practitioners now credit as the lasting contribution, since they address how a large system is divided among teams.
- Netflix began moving from a monolith to services on AWS after a major database corruption in 2008 halted DVD shipping for days, a migration that took years and was accompanied by heavy investment in tooling for resilience and operations. It is often cited as a success, and it is worth noting how much platform engineering the approach required.
Review Questions & Answers
It is a boundary within which a model and its terms have one consistent meaning. Boundaries drawn around contexts follow real differences in language and responsibility, so the resulting modules or services change independently, unlike splits drawn along technical layers.
It translates between a foreign model, such as a legacy system or third-party API, and your own domain model, so the foreign terms and quirks stay at the edge. Changes in the external system then affect only the adapter.
Any service can read and change another's tables, so schema changes break others and the boundaries exist only on paper. Each service should own its data and expose it through an API or events.
The gateway is one layer, and a request may reach a service by another path or from a compromised internal component. Each service that holds data must validate the caller's identity and permissions, as defense in depth.