Chapter 20 · Practice · DDD in Practice – Where It Hurts

DDD in Practice – Where It Hurts

Twenty places where DDD in PHP and Symfony hurts: transactions across several aggregates, Doctrine mapping, the Outbox, Messenger debugging, validation, the Anti-Corruption Layer, convincing management, and more. Each with the problem and a solution.

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

The previous chapters covered both the theory and the advanced patterns: from the DDD Building Blocks through CQRS and Event Sourcing to Sagas and Process Managers. Implementing DDD runs into problems that textbooks usually leave aside: architectural principles collide with the reality of the framework, the database, the asynchronous infrastructure, and team dynamics.

What follows is a catalog of 20 problems that teams adopting DDD in PHP and Symfony run into. Most of them are friction with a specific technology: the Doctrine Unit of Work, Symfony Messenger, the Outbox Pattern, authorization, and race conditions. For most problems you will find a description of the situation, the cause, and the recommended solution, with a code sample where it helps.

Code and modeling anti-patterns (the anemic model, Primitive Obsession, God Aggregate, a database shared between contexts) are covered in Anti-Patterns and Common Mistakes. The decision framework for whether to use DDD at all is in When Not to Use DDD.

20.01 A – Doctrine vs. the domain model#

Doctrine ORM has its own internal model: Unit of Work, Identity Map, lazy loading. A domain model with immutable value objects, private constructors, and invariants collides with it in six places.

A1. Transactions across aggregates and the Doctrine Unit of Work

Problem: Vernon's rule of thumb says that one transaction modifies at most one aggregate. In practice, though, there are situations where changes to two aggregates need to be stored atomically. For example, closing a warehouse transfer (state Transferred) and at the same time confirming the stock reservation that the transfer fulfills. Doctrine shares one EntityManager (and with it one Unit of Work) across the whole application; a single flush() writes everything the EM tracks.

Cause: The Doctrine Unit of Work lives for the whole request (or the handling of one message). It holds an identity map of all loaded entities, and on flush() it stores all changes at once in a single database transaction. For CRUD this is convenient. In DDD it means that an unintentionally modified entity from another aggregate gets written along with your intended change.

Solution: The need to change two aggregates atomically is first of all a diagnosis. It usually points to a badly drawn aggregate boundary. The fix then moves the boundary, or performs the second change in its own transaction via a domain event, or via a saga. A shared Bounded Context and a shared database are only the technical precondition for one transaction, not its justification. Only the exceptions discussed in the When to break the rule section of the Aggregate Design chapter are defensible.

When the team accepts such an exception deliberately, the Application Service acts as an explicit transaction boundary. Doctrine offers wrapInTransaction() for this, which the documentation recommends over a manual beginTransaction() / commit() precisely so that the developer does not forget the rollback.

A2. A “dirty” EntityManager and unwanted changes

Problem: In actions that mostly read (preparing data for an API response, building a read model), you load an entity from the database, compute a value from it, but store nothing. Still, the first flush() anywhere in the request (say, in another part of the application) writes changes to the database. The reason is that you quietly modified an entity that Doctrine is still tracking.

Cause: The Doctrine Identity Map remembers every loaded object, and on flush() the Unit of Work compares the current state with the snapshots taken at load time (change tracking). A getter that changes state internally (for example, stores a derived value in a mapped property) is evaluated by Doctrine as a change.

Solution: three approaches, depending on the situation.

Situation Solution
Read model in a single request $em->detach($entity) after loading – the EM stops tracking the entity (available in ORM 2.x and 3.x; note: merge(), by contrast, was removed in ORM 3.x)
Complex read queries Use HYDRATE_ARRAY or raw SQL via $em->getConnection() – the EM does not hydrate objects
The whole controller is read-only Queries with the Query::HINT_READ_ONLY hint – the UnitOfWork does not check entities loaded this way on flush(). The #[ORM\Entity(readOnly: true)] mapping does the same, but for the class across the whole application: it only suits an entity that nothing modifies. Doctrine has no read-only EntityManager

ORM 3 also removed the usual escape hatch. The arguments flush($entity) and clear($entityName) are gone, and both methods silently ignore them, because PHP does not report a surplus argument to a user-defined method. That is worse than an error: clear('Order') looks like a targeted detach, but it detaches the entire Identity Map. “I will save only this aggregate” cannot be expressed: flush() always writes the whole Unit of Work, including every unintentionally tracked entity.

A3. Mapping complex Value Objects

Problem: Doctrine #[Embedded] works well for simple VOs (first name + last name → two columns). It hits its limits with polymorphic VOs (different kinds of prices), nullable VOs in collections, VOs with their own serialization logic, and VOs mapped to a data type other than the default (enum, JSONB, custom SQL type).

Solution: a custom Doctrine Type. Extend the abstract Type class from Doctrine\DBAL\Types; the type defines how a PHP object is converted to an SQL value and back.

Register the type in config/packages/doctrine.yaml:

yaml config/packages/doctrine.yaml (excerpt: custom type)
1doctrine:2    dbal:3        types:4            money: App\SharedKernel\Infrastructure\Doctrine\Type\MoneyType

Then use it in the entity:

php snippet.php
1#[ORM\Column(type: 'money', nullable: true)]2private ?Money $price = null;

A4. Lazy loading and domain methods

By default, Doctrine loads associations lazily: it puts a proxy into the property, which is initialized only on first access. A domain method such as totalAmount() or items() knows nothing about it and implicitly relies on an active database connection. When the record the proxy points to has meanwhile disappeared from the database, initialization fails with EntityNotFoundException. Detaching the entity does not cause the error by itself. The proxy initializer does not check the state in the UnitOfWork and reads the data through the persister as long as the connection is open. This applies to classic proxy classes and to PHP 8.4 native lazy objects alike.

You cannot avoid native lazy objects, either. Since ORM 3.5, turning them off on PHP 8.4+ is deprecated, and in version 4.0 the option disappears entirely; Configuration::enableNativeLazyObjects(true) is the target state. Anyone who builds behavior on the details of generated proxy classes today relies on an implementation that is on its way out.

A lazy proxy is an infrastructure concept. The domain model must not know about it, yet it carries it in memory. The loading strategy is therefore decided by the repository or the specific query.

Solution, by the complexity of the situation:

Situation Solution
Collection needed only sometimes The repository offers two methods: get() (lazy) and getWithItems() with a fetch join in DQL – that one really issues the JOIN
Collection always needed with the aggregate fetch: 'EAGER' on the association – for OneToMany a second query in batches (default batch of 100 parents), not a JOIN. ManyToMany and OneToMany with indexBy get no batching, and N+1 remains
Serialization / JSON response Never serialize the aggregate directly – build a DTO from the loaded data inside the transaction

The order of the rows in the table is not random. A fetch join in DQL is the first choice because it applies only to a specific query. fetch: 'EAGER' in the mapping acts globally, and for to-many associations it does not do what most people expect. It issues a JOIN only for to-one associations, and even there Doctrine reserves the choice between a LEFT JOIN and a second query. For more on choosing a strategy, see Read Models, Projections, and Performance.

A5. Identity generation – when and where

Problem: By default, Doctrine generates IDs in the database (SEQUENCE, AUTO_INCREMENT). A newly created aggregate has no ID until Doctrine persists it (SEQUENCE) or flushes it (AUTO_INCREMENT). That breaks a domain invariant: every aggregate must have an identity from the moment it comes into existence.

Cause: Generating IDs in the database is convenient, but it ties the creation of identity to infrastructure. The domain model should not know about the database; identity belongs to the domain.

Solution: Create the identity in PHP code, not in the database, and do it before the aggregate is stored. The canonical factory has the form Order::place(OrderId $id, CustomerId $customerId): the caller creates the identity via OrderId::generate(), and the aggregate only accepts it. Doctrine is configured without a generator; you hand it a ready-made ID. Three chapters add another factory to the same class, because without it they could not show their topic. Aggregate Design has placeWithFirstItem(), where the signature itself already enforces the invariant “an order has at least one item.” The Outbox Pattern has placeWithItems(), because it needs the list of items in the event payload. Supporting Tactical Patterns has placePhysical() and placeDigital(), on the same principle, only under names that say what kind of order the factory creates. It is always a different name, never a different version of place(). Two incompatible signatures of one method could not coexist in a real project. The derived factories do not accept an identity; they create one themselves via OrderId::generate(). The rule applies to both paths: identity comes into existence in PHP code before storing, never in the database.

The constructor stays clean because of reconstitution. Doctrine bypasses it during hydration, but a custom mapper or an event stream may call it. The event is therefore created in the factory; see Aggregates and domain events: the lifecycle.

The identifier mapping in Doctrine follows. The sample maps a primitive string; the value object OrderId is converted to a column by a custom Doctrine type, see section A3:

php snippet.php
1#[ORM\Id]2#[ORM\Column(type: 'string', length: 36)]3// Without #[ORM\GeneratedValue], Doctrine does not assign the ID;4// per the documentation, strategy: 'NONE' is the same thing, only more verbose5private string $id;

A6. Polymorphism and the discriminator map

Problem: You need to model a hierarchy, for example different kinds of delivery (HomeDelivery, PickupPoint, LockerDelivery). Doctrine offers InheritanceType::SINGLE_TABLE or JOINED with a discriminator map. The cost is concrete, not a matter of principle. An explicit map is written on the root entity, so a new subtype means touching a class that has no reason to know about it. Without a map, Doctrine generates one itself from the short class names; renaming a class then changes the expected value in the discriminator column. With SINGLE_TABLE, on top of that, every column specific to one variant must be nullable for all the others; with JOINED you pay for a JOIN on every read. The documentation explicitly warns about its performance impact. And because this is schema, every addition to the hierarchy means a database migration, not only a new class.

Solution: two alternatives to the default discriminator map.

Approach When to use Drawback
Value Object with a type field The variants differ mainly in data, with little behavior Every type-dependent behavior means a switch over the enum
Flat table + Custom Type The variants have different behavior The Custom Type must build the class of the right variant from JSON; the JSON column loses type safety
Discriminator map (Doctrine default) Few variants, a stable hierarchy A schema migration for every variant, nullable columns

In most DDD scenarios, the Value Object with a type field proves its worth: one enum column for the type, one JSON column for the variant-specific data. The logic moves into domain methods that accept the VO as a parameter, not into inheritance.

Even this choice is not free. The switch over the enum does not disappear; it only moves from inheritance into a domain method. And whatever you store in a JSON column, you stop filtering, indexing, and aggregating in SQL. So the choice is: pay with schema migrations, or with queryability.

20.02 B – Asynchronous infrastructure#

Symfony Messenger and asynchronous queues bring distributed communication, and with it distributed problems: messages get lost, get delivered twice, or arrive in the wrong order. The four most common pains follow.

B1. Outbox Pattern – guaranteed delivery of integration events

Problem: A handler stores an aggregate and, in the same method, sends an integration event to the broker. Under the canonical doctrine_transaction middleware, flush() only writes SQL; the commit comes after the handler returns. The event therefore leaves before it is certain that the change in the database will stay. When the commit fails, subscribers receive a phantom event: Payment charges money for an order that does not exist. Without the middleware, the opposite can happen. flush() commits on its own, the server crashes before sending, and the event is lost. The payment went through, and the warehouse never learns about it.

Cause: The database commit and $bus->dispatch() to the broker are two separate operations with no atomic guarantee. They cannot be wrapped in one transaction, because the database and the message broker are different systems. Both scenarios are analyzed in detail in Naive publishing implementation – anti-pattern.

Solution: store the event in an outbox table in the same transaction as the aggregate, and leave sending to a separate process. Atomicity is then held by the database transaction. Domain events for listeners inside the context do not need the outbox: the synchronous event.bus delivers them in the same transaction.

The table schema, two variants of the relay process, the idempotent inbox on the receiver side, operational metrics, and the procedure for migrating an existing project are covered in the separate chapter Outbox Pattern.

B2. Debugging a lost message in Messenger

Problem: A message went to an asynchronous queue and the worker is running, but the handler was never called. The following procedure shows where the message ended up.

Debugging procedure:

1. Check the failed transport:

bash snippet.sh
1php bin/console messenger:failed:show

If the message is there, it is shown with its error. Process it again:

bash snippet.sh
1php bin/console messenger:failed:retry

2. Turn on verbose logging: In config/packages/monolog.yaml, add a handler for the messenger channel at the debug level. Every send, receive, and handling is then logged.

3. Correlation ID middleware: Add a custom middleware that assigns a UUID to the initiating message and logs it both on send and on receive. Messages sent while it is being handled (derived events, further commands) inherit the ID, so in the log you find the whole flow by a single ID. The causation ID, that is, the immediate cause of a specific message, is a different piece of data, and the middleware does not handle it.

Register the middleware in config/packages/messenger.yaml on every bus the flow passes through. The middleware key overrides the list from the Symfony Messenger configuration for CQRS, which is why the excerpt also repeats validation and doctrine_transaction:

yaml config/packages/messenger.yaml (excerpt: correlation ID)
1framework:2    messenger:3        buses:4            command.bus:5                middleware:6                    - App\SharedKernel\Infrastructure\Messenger\CorrelationIdMiddleware7                    - validation8                    - doctrine_transaction9            event.bus:10                default_middleware:11                    enabled: true12                    allow_no_handlers: true13                middleware:14                    - App\SharedKernel\Infrastructure\Messenger\CorrelationIdMiddleware

B3. Idempotent handlers

Problem: Messenger guarantees at-least-once delivery, not exactly-once. If a worker handles a message but crashes before the acknowledgment (ack), the broker delivers the message again. The handler processes it a second time. The result can be a double payment, a duplicate order, or a duplicated email.

Solution: an Idempotency Middleware with a deduplication table. Every command carries an IdempotencyStamp with a key derived from the business operation, for example payment.capture:{orderId}. Before handling, the middleware checks a database table. When the key exists, it skips the message.

The middleware sits on the bus, not at the handler, and is therefore suitable only for commands with a single handler. For an event with several listeners, the stored key would skip all of them, including those that have not processed it yet. Events are deduplicated by the inbox with the (event_id, consumer) key from the Outbox Pattern chapter.

The whole mechanism rests on the word “derived.” A UUID generated at send time does not work as an idempotency key: sending the same logical command twice produces two different keys, and both handlings go through. The key must be the same on every send of the same logical command. The difference is practical: a random UUID covers a duplicate from a broker retry, but not a user's double click, which happens more often.

The condition on ReceivedStamp carries the whole sample. An asynchronous command passes through the middleware twice: on dispatch, when SendMessageMiddleware only sends it to the transport, and again in the worker, which marks the envelope with ReceivedStamp before handling. Without the condition, the key would be stored already at send time. The worker would then skip its own message as a duplicate, and the handler would never run. On a synchronous bus without a transport, no ReceivedStamp is created, so the middleware does not deduplicate there; it targets asynchronous commands.

The sender attaches the stamp from the data it has at hand:

php snippet.php
1$this->commandBus->dispatch(2    new CapturePayment($orderId),3    [IdempotencyStamp::forOperation('payment.capture', $orderId->value)],4);

B4. Message ordering – message B arrives before A

Problem: You have two workers processing the same queue in parallel. The events OrderPlaced and OrderShipped leave one after the other, but a different worker processes OrderShipped faster. The handler tries to mark the order as shipped, but the order does not exist yet (or is in the wrong state).

Solution: three approaches, depending on the context.

Approach When to use Trade-off
Optimistic retry The dependency is short-lived (ms) The handler throws RecoverableMessageHandlingException with retryDelay → Messenger postpones the message; max_retries does not apply to it
One worker per aggregate Ordering is critical Lower throughput, but guaranteed ordering for each aggregate
Inbox buffer Complex dependencies The handler stores the message in an “inbox” table and processes it only once the conditions are met

RecoverableMessageHandlingException accepts a retryDelay parameter (in milliseconds) and thereby overrides the delay from the configured strategy. For a missing dependency, it is a more precise tool than a generic exception: you wait on the order of hundreds of milliseconds, not through an exponential backoff calculated for an outage of an external service.

The exception, however, also bypasses max_retries. According to the Symfony documentation, such a message is retried indefinitely and never reaches the failed transport on its own. When the precondition never arrives (OrderPlaced ended up in the failed transport), the worker will retry OrderShipped without end. The cap is therefore enforced by the handler itself, for example by the age of the message: once it is exceeded, the handler throws an ordinary exception, to which max_retries does apply.

In the end, though, the ordering guarantee is held by the transport, not by the handler code. Only some brokers offer FIFO, and usually at the cost of throughput or a restriction to one message group. Check what your transport actually promises before you build domain logic on ordering. The healthier path is not to need ordering. A handler that tolerates messages in any sequence has nothing to break.

The delay does not stop at the worker boundary. A user who has just submitted an order and right after that sees an overview without it is reading a consequence of the same mechanism. What to do about it in the UI is covered in Eventual consistency in practice: confirming the action instead of reading from the read model, optimistic rendering, and a visible “processing” state are the three usual answers. The decision belongs in the screen design, not in the handler.

20.03 C – Modeling#

Modeling decisions seem trivial until they cause a problem in production. The four traps that come back most often follow.

C1. Where validation lives

Problem: Validation is scattered across three places: the Symfony Validator (attributes on the DTO), the Application Service (domain conditions), and the domain constructor (invariants). The result is either duplication (the same rules in two places) or holes (a rule missing in one place).

Validation type Where it belongs Example
Value format The value object constructor; the Symfony Validator repeats the check at the input for a readable message An email has a valid format, a price must not be negative
Domain invariant An aggregate method The quantity must not be zero; only an order with items can be confirmed
Domain policy The aggregate or a domain service; the application service only supplies the input data A customer must not have more than 5 open orders
Database uniqueness A database unique constraint + a check in the Application Service A customer's email is unique in the system

Main rule: Both the format and the domain invariant are always enforced in the domain; validation in a higher layer does not replace them. A domain object is created elsewhere too: in a CLI command, in a test, during an import. The Symfony Validator is the first line of defense for user input; see Where to validate: Symfony Validator vs. domain validation.

C2. A state machine without an anemic model

An order goes through the states Draft → Confirmed → Paid → Shipped → Delivered, with the option of cancellation up to a certain point. The anemic approach $order->setStatus('shipped') overwrites the value without guard conditions and without checking whether the transition is allowed. The rules that define the domain get lost along the way.

Each transition has its own method, which verifies its validity, changes the state, and records a domain event; no setter is left on the outside. A bare setter is a typical symptom of the anemic model; the general analysis is in Anti-Patterns and Common Mistakes.

php snippet.php
1// A shortened form of Order from the Aggregate Design chapter: the excerpt omits2// the place() factory, the items, and the idempotent branches.3final class Order extends AggregateRoot4{5    private OrderStatus $status = OrderStatus::Draft;6 7    private function __construct(8        public readonly OrderId $id,9        public readonly CustomerId $customerId,10    ) {11    }12 13    public function confirm(): void14    {15        if ($this->status !== OrderStatus::Draft) {16            throw InvalidOrderStateTransitionException::cannotTransition(17                $this->status->value,18                OrderStatus::Confirmed->value,19            );20        }21        $this->status = OrderStatus::Confirmed;22        $this->record(new OrderConfirmed($this->id, $this->customerId, new \DateTimeImmutable()));23    }24 25    public function ship(ShipmentId $shipmentId): void26    {27        if ($this->status !== OrderStatus::Paid) {28            throw InvalidOrderStateTransitionException::cannotTransition(29                $this->status->value,30                OrderStatus::Shipped->value,31            );32        }33        $this->status = OrderStatus::Shipped;34        $this->record(new OrderShipped($this->id, $shipmentId, new \DateTimeImmutable()));35    }36}

C3. Anti-Corruption Layer for external APIs

Problem: Stripe returns \Stripe\PaymentIntent, ARES (the Czech business register) returns JSON, Fakturoid its own DTO. When data from external systems leaks directly into domain code, every change to an external API also changes the domain model. The pattern as such, including its place on the Context Map, is covered in Anti-Corruption Layer (ACL); this section is about its form in PHP.

Solution: Ports & Adapters, that is, hexagonal architecture. The domain model defines a Port (an interface) that describes, in domain terms, what it needs from the external system. The infrastructure layer adds an Adapter for it, which translates the external API into the domain interface.

Domain code works only with the PaymentGateway interface and knows nothing about Stripe. The chapter on sagas shows a port of the same name with primitive parameters; that is a different, simplified excerpt. Switching the payment gateway (Stripe → Adyen) requires only a new Adapter. The adapter calls the Payment Intents API. Stripe does not allow the older Charges API with a source token for new integrations. The sample adapter cannot handle 3D Secure verification, which the bank may require, and declines the payment. A full integration handles it on the client via Stripe.js; for illustrating the ACL, that is not essential.

C4. Ubiquitous Language drift

Problem: After six months of development, the code speaks a different language than the domain expert. The code has Invoice, the customer says “faktura” (the Czech word for invoice), and the accounting system knows “Bill.” The Order class covers concepts that the domain splits into a “quote,” an “order,” and a “contract.” Developers stop being sure what the class models.

Cause: Ubiquitous Language evolves with the understanding of the domain; it is not an artifact written down once. Without active care, the code lags behind the current understanding.

Measures: four practices.

  1. A domain glossary in the repository (docs/glossary.md) – a living document where every term has a definition, synonyms, and a link to the class in the code. It is updated with every rename.

  2. Architecture Decision Records (ADR) – for every deliberate rename of a concept, write an ADR with the reason. A future developer will understand why Contract replaced Order.

  3. Event Storming as a regular activity – not a one-off workshop at the start of the project, but a review with domain experts every six months to a year, and more often in a fast-changing product. The cadence is discussed in the Recommended frequency section.

  4. Living documentation through tests – describing behavior in BDD-style test names (it_places_an_order_when_items_are_in_stock()) produces readable documentation of the current behavior.

20.04 D – Symfony-specific friction#

Symfony conventions aim mostly at CRUD. They collide with the domain model most visibly in three places.

D1. Symfony Form vs. Command

Problem: By default, a FormType fills an existing object through setters or public properties. An Application Command is supposed to be a readonly DTO with required constructor arguments. The claim “Symfony Form cannot handle immutable objects” is inaccurate, though: the documentation describes the empty_data option as a closure that creates the object and passes the submitted values to its constructor. So a Command can be filled directly from a form.

The remaining question is where it should come into existence. When the Command is created directly in the form, the shape of the application command starts copying the shape of the screen. As soon as a second input channel (API, CLI, import) appears, the mismatch shows.

Solution: The form fills a plain mutable DTO (a form object); the controller then builds the immutable Command from the validated data. The form does not know about the Command, and the Command does not know about the form either. The empty_data route fits where the form is the only input and the intermediate step would be a mere copy.

php snippet.php
1// 1. Form object – mutable, compatible with the framework2final class PlaceOrderFormData3{4    public string $customerId = '';5    public array  $items      = [];6}7 8// 2. The FormType works with the form object9$form = $this->createForm(PlaceOrderType::class, new PlaceOrderFormData());10$form->handleRequest($request);11 12if ($form->isSubmitted() && $form->isValid()) {13    /** @var PlaceOrderFormData $data */14    $data = $form->getData();15 16    // 3. The controller builds the Command – immutable, with domain types17    $command = new PlaceOrder(18        // The PlaceOrder variant with its own orderId, see section D2.19        // The application assigns the identity, not the database – see section A5.20        orderId: OrderId::generate(),21        customerId: CustomerId::fromString($data->customerId),22        items: array_map(23            fn(array $i) => [24                'productId'        => $i['productId'],25                'quantity'         => (int) $i['quantity'],26                'unitPriceInCents' => (int) $i['unitPriceInCents'],27            ],28            $data->items,29        ),30    );31 32    $this->commandBus->dispatch($command);33}

PlaceOrder is a readonly PHP class. The handler works with it without any dependency on the Symfony Form component.

D2. API Platform vs. domain aggregates

Problem: By default, API Platform expects direct access to Doctrine entities: it reads and writes them with its built-in providers and processors. An aggregate, however, should not be serialized directly (internal state would leak into the API), and API Platform should not modify it outside the Application Service.

Solution: Expose an API Resource DTO to API Platform (not the aggregate) and implement your own StateProvider and StateProcessor that act as adapters to the application layer.

D3. Security Voter vs. domain permissions

Problem: Access rules set by the business are part of the domain. An example: “an order can be canceled by the customer, but only within 24 hours of confirmation and only if it has not been shipped yet.” A Symfony Security Voter lives in the infrastructure layer and depends on the framework. If you write the logic directly into the Voter, testing it requires a security token and other framework objects.

Solution: The Voter acts as a thin adapter that delegates the decision to a domain method of the aggregate. The domain method does not depend on the framework and is tested without it.

Where exactly each check lives is covered in the Authorization in DDD chapter, including why the Voter alone is not enough and what belongs directly in the aggregate.

20.05 E – Organization and team#

Projects that abandon DDD rarely founder on technology. Evans sums it up in the DDD Reference without embellishment: many projects do modeling and still get little out of it in the end. The reasons that usually precede this are organizational: the team does not understand the pattern, management does not give it a mandate, the knowledge stays in the head of one senior developer. The following three sections are based on experience, not on measurement; there is no citable data on abandoning DDD.

E1. The business case for a DDD refactoring

Problem: Management sees the costs of the refactoring (time, risk) but not the benefits. “Rewriting it in DDD” sounds like technical purity without business value. Developers often cannot translate the benefits into a language the decision-makers understand.

How to argue: with metrics.

Metric How to measure Why track it
Change lead time Time from commit to deployment to production (DORA definition) Comparable across teams; management knows it
Change fail rate % of deployments that require a hotfix or a rollback Shows whether changes in the module hold
Regression rate % of tickets marked as a regression Closest to the pain of “we fix one thing and another breaks”
Onboarding time Time until a new developer makes their first commit to the module Measures how understandable the model is, not how clean

Two of these metrics (change lead time and change fail rate) come from the DORA set, which has grown from the original four metrics to five and serves as a shared vocabulary for software delivery. Measure them before and after the refactoring, but refrain from promising that they will drop because of DDD. No study has demonstrated a link between architectural style and defect rates, and the “bugs per thousand lines” metric is misleading in a refactoring in its own right: its denominator changes. The numbers therefore carry weight as a shared language with the business, not as proof.

Tactic: Do not start with the argument “our code is bad,” but with a concrete business pain. Illustrative scenario: “Adding a new payment method takes three weeks and causes a regression in the ordering module every time.” The cause and a proposed solution follow. Plug in your own numbers; a decision-maker will see through borrowed estimates.

E2. Gradual adoption – the Strangler Fig Pattern

Problem: Rewriting the whole application in DDD at once usually fails: it takes longer than estimated, the team loses motivation, and the business waits in vain for new features. Meanwhile, the original application must keep running. Why a big-bang rewrite ends badly is covered in the warning in the Migrating from CRUD to DDD chapter.

Solution: the Strangler Fig Pattern. Pick one module that changes most often (highest churn), has the most bugs, or has the greatest business value, and implement exactly that one in DDD. The rest of the application stays unchanged. It communicates with the new code through a facade (the ACL pattern), and a feature flag allows an immediate rollback to the legacy code. Once it stabilizes, the procedure repeats with the next module, until the legacy dries up.

The complete procedure is described in the Migrating from CRUD to DDD chapter: domain analysis, extracting the domain layer, characterization tests, and effort estimates.

E3. Knowledge silos and the bus factor

Problem: The domain model is complex, and after a year of development only one person understands it well. When that person gets sick, leaves, or becomes overloaded, the team stalls. Onboarding a new developer takes months. A bus factor of 1 is a critical risk for the project.

Measures: Two practices aimed directly at sharing ownership help against a low bus factor:

  1. Pair programming on the domain model: Changes to aggregates and domain rules are made in pairs. Knowledge transfers continuously, not only when the author leaves.

  2. Rotating module ownership: No Bounded Context permanently has only one maintainer. Periodic rotation forces the team to understand more parts of the system.

The other tools are the same as against Ubiquitous Language drift: a domain glossary in the repository, ADRs for non-trivial decisions, regular Event Storming, and living documentation through tests (see Ubiquitous Language drift).

Frequently asked questions

Why does traditional Doctrine mapping complicate a clean domain model?

Doctrine hydrates objects via reflection and tracks changes through the Unit of Work, while a DDD aggregate protects invariants in its constructor and domain methods, and value objects are immutable. The conflict includes identification via a generated ID (Doctrine) versus identity in the domain (DDD), the problem of a “dirty” EntityManager during a request, and type limitations for value objects. The pragmatic default is to keep the attributes directly on the aggregate (they are metadata, not behavior) and to use Doctrine custom types for value objects. A strictly separated domain is offered by the Persisted Object Pattern: a separate persistence model and a mapper. Details in the Doctrine vs. the domain model section.

How do you handle the Outbox Pattern for reliable delivery of integration events?

The outbox stores integration events in a local table in the same transaction as the aggregate change. The event is thus not lost in a crash between the commit and publishing, and it does not go out before the transaction has actually gone through. A separate process (the relay) then reads the outbox table and publishes the events to the message bus or an external system. The outbox itself guarantees at-least-once delivery; idempotent consumers make sure that a repeated delivery does not cause duplicate processing. A summary is in the Outbox Pattern – guaranteed delivery of integration events section, the full explanation in the Outbox Pattern chapter.

How do you explain the benefit of DDD to management when the first iteration slows things down?

The recommended approach is to admit the short-term cost and to base the benefit on a concrete business pain, such as how many weeks it takes to add a new payment method. The metrics (change lead time, change fail rate, regression rate, onboarding time) are measured before and after the refactoring as a shared language with the business, not as a promise that DDD will improve them. Starting with a pilot Bounded Context works well. When the first results arrive depends on the size of the context and the experience of the team; it is a matter of months rather than weeks, and promising a specific number in advance does not pay off. Without sponsorship at the management level, an investment in DDD usually does not get approved. The communication strategy is analyzed in the section The business case for a DDD refactoring.

How do you keep Ubiquitous Language from drifting over time?

Ubiquitous Language erodes when the code and the speech of domain experts start to diverge: the code has “Invoice” while the customer says “faktura,” the Czech word for invoice. Prevention requires regular reviews of the code against the vocabulary, an ADR whenever it changes, and a glossary in the repository as a living document. Drift shows as soon as a new feature introduces a term the domain expert does not know. At that point, either the code backs off or the language is adjusted together. A detailed analysis is in the Ubiquitous Language drift section.

How do you survive the parallel existence of the old CRUD part and the new DDD layer?

The Strangler Fig Pattern lets you keep both states in one application: the old CRUD modules stay in operation, new features are built in the DDD style, and the Anti-Corruption Layer handles the connection. The challenges are the shared database, authentication, and user state. The pragmatic solution: migrate gradually, one Bounded Context at a time, and explicitly accept that the mixed state will last a long time. For a non-trivial system it is a matter of years, not of one quarterly planning cycle. See the Gradual adoption – the Strangler Fig Pattern section.