Chapter 19 · Practice · DDD and Microservices

DDD and Microservices

BC = microservice is a half-truth. A Bounded Context is a logical boundary of the model, a microservice a physical boundary of deployment. The chapter shows when the 1:1 mapping holds, when a modular monolith works out better, and how to spot a distributed monolith in time.

Author M. Katuščák
Reading time ≈ 51 min
Difficulty expert
Published · Updated ·
In this chapter

A Bounded Context is a delimited area with one consistent domain model and one Ubiquitous Language. Bounded Context and Context Mapping described how contexts communicate with each other, and Sagas and Process Managers added coordination of a process across them: compensation instead of distributed transactions.

One question remains that every team asks sooner or later: how logical boundaries turn into physical deployment units, that is, when a Bounded Context maps to a microservice and when it does not. The chapter defends three theses that are often overlooked. The 1:1 mapping (BC = service) is only one of three options. For most teams, a modular monolith is the more reasonable starting point. And badly designed microservices are worse than the monolith they are trying to escape.

19.01 The “microservice = Bounded Context” myth#

A slogan circulates in the DDD and microservices community in various forms: “Each microservice should be one Bounded Context.” Its root is the article Microservices (2014) by James Lewis and Martin Fowler, which speaks of a natural correlation between a service boundary and a context boundary. Along the way, the correlation hardened into an equation: DDD defines the boundary of the model, microservices the boundary of deployment, so why not make them one and the same. Practice does not confirm the equation. The slogan is a half-truth that leads to wrong architectural decisions more often than to right ones.

What matters is telling apart two levels that the slogan merges into one. A Bounded Context is a logical boundary of the model: it marks out the territory where one consistent interpretation of terms, one Ubiquitous Language, and one set of invariants apply. A microservice, by contrast, is a physical deployment boundary: one built artifact, one running process, one database, one responsible team. The two levels may overlap, but they do not have to.

Sam Newman stresses this difference repeatedly in Building Microservices, 2nd ed. (2021). In chapter 2, he calls a Bounded Context a strong candidate for a service boundary. Whether a context actually gets its own deployment unit depends on team size, different scaling needs, a different release cycle, and the operational capacity of the organization. In chapter 2 of Microservices Patterns (2018), Chris Richardson describes the same decision as decomposition by business capabilities and by subdomains, and he stresses that a split must have a domain reason, not a purely technical one.

Eric Evans, who coined the term Bounded Context, looks at the matter from the opposite side. In the talk DDD & Microservices: At Last, Some Boundaries! (QCon London 2016), he argues that a logical split inside a single process does not hold up in practice. Nothing enforces it, and the boundary gradually dissolves. A separate deployment unit gives the boundary a physical enforceability that a module does not have on its own. According to Evans, the relationship is therefore one of enablement, not equality: a microservice is one way to defend a context boundary, not its definition. The book agrees with his diagnosis but offers a different answer: the boundary can be enforced inside a monolith as well, with a static check in CI.

One more misunderstanding: the community uses the term “Bounded Context” more loosely than Eric Evans defined it. Sometimes it means a mere module, other times a whole product domain. In chapter 2 of Implementing Domain-Driven Design (2013), Vaughn Vernon emphatically reminds readers that a Bounded Context is a linguistic boundary. Inside one BC, every term has a single meaning. When two teams talk about the same concept (for example, “Customer”) differently, there are two Bounded Contexts regardless of whether they run in one Symfony process or in two.

FIG. 19.1-A Three scenarios for mapping Bounded Context ↔ Service

The table summarizes how a Bounded Context and a microservice differ and at what level each is decided. Most of the anti-patterns in this chapter arise from confusing the two levels.

Aspect Bounded Context Microservice
Boundary Logical – model and language Physical – process, deploy, DB
Defined by Evans 2003, Vernon 2013 Lewis & Fowler 2014, Newman 2015
Owner A team of domain experts + developers Stream-aligned team (Skelton & Pais 2019)
Changes because of A change in the domain model Scaling, release cycle, operations
Exists in a monolith too Yes, always – as a module No, a monolith is one deployment

19.02 When 1 BC = 1 service (target state)#

The community presents a 1:1 mapping between a Bounded Context and a microservice as the default goal. It is not an automatic rule, though: it applies only where the team meets specific organizational and technical prerequisites. In Building Microservices, 2nd ed., Sam Newman sums them up under the terms “information hiding” and “independent deployability.” A service makes sense when it can be changed, deployed, and scaled independently of the rest of the system. He explains the concept of information hiding, taken from David Parnas, as early as chapter 1: hide as much as possible inside a component and expose as little as possible to the outside. He applies it to finding boundaries in chapter 2.

When to split a BC into its own service

These conditions speak for a separate deployment unit:

  • Its own stream-aligned team – the context has its own team with autonomy over the backlog, the release cycle, and operational decisions. Without one, a separate service is only extra administrative overhead. Details in Conway's Law and Team Topologies (based on Skelton & Pais 2019).
  • Its own data – the context keeps its data in a separate database (or at least in separate tables with a single schema owner). Other contexts do not touch it directly, only through an API or events. A database shared by several services is the defining sign of a distributed monolith (see section 19.04).
  • Independent release cycle – the context can be deployed without deploying other contexts at the same time. If a change in service A requires a simultaneous change in service B, these are not two services – the team has one deployment unit split into two processes.
  • Different scaling needs – the context has an order-of-magnitude different processing volume (e.g., catalog with heavy read traffic vs. ordering with low but transaction-heavy traffic) or different latency requirements. The split makes it possible to scale horizontally only the one that needs it.
  • Different stack or runtime – the context needs different runtime parameters (a different PHP version, different dependencies, different memory limits) or even a different language. Rare, but justified.
  • Different compliance regime – the context processes sensitive data (PCI DSS, special categories of personal data under GDPR) that requires strict separation from the rest of the system. Network isolation and a separate audit trail are more naturally handled in a service of its own.

Example: an online store with four services

Illustrative scenario: a mid-sized e-commerce platform with 30 engineers in four stream-aligned teams identified four Bounded Contexts in an Event Storming workshop:

  • Catalog – product catalog, search, categories, attributes. Read-heavy, small write operations, aggressive caching. A team of 8.
  • Ordering – cart, orders, status, refunds from the domain perspective. Transactional, latency-sensitive, strong consistency. A team of 9.
  • Payment – payment gateway integration, authorization, capture, recurring payments, refunds from the technical perspective. PCI DSS scope, audit trail. A team of 6.
  • Shipping – carrier integration, tracking, delivery windows. Eventual consistency with Ordering, a long write cycle (hours or even days). A team of 7.

Each of these contexts has its own team, its own DB schema, its own release cycle, and measurably different scaling needs. In this organizational reality, the decision to have four Symfony applications (catalog-svc, ordering-svc, payment-svc, shipping-svc) is defensible, provided someone can also handle running them. All thirty engineers sit in stream-aligned teams, so the platform has to come from managed services or from a small platform team formed out of them (see the operational rule). They communicate asynchronously through the Outbox and a saga of the “Place Order” kind.

The key word is defensible, not “correct.” Microservices are a decision with trade-offs: higher operational complexity, the need for distributed tracing, and eventual consistency everywhere an ACID transaction used to be enough. The following sections examine the trade-offs.

How big one service should be

Zhamak Dehghani gives a usable answer in the article How to break a Monolith into Microservices (2018) with the motto “macro first, then micro”: start with larger services built around one domain concept and split them further once the team is operationally ready for it. The order matters. Splitting an oversized service is a refactoring; untangling a web of twenty nano-services is a project for a quarter.

The second half of the answer is Newman's information hiding. A well-chosen boundary hides a lot and exposes little. You can recognize it by the fact that an ordinary change happens inside one service and touches no one else. The number of lines of code says nothing about the quality of a boundary.

19.03 When to choose a modular monolith#

A modular monolith is one deployed unit (one Symfony application, one database, one process) inside which several Bounded Contexts live as modules with enforced boundaries. From the outside, it looks like a classic monolith; on the inside, it keeps the discipline that a service boundary would otherwise enforce.

It belongs in a chapter on microservices because, for most teams starting with DDD, it is a reasonable starting point. According to Martin Fowler (MonolithFirst, 2015), microservices at the start of a project split the system before its boundaries have settled, and the resulting debt is hard to untangle. In Building Microservices, 2nd ed. (ch. 1), Sam Newman calls a monolith a sensible default architecture. For new products and startups whose domain is still being discovered, microservices are, in his view, often a poor choice. Chapter 3, on splitting the monolith, refers back to this conclusion.

It is not a consensus, though. Fowler himself admits in MonolithFirst that he does not have enough documented cases for a firm conclusion. Six days later, his site published the opposite view by Stefan Tilkov (Don't start with a monolith, 2015). According to Tilkov, splitting an existing monolith is extremely hard: its parts meanwhile build up dependencies through shared libraries, the database, and domain objects. So whoever knows they are aiming for microservices should, in Tilkov's view, start with them right away.

One variable decides the dispute: whether the boundaries inside the monolith are enforced or merely recommended. Tilkov's objection describes a monolith without boundary checks, and there it holds to the letter. With rules in CI that prevent one context from reaching into the internals of another, a monolith does not lose its ability to be split. The section on phparkitect shows what such rules look like.

Indicators that favor a modular monolith

A modular monolith works out better than microservices when any of these indicators applies:

  • Small organization – under ~30 people on the whole product. There are too few stream-aligned teams for every service to have its own team. After a split, one team then runs five services and spends half the week context switching.
  • Unstable boundaries – the product is at an early stage and the Bounded Contexts are still going through iterations. Refactoring a boundary inside a monolith is trivial (moving files and classes); refactoring across the network boundary between two services means data migration, a coordinated release, and an Anti-Corruption Layer.
  • Similar scaling needs across all contexts – if catalog, ordering, and shipping have a similar volume and profile, there is nothing to scale separately. Scaling the whole monolith horizontally is operationally cheaper than scaling four services.
  • You have no operational platform for N services – no Kubernetes, no service mesh, no centralized logging and tracing. Without them, microservices will technically run, but debugging incidents will be slow and expensive. More in the section on operations.
  • Low operational capacity – the organization cannot staff even a small platform team for CI/CD, observability, deployments, and incident response. For a mature organization, the book roughly assumes ~15% of people in platform teams (Rough proportions (75/15/10) in Conway's Law and Team Topologies). Newman repeatedly points out that microservices shift complexity into operations. Without people for operations, a modular monolith protects the team's productivity.

A modular monolith in Symfony 8

In Symfony, a modular monolith takes shape through the directory structure under src/. Each Bounded Context gets its own namespace and subdirectory, typically with three layers inside (Domain, Application, Infrastructure). The application is thus split vertically by context first and only then into layers inside; the comparison with a vertical slice by feature is in the chapter on architectural styles:

bash src/ structure – modular monolith
1src/2├── Catalog/                      # Bounded Context: Catalog3│   ├── Domain/4│   │   ├── Model/5│   │   │   ├── Product.php6│   │   │   └── Category.php7│   │   ├── Event/8│   │   │   └── ProductPriceChanged.php9│   │   └── Repository/10│   ├── Application/11│   │   ├── Command/12│   │   ├── Query/13│   │   └── Handler/14│   └── Infrastructure/15│       ├── Persistence/16│       └── Http/17│18├── Ordering/                     # Bounded Context: Ordering19│   ├── Domain/20│   │   ├── Model/21│   │   │   └── Order.php22│   │   ├── Event/23│   │   │   └── OrderPlaced.php24│   │   └── Repository/25│   ├── Application/26│   │   ├── Command/27│   │   ├── IntegrationEvent/28│   │   │   └── ProductPriceChangedReceived.php29│   │   └── Handler/30│   └── Infrastructure/31│32├── Billing/                      # Bounded Context: Billing33│   ├── Domain/34│   ├── Application/35│   │   └── IntegrationEvent/36│   │       └── OrderPlacedReceived.php37│   └── Infrastructure/38│39└── SharedKernel/                 # Small shared subset of the domain model40    ├── Domain/41    │   ├── Money.php42    │   └── Currency.php43    └── Application/

Notice two details. SharedKernel holds a small shared subset of the domain model, that is, value objects like Money and Currency whose interpretation all contexts have agreed on. Evans does not restrict the contents of the kernel, but shared entities or events enlarge the surface on which teams must agree. A change to the Shared Kernel requires the consent of all owners, and because that is expensive, the kernel must stay small. In other chapters, the App\SharedKernel namespace also carries technical base types, such as bus interfaces or middleware. That is shared code; only its domain subset forms a Shared Kernel in Evans's sense. The full pattern is covered in Shared Kernel in the Bounded Context and Context Mapping chapter. The second detail: each BC has its own Application/IntegrationEvent/, where it maps incoming events from other contexts. Section 19.08 applies the same principle between separate services.

Enforcing boundaries with phparkitect

The directory structure alone is not enough. A developer under deadline pressure will happily add use App\Billing\Infrastructure\StripeClient; to App\Ordering\Domain, and the boundary is broken. The discipline is held by an automated check in CI. For PHP, the tool is phparkitect, a static analyzer of architecture rules.

The subject of the rule is every context. A hand-written trio of rules for only two contexts leaves the rest unsupervised: a breach from Catalog into Ordering passes, because Catalog is not the subject of anything. Deriving the rules from the list closes this hole, and a new context only needs to be added to the array. Rule 2 lets through only identifiers of foreign contexts, such as App\Shipping\Domain\ValueObject\ShipmentId, because aggregates refer to each other by ID (References by identity, not by object in Aggregate Design). If you want to go further, flip the polarity to DependsOnlyOnTheseNamespaces, a whitelist that rejects a foreign dependency even without listing it.

The rule runs in CI as part of the regular quality check:

json composer.json (excerpt)
1{2    "scripts": {3        "phparkitect": "phparkitect check --config=phparkitect.php",4        "ci": [5            "@phparkitect",6            "@phpstan",7            "@phpunit"8        ]9    }10}
yaml .github/workflows/ci.yml (excerpt)
1- name: Architecture rules2  run: composer phparkitect

With these rules, a team can stay in a monolith for months or even years. CI guards dependencies between BCs in code about as firmly as a network boundary would, at an order of magnitude lower operational complexity. Shared tables, though, are invisible to phparkitect; data ownership has to be guarded by separate schemas or conventions.

When to leave the modular monolith

A modular monolith is the default state that some BCs leave over time. Four signs show that a specific module is ready for its own service:

  1. The module has a markedly different load profile, typically a read-heavy module (catalog, search) or a module with irregular peaks (notifications, batch reporting).
  2. The module has its own stream-aligned team that wants its own release cycle and has the operational capacity to take care of a separate runtime.
  3. The module needs compliance isolation (PCI DSS, special categories of personal data under GDPR).
  4. The module's boundary has not changed for the past ~6 months. The model is stable, and a refactoring across the network boundary is unlikely.

The migration procedure is covered in section 19.09 (Strangler Fig).

19.04 Distributed Monolith – an anti-pattern#

A distributed monolith has the outer shape of microservices (N separate services, N deployments, N repositories, N teams) but the inner coupling of a monolith (a shared database, synchronous calls everywhere, a coordinated release, a shared library with domain types). The team pays all the costs of microservices without their benefits; there is no more expensive way to run a monolith.

It arises in two ways. The first way: the team split the monolith into services before it identified the Bounded Contexts. The boundaries between services are accidental (by technical layer or by CRUD entity), not by domain, so the services have to talk to each other about everything. The second way: the team split correctly by BC but did not verify that each service has real autonomy. A shared database “for simplicity,” a shared library with domain types “so the code does not repeat,” a shared deployment pipeline “so the release is atomic.”

Why it is worse than a monolith

A distributed monolith combines the coupling of a monolith with the operational overhead of microservices:

  • Latency. An internal call in a monolith is a function call (~µs); a call between services is a network round trip (~ms) plus serialization, deserialization, and validation. That is a difference of three orders of magnitude on every call. With 10 nested calls, microseconds grow into tens of milliseconds.
  • Availability. If each service has 99.9% availability, a chain of ten services reaches 99.0%, which means roughly ten times the downtime.
  • Debugging. The trace of one request passes through N services. Without distributed tracing, tracking down an incident is very hard; with it, it is expensive.
  • Refactoring. Moving a field from one entity to another is an IDE refactoring in a monolith. Between services, it means a data migration, a change of API contracts, a coordinated deploy, and a period of concurrent writes to both places.
  • Test environment. Instead of composer install && vendor/bin/phpunit, you need docker-compose with ten containers and 32 GB of RAM.

A detailed analysis of the general anti-patterns that lead to a distributed monolith (microservices first, shared DB, sync everywhere) is in the Anti-Patterns and Common Mistakes chapter.

Hybrid topology – a mix of monolith and extracts

Real systems rarely fit the pure categories of “monolith” and “microservices.” The most common is a hybrid topology: one modular monolith as the core plus 1–3 extracted services for contexts that have a clear reason to exist on their own.

FIG. 19.4-A Hybrid topology – core monolith + 2 extracts with reasons

A typical scenario:

┌──────────────────────────────────┐    ┌─────────────────┐
│ Modular monolith (core)          │ ◄──┤ Reporting svc   │
│  ├── Catalog                     │    │ (read-heavy,    │
│  ├── Ordering                    │    │  separate DB)   │
│  └── Customer                    │    └─────────────────┘
└──────────────────────────────────┘
        ▲                    │
        │                    ▼
┌─────────────────┐    ┌──────────────────┐
│ Public API      │    │ Payment svc      │
│ (rate limiting, │    │ (PCI scope,      │
│  versioning)    │    │  audit isolation)│
└─────────────────┘    └──────────────────┘

A hybrid is a full-fledged goal, not a transitional state “until we finish migrating to microservices.” Three reasons speak for it in the long run:

  • The contexts in the core are tightly coupled (Catalog ↔ Ordering ↔ Customer), and refactoring is done in the IDE in a monolith; a split into three services adds an Anti-Corruption Layer for every query across a context boundary.
  • The peripheral contexts have a clear operational reason to stand alone (Payment for compliance, Reporting for its load profile, Public API for its SLA).
  • The team cannot carry N+1 services – one team owns the core monolith, and each extract adds operational debt.

De-microservicing – a return to the monolith

Going back from several services to a single process is not heresy. A counter-position to splitting at any cost has accompanied the trend from the start: Fowler formulated it in MonolithFirst as early as 2015, Newman in the same year in the text Microservices For Greenfield?, and DHH in The Majestic Monolith (2016). What is new is not the conviction but the number of teams that have a decade of operations behind them and can revisit the decision with their own data.

The most cited example is Amazon Prime Video (an article from March 2023 that drew attention in May). A story has grown around it, however, that agrees with the original text only in part:

  • What the team actually described. The Video Quality Analysis component ran as a serverless pipeline. AWS Step Functions handled orchestration, computation ran in Lambda functions, and video frames were stored in S3 in between. Costs grew because of the orchestration and the Tier-1 calls to S3. Merging the components into a single process on ECS removed the intermediate storage, data flows in memory, and infrastructure costs dropped by more than 90%.
  • What its scope was. It concerned one component of one team, not Prime Video as a product, let alone a reversal of Amazon's architectural strategy. The article appeared on the Prime Video Tech blog, which has since been shut down. The original address now redirects to aboutamazon.com, so the text is cited through the archive and reprints.
  • How the person who popularized microservices reads it. Adrian Cockcroft (Netflix, later VP at AWS) answered the wave of reactions with the text So many bad takes. In his view, it was a matter of taking a serverless prototype to production form, that is, a routine step in the development of one service, not proof against microservices in general.

Werner Vogels drew a usable conclusion from the case in the article Monoliths are not dinosaurs (2023): no single solution fits everything, and in his view the architecture needs to be revisited with every order-of-magnitude growth. Prime Video itself runs both: live sports streaming as a distributed workflow and monitoring as a single process. That is something other than “microservices failed.”

Symptoms that speak for de-microservicing:

  • Latency made up mainly of network hops between services. Such an interaction should be a function call in one process.
  • Refactoring a context requires simultaneous changes in 3+ services. The team chose the boundary badly; a refactoring in a monolith is trivial.
  • Engineering capacity > 50% on the operational platform. The team maintains Kubernetes, a service mesh, and distributed tracing instead of working on the product.
  • Infrastructure costs grow faster than traffic volume. AWS Lambda
    • API Gateway + DynamoDB across 20 services cost an order of magnitude more than a comparable EC2 monolith.
  • Incident MTTR > 60 minutes. Even distributed tracing is not enough to quickly find the root cause across N services.

The procedure mirrors the extraction from section 19.09:

The cost of microservices – what you actually pay for

In Building Microservices, 2nd ed. (ch. 1, section “Microservice Pain Points”), Sam Newman lists the areas where microservices hurt: developer experience, technology overload, cost, reporting, monitoring and troubleshooting, security, testing, latency, and data consistency. The breakdown below picks the cost side from them, and the categories are the book's own. Numbers are missing on purpose: they depend on the cloud, the region, the salary level, and on how much the team runs itself. The table therefore says what you pay for and what makes it grow, not how much it costs:

Category What you pay for in it What makes it grow
Platform team Running the orchestrator, service mesh, observability stack The number of services and environments
Cloud infrastructure More databases, message broker, load balancers, NAT The number of services
Observability APM tool licenses, log and trace retention The number of hosts, metrics, and spans
CI/CD N pipelines instead of one, integration tests through docker-compose The number of services and release frequency
Onboarding Understanding the topology, deployment, and debugging across services The complexity of the topology
Incident response A longer path to the root cause across services The depth of call chains

19.05 The contract between services – communication and data#

Once two services exist, you have to decide how they talk to each other. There are two basic patterns: synchronous communication over REST, gRPC, or SOAP, and asynchronous communication through a message broker (RabbitMQ, Kafka, NATS, AWS SNS/SQS). Most real systems combine both, and the choice determines the resulting coupling, latency, and availability.

Synchronous calls – when

  • A query (read) where the caller needs the answer during the request flow. The frontend needs a product detail to render a page; catalog-svc returns it over REST. Without the answer, it cannot continue.
  • Validation that blocks the next step. Before saving an order, ordering-svc must check with catalog-svc that the product exists and is available. The call has to be synchronous; otherwise an order for a nonexistent product could slip through.
  • Latency-sensitive operations. Real-time fraud detection, payment authorization, rate limit checks.
  • Idempotent lookup. Immutable or rarely changing data where network latency does not matter and where a cache helps.

Asynchronous events – when

  • State changes (writes) where the caller does not need to know what follows. After saving an order, ordering-svc publishes the OrderPlaced event. billing-svc, shipping-svc, and notification-svc process it when they can. The caller waits only for the local commit.
  • Reactions of other BCs that the result does not depend on. A saga advances step by step through events and commands; each step is separate.
  • An operation that can safely run with a delay. Generating an invoice, sending an email, updating a search index, generating a sitemap.
  • Multi-subscriber broadcast. One event is consumed by N independent subscribers; the publisher does not need to know about them.

The “async-first” rule

In Microservices Patterns (ch. 3), Chris Richardson formulates a recommendation: asynchronous messaging takes precedence, with sync only where it is objectively necessary. The reasons:

  • An asynchronous subscriber can be restarted, retried, and split into replicas. A synchronous caller can only wait for the response or for a timeout, and it cannot recover on its own.
  • Asynchronous messaging has better temporal decoupling: a subscriber can be temporarily unavailable without the publisher knowing. With a sync call, the caller depends directly on the uptime of the callee.
  • Asynchronous flows scale better: a message queue builds up and a worker consumes it at its own pace; a synchronous flow has to be scaled as a whole.
  • An asynchronous flow fits more naturally into the model from Event Storming, which is built on domain events.

In Symfony, asynchronous communication between services is handled by Messenger (an AMQP or Redis transport) combined with the Outbox Pattern, so that the event is written atomically together with the domain state. Details in section 19.08 Symfony specifics.

Aspect Sync (REST/gRPC) Async (events)
Coupling in time Tight – the caller waits Loose – the subscriber can be offline
Latency perceived by the user The sum of all sync calls The latency of the local write
Availability The product of the uptime of all callees Only local uptime + the broker
Backpressure The caller gets HTTP 503 The queue builds up, the worker catches up
API refactoring Coordinated release of caller + callee The subscriber has its own integration event DTO
Testability Requires WireMock / Pact / a mock Dispatching the event to a test handler is enough

How much data an event carries

The sync/async axis is only half of the decision. The other half concerns the content of the event. In the article What do you mean by “Event-Driven”? (2017), Martin Fowler distinguishes four patterns hidden under this term. Two of them matter for service integration, and in practice they get confused.

Event notification announces that something happened, and nothing more. The message carries an identifier and a timestamp; whoever wants details has to fetch them with a callback. The publisher stays lean and the contract between the services minimal, but the receiver again has a synchronous dependency on whoever sent the event, only moved one step further.

Event-carried state transfer carries in the event all the data the receiver needs. The callback goes away; the subscriber builds its own copy of the data from the event stream and survives a publisher outage. The price is data duplication and a wider contract. Every field in the payload is a commitment that someone consumes.

The example in section 19.08 belongs to the second category. OrderPlacedReceived carries orderId, customerId, the amount, and the currency, so billing-svc issues the invoice without a single query back to ordering-svc. The choice between the two modes is a conscious one, and each direction of integration sticks to one of them. Mixing both in one flow ends with nobody knowing which data is authoritative.

Data ownership – database per service

Splitting the code is the easier half of the work; splitting the data is harder. Chris Richardson lists Database per Service as a pattern of its own: each service owns its schema, and nobody else touches it, not even for reading. Ownership here means the right to change the schema without coordinating with anyone else. As soon as a second service reads from a table, the right is gone, and independent deployment goes with it.

The price of the pattern shows as soon as data from two services is needed at once. There is no JOIN across the boundary, and three options replace it:

  1. API composition. The caller requests a piece of data from each service and assembles it in memory. It works for small results. It falls apart with paging and sorting across the boundary – building one sorted page from two sources means fetching both sources in full.
  2. A read model fed by events. The service builds its own denormalized view from incoming integration events and reads only from its own. Queries are fast; the price is eventual consistency and duplication. The mechanism and its pitfalls are covered in the chapter on CQRS.
  3. A separate analytical store. Reporting and exports do not belong in the operational database. The data is replicated into a store that reporting owns and that none of the operational services queries.

Duplicated data needs a rule; otherwise it becomes a second source of truth. A copy in another service is a projection with a clear owner: one context creates and publishes the data, the others keep a read-only view and never change it behind the owner's back. If two services claim to own the same field, the boundary between them is drawn wrong, and no integration pattern will fix that.

19.06 Distributed transactions – a saga, not 2PC#

Once a domain process crosses the boundary of one Bounded Context (in a microservices architecture, also the boundary of one service), the question of consistency between services arises. The ACID transaction the team is used to from a single database does not work in a distributed environment. The classic answer used to be Two-Phase Commit (2PC, XA transactions); in a microservices architecture, however, it is practically unusable.

Why not 2PC in microservices

2PC assumes a global coordinator and participants with XA support. Neither HTTP, AMQP, nor external REST APIs offer any of that. Participants also hold locks during both phases, and when the coordinator fails, they get stuck in an in-doubt state. A detailed analysis of the reasons (missing XA support in brokers, the cost of locks, a single point of failure, violated context autonomy) is in Why not Two-Phase Commit (2PC / XA)? in the Outbox Pattern chapter.

A saga as the answer

Instead of one big distributed transaction, a saga splits the process into a series of local transactions. Each one is committed by one service to its own database. Events or commands are sent between the steps through a message broker. When a step fails, the saga performs compensating actions for all previous successful steps. That is a semantic undo, not an ACID rollback.

A saga comes in two variants:

  • Choreography – each service reacts to the events of the other services. There is no central orchestrator; the course of the process follows from the events. It suits a straightforward process without branching and without waiting for deadlines.
  • Orchestration – a Process Manager, the component that drives the saga, holds the state of the whole process and sends commands to the individual services. It pays off for processes with conditions, timeouts, parallel steps, and retry logic.

The shape of the process decides the choice, not the number of steps (Choreography has its place).

A detailed implementation of sagas in Symfony 8 (compensation, idempotence, choreography vs. orchestration, timeouts, parallel steps) is covered in the separate chapter Sagas and Process Managers. For this chapter, two things are enough: in DDD, a saga is the recommended mechanism for distributed transactions between microservices, and the price is eventual consistency and compensation logic.

19.07 Service mesh, observability, operations#

Microservices are above all an operational problem, not a programming one. A team that moves from a monolith to ten services suddenly deals with things the operating system and the Symfony framework used to take care of: routing between processes, retries, circuit breaking, mTLS, distributed debugging, service discovery, centralized logs, rate limiting. Each of these has its own tool and cost, and together they form a stack that someone has to run.

Martin Fowler named the minimum as early as 2014 in the text MicroservicePrerequisites: rapid provisioning of environments, basic monitoring, and rapid application deployment, plus an organizational shift toward DevOps. According to Fowler, whoever lacks these capabilities should build them before letting microservices into production. The rest of the section translates this minimum into today's tools.

Service mesh

A service mesh (Istio, Linkerd, Consul Connect) is an infrastructure layer that handles the cross-cutting concerns of communication between services:

  • mTLS – mutual authentication over TLS without manual certificate management.
  • Retry and circuit breaking – automatic retries and opening the circuit after repeated failures.
  • Rate limiting – protection against overload and abuse at the network layer.
  • Traffic shaping – canary deploys, A/B testing with percentage routing, blue/green switching.
  • Observability – latency, error rate, and throughput on every edge between services without instrumenting the application code.

A service mesh is usually implemented as a sidecar: next to the application container, each pod has a proxy (Envoy, linkerd-proxy) that intercepts all network traffic and applies mesh policies to it. The configuration is controlled through the control plane (istiod, linkerd-control).

When to use a service mesh: 10+ services, a multi-team organization, a requirement for mTLS without manual work, a need for advanced traffic management (canary, blue/green with percentage routing). When not to: 3–5 services, a small team, no Kubernetes. The operational overhead outweighs the benefits.

Observability – three pillars

In a monolith, a combination of structured logs and metrics was enough. Microservices add a third pillar, distributed tracing. All three then have to be handled centrally:

  • Logs – centralized log aggregation (ELK / Loki / CloudWatch). Every log line must carry trace_id and service_name; otherwise you cannot assemble the timeline of events across services.
  • Metrics – Prometheus + Grafana, or a cloud equivalent (Datadog, New Relic). Standard metrics (RED – rate, errors, duration) per service and per endpoint.
  • Traces – OpenTelemetry + Jaeger / Tempo / Honeycomb. One user request is traced across all services, and each hop has a span. Without this, debugging is practically impossible: five services and twenty logs in an incident do not add up to one timeline.

Service discovery and deployment

  • Service registry / discovery – Consul, Kubernetes service / DNS, AWS Cloud Map. Services cannot rely on static IP addresses. They need a resolver that returns an instance's address at runtime.
  • Container orchestration – Kubernetes is the de facto standard. Without it (or without an equivalent such as Nomad or ECS), you cannot realistically run more than a few services. Kubernetes itself is nontrivial, and running it is a specialization of its own.
  • CI/CD per service – each service has its own pipeline, its own release schedule, its own rollback. A shared pipeline = a coordinated release = a distributed monolith.
  • Schema registry – events through a broker (especially Kafka) need a schema registry (Confluent, AWS Glue) that versions their schema and checks compatibility.

Contract testing

The fourth symptom of a distributed monolith from section 19.04, that an end-to-end test requires all services, has an established answer: consumer-driven contracts. The consumer writes down what it expects from the provider (which fields, which types, which status codes), and a contract comes out of that. The provider then verifies it in its own pipeline, without a running consumer. The test suite stops needing the runtime of all N services and breaks up into N independent suites.

The best-known tool is Pact. Its PHP support is weaker than in Java or JavaScript, so wiring it up takes more work than in the languages the pattern comes from. A cheaper alternative is to keep the schema of integration events as a versioned artifact and check in CI that the payload from the publisher passes deserialization at every subscriber. The coverage is narrower, but it catches exactly the bug that hurts most in production. The general testing strategy is covered in the chapter on testing.

19.08 Symfony specifics – when and how#

Symfony 8 serves both architectures, a modular monolith and microservices, without a fundamental change to the code in the domain layer. The difference lies in the Messenger routing configuration. Inside a monolith, events and commands go to a sync transport (a direct call) or to a local async transport (doctrine/redis) with a worker. Between services, they go to an outbox transport, from which a relay publishes them to RabbitMQ through an amqp transport.

A modular monolith in Symfony

In a monolith, all BCs live in the same Symfony process. Integration between them goes through Symfony Messenger with a sync transport, that is, inside the process and in one DI container. The publishing BC translates the domain event at the boundary into an integration event with primitives. A handler in the other BC receives it, maps it to its own DTO, and triggers a local command. Subscribing directly to another context's domain event would violate rule 3 from the phparkitect configuration. The boundary exists purely in code, enforced by phparkitect.

Integration through a port is cheaper still: the application layer of the publishing BC exposes an interface, and the consumer implements it. No HTTP and no broker. If you later split the BCs into services, the port stays the same; only an HTTP client or Messenger appears behind it.

A microservice in Symfony

In a microservices architecture, each BC is a separate Symfony application with its own composer.json, config/, src/, and database. Integration that reacts to state changes runs asynchronously (setting aside the synchronous queries and validations from section 19.05) through Symfony Messenger with an AMQP transport (RabbitMQ), combined with the Outbox Pattern in the publisher and Inbox idempotency in the subscriber.

The rule: the publisher and the subscriber do not share the PHP event class. In ordering-svc, the publisher has its own classes: the domain App\Ordering\Domain\Event\OrderPlaced and the integration OrderPlacedIntegrationEvent built from it, from PHP: the OrderPlacedIntegrationEvent integration event in the Outbox Pattern chapter. The subscriber in billing-svc has its own App\Billing\Application\IntegrationEvent\OrderPlacedReceived, a separate class filled from the deserialized AMQP payload. The reasons are in section 19.04 (a shared library with domain types = a distributed monolith).

The outbox transport writes the event to a table in the same DB transaction as the domain commit. Instead of a dedicated outbox table with the OutboxMessage entity from PHP: the OutboxMessage Doctrine entity in the Outbox Pattern chapter, the table of the Doctrine transport (messenger_messages, queue outbox_events) serves as the outbox here. The principle is the same, but the schema belongs to Messenger. Messenger has no built-in relay between two transports, though, so messages do not flow from events_out to amqp_out on their own. The relay is custom code: a console command or a handler that reads records from the outbox table and publishes their payload to the AMQP transport. The implementation of the relay process, including polling and handling duplicates, is described in Relay process – two variants in the Outbox Pattern chapter.

The subscriber service has a mirror-image configuration: an AMQP transport for incoming messages, its own mapping to an integration event DTO, and a local command bus to trigger the reaction. The local transport is called plain async in both services, because each service has its own messenger.yaml. The monolith from the other chapters splits asynchronous messages into the async_commands and async_events transports.

IntegrationEventSerializer is a custom serializer that maps the AMQP payload (typically JSON) to a specific integration event class. The subscriber decides by the event_type string in the header, not by the PHP type, and in doing so fully decouples itself from the publisher at the code level.

Someone has to set that event_type, though. Messenger's built-in serializers do not send it. The default messenger.transport.native_php_serializer sends the whole envelope as a serialized PHP object without headers; only a PHP consumer with the same class can read it. The alternative messenger.transport.symfony_serializer puts type with the full PHP class name into the headers and derives the body from the class's properties, so every property rename changes the contract. The consumer in this section expects an event_type header and fields including the currency, so with either of them it gets Missing event_type header. The publisher therefore needs its own serializer that translates the event into the agreed shape:

php ordering-svc/src/Infrastructure/Messaging/OutboundEventSerializer.php
1<?php2 3declare(strict_types=1);4 5namespace App\Ordering\Infrastructure\Messaging;6 7use App\Ordering\Application\IntegrationEvent\OrderPlacedIntegrationEvent;8use Symfony\Component\Messenger\Envelope;9use Symfony\Component\Messenger\Transport\Serialization\SerializerInterface;10 11/**12 * Encode-only: converts an integration event to the agreed wire format.13 * The shape of the payload is part of the Published Language, not an implementation detail,14 * so it must not change along with the PHP class.15 */16final class OutboundEventSerializer implements SerializerInterface17{18    /** @param array<string, mixed> $encodedEnvelope */19    public function decode(array $encodedEnvelope): Envelope20    {21        throw new \LogicException('OutboundEventSerializer is encode-only.');22    }23 24    /** @return array<string, mixed> */25    public function encode(Envelope $envelope): array26    {27        $event = $envelope->getMessage();28 29        if (!$event instanceof OrderPlacedIntegrationEvent) {30            throw new \LogicException($event::class . ' has no agreed wire format.');31        }32 33        return [34            'body' => json_encode([35                'eventId'          => (string) $event->eventId,36                'occurredAt'       => $event->occurredAt->format(\DateTimeInterface::ATOM),37                'orderId'          => $event->orderId,38                'customerId'       => $event->customerId,39                'totalAmountCents' => $event->totalAmountCents,40                // The integration event does not carry a currency: the store in this book bills41                // in a single currency (placeWithItems() creates the items in CZK). It still goes42                // on the wire explicitly, so the receiver does not have to guess it.43                'currency'         => 'CZK',44            ], JSON_THROW_ON_ERROR),45            'headers' => ['event_type' => 'ordering.order_placed'],46        ];47    }48}

The pair “own DTO plus a translation layer at the boundary” is the Anti-Corruption Layer from Context Mapping, only implemented through a serializer instead of a client class. The other relationships from the Context Map have an equally direct counterpart in a microservices architecture:

Context Map relationship Mechanism between services
Anti-Corruption Layer Own integration event DTO and a serializer that translates the foreign payload into it
Open Host Service + Published Language A public API or a published event schema with backward compatibility
Conformist Taking over the publisher's schema unchanged, typically for reporting or a pass-through context without its own logic over the adopted data
Separate Ways No integration – the data is acquired again, because translation would cost more
php billing-svc/src/Infrastructure/Messaging/IntegrationEventSerializer.php
1<?php2 3declare(strict_types=1);4 5namespace App\Billing\Infrastructure\Messaging;6 7use App\Billing\Application\IntegrationEvent\OrderCancelledReceived;8use App\Billing\Application\IntegrationEvent\OrderPlacedReceived;9use Symfony\Component\Messenger\Envelope;10use Symfony\Component\Messenger\Exception\MessageDecodingFailedException;11use Symfony\Component\Messenger\Transport\Serialization\SerializerInterface;12 13final readonly class IntegrationEventSerializer implements SerializerInterface14{15    /**16     * Mapping of the event_type header -> integration event class.17     * When the publisher adds a new event_type, we add a line here;18     * until we do, decoding fails.19     *20     * A decoding failure MUST be a MessageDecodingFailedException.21     * Since Symfony 8.1, the receiver sends the message with it along the regular22     * retry/failure path to the failure transport. On 8.0, AmqpReceiver only rejects it,23     * so it survives only in a dead-letter exchange configured on the queue.24     * Any other exception crashes the worker, the message stays unacked, and after a restart25     * it comes back again – an endless loop over a single faulty message.26     */27    private const TYPE_MAP = [28        'ordering.order_placed'    => OrderPlacedReceived::class,29        'ordering.order_cancelled' => OrderCancelledReceived::class,30    ];31 32    public function decode(array $encodedEnvelope): Envelope33    {34        $headers = $encodedEnvelope['headers'] ?? [];35        $eventType = $headers['event_type']36            ?? throw new MessageDecodingFailedException('Missing event_type header');37 38        $targetClass = self::TYPE_MAP[$eventType] ?? throw new MessageDecodingFailedException(39            sprintf('Unknown event_type: %s', $eventType)40        );41 42        try {43            $payload = json_decode($encodedEnvelope['body'], true, flags: JSON_THROW_ON_ERROR);44        } catch (\JsonException $e) {45            throw new MessageDecodingFailedException('Body is not valid JSON', 0, $e);46        }47        if (!is_array($payload)) {48            throw new MessageDecodingFailedException('Body is not a JSON object');49        }50 51        // Mapping the publisher's payload to our subscriber-side DTO.52        // Each event type carries different fields, hence the branching here. Defensive –53        // no fields from the payload that we would not use.54        try {55            $message = match ($targetClass) {56                OrderPlacedReceived::class => new OrderPlacedReceived(57                    eventId: $payload['eventId'],58                    occurredAt: $payload['occurredAt'],59                    orderId: $payload['orderId'],60                    customerId: $payload['customerId'],61                    totalAmountCents: $payload['totalAmountCents'],62                    currency: $payload['currency'] ?? 'CZK',63                ),64                OrderCancelledReceived::class => new OrderCancelledReceived(65                    eventId: $payload['eventId'],66                    occurredAt: $payload['occurredAt'],67                    orderId: $payload['orderId'],68                    reason: $payload['reason'] ?? null,69                ),70            };71        } catch (\TypeError|\ErrorException $e) {72            // A missing field arrives as null, a field of a different type does not pass73            // strict_types – both crash the DTO constructor with a TypeError.74            // ErrorException is added by Symfony's ErrorHandler in debug mode75            // from the “Undefined array key” warning. A faulty message, not a worker crash.76            throw new MessageDecodingFailedException(77                sprintf('Invalid payload for event_type %s', $eventType), 0, $e,78            );79        }80 81        return new Envelope($message);82    }83 84    public function encode(Envelope $envelope): array85    {86        // The subscriber does not encode – the publisher does that on its side.87        // Consequence for the configuration: a transport with this serializer must not have88        // a retry_strategy, because a retry sends the envelope back through encode().89        // Failures are therefore handled by failure_transport with the default serializer.90        throw new \LogicException('IntegrationEventSerializer is decode-only.');91    }92}

The serializer is the only place in the subscriber that knows the publisher's format. A change of the payload on the publisher's side affects only this spot; the rest of the code works with its own class.

The integration event handler

After deserialization, a regular Messenger handler takes over the message and converts it into a local command of its own BC:

php billing-svc/src/Application/Handler/OrderPlacedReceivedHandler.php
1<?php2 3declare(strict_types=1);4 5namespace App\Billing\Application\Handler;6 7use App\Billing\Application\Command\CreateInvoiceForOrder;8use App\Billing\Application\IntegrationEvent\OrderPlacedReceived;9use App\Inbox\Application\InboxRepository;10use Doctrine\DBAL\Exception\UniqueConstraintViolationException;11use Symfony\Component\Messenger\Attribute\AsMessageHandler;12use Symfony\Component\Messenger\Exception\HandlerFailedException;13use Symfony\Component\Messenger\MessageBusInterface;14use Symfony\Component\Uid\Uuid;15 16#[AsMessageHandler]17final readonly class OrderPlacedReceivedHandler18{19    // The consumer's name in the inbox; the pair (event_id, consumer) is unique.20    public const string CONSUMER = 'billing.create_invoice';21 22    public function __construct(23        private MessageBusInterface $commandBus,24        private InboxRepository $inbox,25    ) {}26 27    public function __invoke(OrderPlacedReceived $event): void28    {29        // A quick shortcut for obvious duplicates. It is not authoritative –30        // a parallel delivery can slip through between the check and the write.31        // Details in /outbox-pattern#inbox32        if ($this->inbox->isProcessed(Uuid::fromString($event->eventId), self::CONSUMER)) {33            return;34        }35 36        // The eventId travels into the command. The command handler writes the pair37        // (eventId, CONSUMER) to the inbox in the same transaction as the invoice;38        // the doctrine_transaction middleware on command.bus takes care of the transaction.39        // A unique index on (event_id, consumer) rejects a duplicate, and the whole40        // transaction is rolled back.41        try {42            $this->commandBus->dispatch(new CreateInvoiceForOrder(43                eventId: $event->eventId,44                orderId: $event->orderId,45                customerId: $event->customerId,46                amountCents: $event->totalAmountCents,47                currency: $event->currency,48            ));49        } catch (HandlerFailedException $e) {50            // Without this catch, a genuine duplicate ends up in the failed transport.51            // The rollback is correct, but the message needs to be acknowledged, not retried.52            foreach ($e->getWrappedExceptions() as $wrapped) {53                if (!$wrapped instanceof UniqueConstraintViolationException) {54                    throw $e;55                }56            }57        }58    }59}

The pattern guarantees four properties:

  • No shared code between services – billing-svc has no package in its composer.json that would define ordering-svc classes.
  • Payload versioning – the publisher adds a field, and the subscriber ignores it until it needs it. No coordinated release is needed. Only a breaking change needs a new event_type (for example, ordering.order_placed.v2): a renamed or removed field, or a different meaning of a value.
  • Idempotence – a duplicate delivery (a broker failover, a worker restart) has no effect. The Inbox table in billing-svc holds the processed pairs of eventId and consumer, with the same interface as in Idempotent Inbox – the subscriber side in the Outbox Pattern chapter. The check in the integration event handler is only a shortcut for obvious duplicates; what is authoritative is the unique index on this pair and the inbox write in the same transaction as the domain change. A check separate from the write does not stop a parallel duplicate. The handler must, however, catch a rejected duplicate and acknowledge the message; otherwise it ends up in the failure transport even though the system behaved correctly.
  • Testability – the handler is tested with new OrderPlacedReceived(...), without a network stack.

The economics of microservices in PHP

The literature on microservices was written around long-running runtimes: the JVM, .NET, Node. PHP in classic php-fpm mode does the math differently, and several recommendations shift as a result. Books on microservices lack this part of the calculation, because their authors did not need it.

The application is shared-nothing: it bootstraps on every request and keeps neither an in-process cache nor a connection pool between requests. Each extracted service therefore pays its own bootstrap on its own request. On its own, that is a small thing, but it multiplies with the number of hops in the chain.

The behavior of a synchronous call matters more. Node or Go wait for a response with non-blocking I/O practically for free. A php-fpm child, by contrast, stays occupied for the whole round trip and serves no one else. The number of children is fixed, so a fan-out to three services consumes three times the caller's concurrency capacity. The “synchronous orchestration of everything over REST” anti-pattern from section 19.10 is therefore more expensive in PHP than in the environment the source literature comes from.

There are two ways to mitigate this:

  • Concurrent requests through HttpClient. Symfony HttpClient streams responses, so three calls can be sent at once and awaited at the same time. Three serial ->getContent() calls needlessly add up the latencies.
  • Worker modes. FrankenPHP, RoadRunner, or Swoole keep the application in memory between requests. The bootstrap goes away, and the cost of a synchronous call drops. The price is that services with request-bound state must implement Symfony\Contracts\Service\ResetInterface; otherwise the state leaks into the next request.

A cheap deployment unit works in the opposite direction: there is nothing to compile, the JVM warm-up goes away, and an image builds in minutes. Technically, extracting a service is easier in PHP than in Java, so the cost lies almost entirely in operations. If anything, that strengthens the chapter's main thesis.

In Symfony, operations take a concrete form. Every service that consumes messages needs its own set of workers: messenger:consume under Supervisor or systemd, --memory-limit and --time-limit against growing memory consumption, and messenger:stop-workers in every deploy script. Five services mean five such configurations and five places where you can forget to restart the workers after a deploy. Messenger also offers two newer switches for operations: --keepalive prevents premature redelivery for long-running handlers, and --fetch-size (since Symfony 8.1) reduces the number of queries to the transport during batch processing.

19.09 Gradual migration from monolith to microservices#

Most real systems do not start out as greenfield microservices. They start as a monolith that begins to hurt over time, and only then comes the question of which part to separate. The section builds on Newman's recommendation in Building Microservices, 2nd ed. to avoid rewriting everything at once (a big-bang rewrite). A big rewrite fails far more often than the team expects when planning.

Strangler Fig Pattern

Strangler Fig (Martin Fowler, 2004; under this name since 2019) replaces a system piece by piece: a facade in front of the monolith redirects the traffic of individual Bounded Contexts to newly extracted services, and a rollback remains possible the whole time.

Fowler's current version of the text adds the concept of transitional architecture: the facade, the dual write, and the routing layer are temporary scaffolding that does not belong in the target state and is torn down after the migration. Whoever keeps it “just in case” is left with a permanently more complex topology than they need.

The full account of the pattern is in the Migrating from CRUD to DDD chapter: the principle of coexistence of the old and new parts, the project structure, and a comparison with a direct rewrite. This section covers only what is specific to extraction into separate services: the order of the phases and the criteria for when to stop.

Three migration phases in practice

A procedure for a Symfony team that has a monolith without enforced boundaries:

Phase 1: Modular monolith (3–12 months)

Goal: identify the Bounded Contexts and enforce their boundaries inside one deploy. Nothing is migrated anywhere – the structure is refactored.

  • Run Event Storming or Domain Storytelling with domain experts. Identify the BCs.
  • Reorganize src/ into a src/<BC>/ structure. Each BC has its own Domain / Application / Infrastructure.
  • Introduce phparkitect rules and enforce them in CI. Without this step, the boundaries are fictional.
  • Convert cross-BC integration to Domain Events + Symfony Messenger (sync transport for now).
  • Identify schema ownership, that is, which table belongs to which BC. A table that belongs to two BCs means either a Shared Kernel (rarely) or a badly drawn boundary.

Phase 2: Strangler Fig – the first extraction (1–3 months for the first service)

Goal: pull the first BC out into a separate service. Choose the one with the strongest reason (typically a read-heavy module with a different load profile or a module with compliance isolation).

  • Build a facade (a Symfony API gateway, nginx routing, AWS API Gateway) in front of the monolith.
  • Build a new Symfony project as a separate service. Copy (never git mv) the code of the target BC from the monolith.
  • Data migration: gradually replicate the target BC's tables into the new DB. A dual-write period follows, when both the monolith and the new service write. Switch read traffic over gradually. Dual-write is a deliberate exception here: the Dual-write problem section of the Outbox Pattern chapter describes it as a problem, because writing to two stores is not atomic. During a migration, it is tolerable as a controlled, time-limited state, with one store as the source of truth and with regular reconciliation that finds and fixes differences. Do not turn it into a permanent solution.
  • Move cross-BC events to Messenger's AMQP transport. The subscriber has its own integration event DTO (section 19.08).
  • Once things stabilize, delete the remains of the target BC from the monolith.

Phase 3: Iterate or stop

Goal: decide whether to continue with the next BC, or stop and live with a hybrid architecture (monolith + 1–2 services). A hybrid is a full-fledged goal, not a temporary phase. Many successful systems never reach a pure microservices architecture, because they have no reason to.

  • Measure whether the first extraction met expectations (better scaling, faster releases, better ownership). If not, stop and analyze why.
  • Continue with the next BC that has a clear justification.
  • Invest continuously in the operational platform. Without it, each further extraction hurts productivity.

19.10 Anti-patterns in microservices and DDD#

The five most common anti-patterns when combining DDD and microservices, each with a concrete symptom and fix.

1. Microservices first (before identifying BCs)

Symptom: the team split the monolith into services before running Event Storming or Domain Storytelling. The service boundaries follow technical layers (auth-svc, user-svc, db-svc) or CRUD entities (order-svc, customer-svc, product-svc), not domain contexts.

Consequence: a domain process has to pass through five to ten services and runs into synchronous coupling everywhere. It is a distributed monolith by definition.

Fix: stop, identify the real BCs through Event Storming, and map the current services to the target BCs. It often turns out that three existing services belong to one BC. Merge them into a modular monolith, and only then decide whether the BC should get its own service.

2. A database shared across services

Symptom: service A and service B both read from (or even write to) the same tables. “Simple integration,” “atomicity,” “no time to do it right.”

Consequence: any schema change breaks every service that consumes the table. No service owns the data. Every database refactoring means a coordinated migration of all consumers.

Fix: split the data by BC. Replace cross-BC reads with an API call (sync) or replication through events (async, eventually consistent). No cross-BC join at the DB level. The canonical form of the anti-pattern with code samples is described in Anti-Patterns and Common Mistakes.

3. Synchronous orchestration of everything over REST

Symptom: every domain operation is a chain of sync HTTP calls. Handling an order: ordering calls payment, payment calls fraud-detection, fraud-detection calls ai-scoring, ai-scoring calls customer, ... One user request = 12 nested HTTP calls.

Consequence: latency adds up to seconds, availability multiplies, and outages trigger a retry storm.

Fix: apply the async-first rule (section 19.05). State changes through events, validation queries synchronously with a cache, no synchronous side effects (writes) across a service boundary. Use a saga to coordinate processes.

4. One deployment artifact for N services

Symptom: the CI/CD pipeline builds all services together. The release schedule is centralized (“we have a deployment train,” “release window on Tuesday”). A change in one service cannot be deployed without the others.

Consequence: all services must be compatible at every moment. Gradual rollout, feature toggles, and quick rollback are all impossible. A coupled deploy is the defining sign of a distributed monolith.

Fix: give each service its own pipeline, its own release cycle, and its own rollback. Cross-service compatibility is handled by schema versioning and by versioning integration events (the subscriber accepts both the older and the newer version).

5. Nano-services

Symptom: a service of 50 lines of code, with its own deploy and its own DB. The “single responsibility principle” applied to a deployment unit. A hundred services for a product with 30 engineers.

Consequence: a hundredfold operational overhead. Every service needs monitoring, alerts, CI/CD, a runtime, a knowledge base, an on-call rotation. A team of 30 people has 0.3 engineers per service. Nobody has deep ownership; everyone “maintains.”

Fix: aggregate closely related services into one, typically by merging them into the BC they belong to. “Microservice” means an independently deployable unit, not a “small service.” Size is secondary. In Building Microservices, 2nd ed., Sam Newman bases service boundaries on information hiding, coupling, and cohesion, that is, on the domain, not on technical gymnastics.

A more general analysis of anti-patterns in DDD (not only in microservices) is in the Anti-Patterns and Common Mistakes chapter.

19.11 Summary#

A Bounded Context is a logical boundary of the model, a microservice a physical boundary of deployment. The mapping between them is 1:1, 1:N, or N:1, and the “BC = microservice” slogan serves only as a starting hypothesis.

The chapter carries a single decision: where the boundary between processes runs. For a team of up to thirty people, a modular monolith guards it most cheaply. In code, phparkitect enforces the dependency rules between BCs for a fraction of the operational complexity. A BC deserves a separate service when it meets at least four conditions from section 19.02: its own stream-aligned team, its own data, an independent release cycle, different scaling needs, a different stack, compliance isolation. Three or fewer means staying in the monolith.

Once the boundary runs across the network, three rules hold it. Data has one owner: one schema with two writers is a defect, and a query across the boundary is handled by API composition, a read model fed by events, or an analytical store. Communication is async-first. Sync remains only for queries in the request flow and blocking validations, because tight temporal coupling takes away exactly what microservices were created for. And consistency between services is ensured by a saga with compensations, not by 2PC, which is not usable in this stack.

Symfony Messenger serves both worlds: a sync transport inside the monolith, an AMQP transport with the Outbox between services. One rule cannot be broken: the publisher and the subscriber do not share the PHP event class; the subscriber has its own integration event DTO. A shared library with domain types is among the symptoms of a distributed monolith from section 19.04, just like a shared database and synchronous calls everywhere. And a distributed monolith is worse than the monolith you started with.

The way out of a monolith goes through Strangler Fig: one BC after another, with a facade and with a period of concurrent writes in which one store remains the source of truth (phase 2). A big-bang rewrite usually fails. And if you do not have an orchestrator, distributed tracing, service discovery, and CI/CD per service, the answer to the boundary question is a modular monolith anyway.

19.12 Further reading#

Frequently asked questions

What is the right size for one microservice?

Size is not the primary criterion; independent deployability is. A microservice is the right size when one stream-aligned team can change, deploy, and run it on its own. That can be 500 lines of code or 50,000. In Building Microservices, 2nd ed., Sam Newman recommends that size follow from the domain (one Bounded Context or a logical part of one), not from a technical ideal of a “small service.” Details in the When 1 BC = 1 service (target state) section and in the nano-services anti-pattern.

Can I have 2 Bounded Contexts in one microservice?

Yes, and it is often the right decision. That is the definition of a modular monolith or a small “micro-monolith.” If two BCs share a stream-aligned team and similar scaling needs, running them as two separate services is overhead without benefit. The main condition: the boundary between the BCs inside the service must be enforced by code (typically by phparkitect rules). If the boundaries are bypassed, you have an unstructured monolith, not a modular monolith. Details in the When to choose a modular monolith section.

When should you move from a monolith to microservices?

When you have a specific pain that microservices actually solve: typically different scaling needs of one module, different compliance regimes, or organizational separation (different stream-aligned teams with different release cycles). Without a specific pain, the move brings only operational complexity. The procedure always goes through Strangler Fig (gradual extraction of one BC at a time), never a big-bang rewrite. Details in the Gradual migration from monolith to microservices section.

What is a BFF (Backend For Frontend), and where does it belong in DDD?

A BFF is a pattern in which each frontend (web, mobile, partner API) has its own backend aggregator that calls downstream microservices and assembles a view model tailored exactly to that client. In DDD terminology, a BFF is a downstream consumer of the services it calls: it uses their Open Host Service and Published Language and builds an Anti-Corruption Layer against their models. It is not an OHS itself. An OHS is a protocol open to all consumers, whereas a BFF serves a single client. It carries no domain logic; it is an integration layer with its own model of screens, which can be treated as a separate context (typically “Web Frontend”).

GraphQL Federation as a replacement for microservices integration?

GraphQL Federation lets several services expose their part of the schema and lets a gateway (Apollo Router) merge them into one schema from the client's point of view. For read operations across microservices, it shields the client from the physical split. For write operations, federation does not solve distributed transactions; you still need a saga. Federation therefore fits as a facade for reads, not as a replacement for an event-driven architecture.

Which service owns customer data across BCs?

No “central” Customer service. Each Bounded Context has its own view of the customer that matches its language and context. Ordering sees Customer as a delivery address and a payment preference, Billing as an invoicing party with a VAT ID, Support as an entity with a ticket history. The same customerId, different models. In the bliki entry BoundedContext (2014), Martin Fowler uses the term polysemic concept for this situation: one concept with a different meaning in each context and with an explicit mapping between them. If you decide to designate one BC as the “source of truth” for customer identity, the other BCs take only the customerId from it and model their own attributes themselves. Details in Bounded Context and Context Mapping.