Skip to content
System Design

Domain Driven Design interview questions and answers

40 questions, 38 with code. About 3 h 5 min to read them all.

By TestLab · Updated

Plan for an interview
40 questions

Track what you know and what to revise.

Sign in to track progress

You can open a few full answers without signing in. Sign in to read all

1

What is domain-driven design, and what are its core principles?

Domain-Driven Design (DDD), introduced by Eric Evans in his 2003 book, is an approach to building software for complex business domains by putting a rich model of the business at the centre of the code and developing it together with domain experts. Its core principles are: focus on the core domain (where the business competes), a ubiquitous language shared by experts and developers and used in the code, bounded contexts that give each model a clear boundary, and tactical building blocks (entities, value objects, aggregates, domain events, repositories, domain services) that keep business rules explicit and protected. DDD pays off when business logic is complex; for simple CRUD applications it is usually overkill.

Read full answer

Applies toenterprise systems with complex rules (ordering, banking, insurance, logistics, healthcare), modular monoliths and microservice architectures

Strategic Design (the Big Picture)

Principle Meaning
Core, supporting and generic subdomains Invest the most modelling effort in the core domain; buy or simplify generic ones (email, auth)
Ubiquitous language One precise vocabulary per context, used in conversations, documentation and code
Bounded contexts Each model applies within an explicit boundary; “Order” in Sales may differ from “Order” in Shipping
Context maps Describe how contexts relate (customer-supplier, shared kernel, anti-corruption layer)

Tactical Design (Inside a Context)

Building block Role Order example
Entity Identity that persists over time Order with order_id
Value object Defined by its values; immutable Money(amount, currency), Address
Aggregate Consistency boundary with one root Order (root) containing OrderLines
Domain event Something important that happened OrderPlaced
Repository Loads and saves whole aggregates OrderRepository
Domain service Domain logic that does not belong to one entity PricingService
Factory Creates complex aggregates in a valid state Order.create(...)

Small Example

from dataclasses import dataclass, field
from decimal import Decimal

@dataclass(frozen=True)
class Money:                                     # value object
    amount: Decimal
    currency: str
    def __add__(self, other):
        assert self.currency == other.currency
        return Money(self.amount + other.amount, self.currency)

@dataclass
class OrderLine:
    product_id: str
    quantity: int
    unit_price: Money

@dataclass
class Order:                                     # aggregate root (entity)
    order_id: str
    customer_id: str                             # other aggregate referenced by ID
    lines: list = field(default_factory=list)
    status: str = "draft"
    events: list = field(default_factory=list)

    def add_line(self, product_id, quantity, unit_price):
        if self.status != "draft":
            raise ValueError("cannot change a placed order")
        if quantity <= 0:
            raise ValueError("quantity must be positive")
        self.lines.append(OrderLine(product_id, quantity, unit_price))

    def total(self):
        total = Money(Decimal("0"), "INR")
        for line in self.lines:
            total = total + Money(line.unit_price.amount * line.quantity, line.unit_price.currency)
        return total

    def place(self):
        if not self.lines:
            raise ValueError("an order needs at least one line")
        self.status = "placed"
        self.events.append(("OrderPlaced", self.order_id, self.total().amount))

order = Order("o-1", "c-42")
order.add_line("p-1", 2, Money(Decimal("499"), "INR"))
order.place()
print(order.status, order.total().amount, order.events[0][0])   # placed 998 OrderPlaced

The rules (“cannot change a placed order”, “needs at least one line”) live in the model, named in the business’s own terms, not scattered across controllers and SQL.

Rules of Thumb

  • Change one aggregate per transaction, and reference other aggregates by ID (the order holds customer_id, not a Customer object).

  • Keep aggregates small; use domain events for consistency across aggregates.

  • Let business language drive names: place(), not set_status(2).

When DDD Fits and When It Does Not

Fits Overkill
Complex, changing business rules Simple CRUD admin screens
Access to domain experts Data pipelines with little logic
Long-lived core systems Short-lived prototypes
Several teams and models Small apps with one obvious model

Interview Tip

Define DDD as modelling a complex domain with experts, then cover strategic design (subdomains, ubiquitous language, bounded contexts, context maps) and tactical design (entities, value objects, aggregates, events, repositories). Stating the one-aggregate-per-transaction rule and when DDD is overkill shows balanced judgement.

2

How does DDD differ from data-driven or service-driven design approaches?

Data-driven design starts from the database schema: tables come first, and code is mostly CRUD around them, with business rules scattered across services, stored procedures and UI code. Service-driven (transaction script) design organises code as procedures per use case (“PlaceOrderService”) that read and write data structures directly. DDD starts from the business domain and its language: it models behaviour and rules inside domain objects (aggregates, entities, value objects), draws bounded contexts around consistent models, and treats the database as a persistence detail. The result is code that mirrors how the business thinks, which pays off when rules are complex and change often.

Read full answer

Applies tochoosing an architecture style for business applications, from CRUD tools to complex ordering, banking or insurance systems

Comparison

Aspect Data-driven Service-driven (transaction script) Domain-driven
Starting point Tables and columns Use cases as procedures Business concepts, language and rules
Where rules live Spread across SQL, services, UI Inside service methods Inside aggregates, value objects and domain services
Objects Anaemic data holders Data structures passed to procedures Rich objects with behaviour
Vocabulary Technical (status = 2) Mixed Ubiquitous language (order.place())
Model boundaries One shared schema for everything Often one shared model Bounded contexts with separate models
Change impact Schema changes ripple everywhere Duplicate logic in several services Changes localised to the model and context
Best for Reporting, simple CRUD Simple workflows Complex, evolving business logic

Same Rule, Three Styles

Rule: “A placed order cannot be modified, and quantities must be positive.”

Data-driven: a database check constraint on quantity, plus each screen remembering to check status:

ALTER TABLE order_lines ADD CONSTRAINT qty_positive CHECK (quantity > 0);
-- "placed orders cannot change" is enforced (or forgotten) in each code path

Service-driven:

def add_line_service(order_row, product_id, qty, price):
    if order_row["status"] != "draft":
        raise ValueError("cannot change a placed order")
    if qty <= 0:
        raise ValueError("quantity must be positive")
    order_row["lines"].append({"product_id": product_id, "qty": qty, "price": price})

row = {"status": "draft", "lines": []}
add_line_service(row, "p-1", 2, 499)
print(len(row["lines"]))   # 1

Another service (say, a bulk import) may forget the check.

Domain-driven:

class Order:
    def __init__(self, order_id):
        self.order_id, self.status, self._lines = order_id, "draft", []

    def add_line(self, product_id, qty, price):
        if self.status != "draft":
            raise ValueError("cannot change a placed order")
        if qty <= 0:
            raise ValueError("quantity must be positive")
        self._lines.append((product_id, qty, price))

    def place(self):
        if not self._lines:
            raise ValueError("an order needs at least one line")
        self.status = "placed"

o = Order("o-1")
o.add_line("p-1", 2, 499)
o.place()
try:
    o.add_line("p-2", 1, 99)
except ValueError as e:
    print(e)               # cannot change a placed order

Every caller must go through add_line, so the rule cannot be bypassed.

Strengths and Weaknesses

Approach Strengths Weaknesses
Data-driven Fast for CRUD; easy reporting; tools generate a lot Logic sprawl; tight coupling to schema
Service-driven Simple, direct; good for straightforward workflows Duplication as rules grow; anaemic model
Domain-driven Rules explicit and protected; aligns with business; scales with complexity Learning curve; more upfront modelling; overkill for simple apps

Mixing Approaches

Real systems combine them: use DDD for the core domain (pricing, ordering), plain CRUD for supporting screens, and data-driven read models (reports, CQRS projections) where queries dominate.

Interview Tip

Contrast where each approach starts (schema, procedures, domain) and where the rules live, then show one rule implemented each way. Saying that DDD is worth it for the core domain while CRUD remains fine elsewhere shows pragmatic judgement.

3

What is the difference between the domain model and the data model in DDD?

The domain model expresses the business concepts, rules and behaviour in code: aggregates, entities, value objects, domain events and the operations on them, named in the ubiquitous language. The data model describes how that state is stored: tables, columns, keys and indexes, or documents and events. In DDD the domain model is primary and persistence-ignorant; the data model is an implementation detail chosen for storage and query needs. A repository and mapping layer translates between them, so a value object like Money may be two columns, and one aggregate may span several tables.

Read full answer

Applies tolayered and hexagonal architectures with ORMs (Hibernate/JPA, Entity Framework, SQLAlchemy, Django ORM), document stores and event-sourced systems

Key Differences

Aspect Domain model Data model
Purpose Express business behaviour and invariants Store and retrieve data efficiently
Contents Classes with methods: Order.place(), Money.add() Tables, columns, keys, indexes
Language Ubiquitous language Storage terms (foreign keys, joins)
Structure Aggregates and object graphs Normalised tables, or denormalised for queries
Driven by Business rules Performance, integrity, storage technology
Changes when The business changes Storage or query needs change

Order Example

Domain model

from dataclasses import dataclass, field
from decimal import Decimal

@dataclass(frozen=True)
class Money:
    amount: Decimal
    currency: str

@dataclass
class OrderLine:
    product_id: str
    quantity: int
    unit_price: Money

@dataclass
class Order:
    order_id: str
    customer_id: str
    lines: list = field(default_factory=list)
    status: str = "draft"

    def place(self):
        if not self.lines:
            raise ValueError("an order needs at least one line")
        self.status = "placed"

# Mapping (normally in the repository or ORM configuration)
def to_rows(order):
    order_row = {"id": order.order_id, "customer_id": order.customer_id, "status": order.status}
    line_rows = [{"order_id": order.order_id, "line_no": i, "product_id": l.product_id,
                  "quantity": l.quantity,
                  "unit_price_cents": int(l.unit_price.amount * 100),
                  "currency": l.unit_price.currency}
                 for i, l in enumerate(order.lines, start=1)]
    return order_row, line_rows

o = Order("o-1", "c-42", [OrderLine("p-1", 2, Money(Decimal("4.99"), "USD"))])
order_row, line_rows = to_rows(o)
print(order_row["status"], line_rows[0]["unit_price_cents"])   # draft 499

Data model

CREATE TABLE orders (
    id           VARCHAR(12) PRIMARY KEY,
    customer_id  VARCHAR(12) NOT NULL,
    status       VARCHAR(20) NOT NULL
);

CREATE TABLE order_lines (
    order_id         VARCHAR(12) REFERENCES orders(id),
    line_no          INT,
    product_id       VARCHAR(12) NOT NULL,
    quantity         INT NOT NULL CHECK (quantity > 0),
    unit_price_cents BIGINT NOT NULL,          -- Money split into two columns
    currency         CHAR(3) NOT NULL,
    PRIMARY KEY (order_id, line_no)
);

Mapping Between Them

The to_rows function above turns one Order aggregate into an orders row and several order_lines rows, splitting Money into cents and currency. In practice an ORM mapping or the repository does this. The domain class has no SQL, and the tables have no business methods.

Why Keep Them Separate

  • Freedom to model behaviour: value objects and invariants do not have to mirror tables.

  • Freedom to optimise storage: denormalise, add indexes, change databases, or use event sourcing without rewriting business rules.

  • Testability: domain logic is tested with plain objects, no database needed.

  • Clarity: business rules are not hidden in triggers or stored procedures.

Practical Compromises

  • ORMs often push the two models together (annotations on domain classes). This is acceptable if the domain stays expressive and the ORM’s constraints do not distort it (for example forcing public setters or no-argument constructors).

  • Read models for queries and reports (CQRS) can use a third, denormalised data model optimised for reading.

  • For simple CRUD, a single model is fine; separation pays off as rules grow.

Interview Tip

Explain that the domain model captures behaviour and rules in business language, while the data model captures storage, and show one aggregate mapped to two tables. Mentioning persistence ignorance, repositories as the translation layer, and pragmatic ORM compromises shows practical experience.

4

What are bounded contexts in DDD, and why are they important?

A bounded context is an explicit boundary within which a particular domain model and its language are consistent. Inside it, every term has one precise meaning; outside, the same word may mean something else. For example, “Order” in Sales is a set of priced lines a customer agrees to, while in Shipping it is a set of parcels with addresses and delivery slots. Bounded contexts matter because a single model for the whole enterprise becomes contradictory and bloated. Splitting the domain lets each team model its part precisely, change it independently, and integrate deliberately through defined contracts. They are the main tool of strategic DDD, and often guide team and service boundaries.

Read full answer

Applies tolarge systems with several business areas (sales, billing, shipping, inventory), modular monoliths and microservice boundaries

Same Word, Different Models

Context “Order” means Key attributes and rules
Sales A customer’s purchase commitment Lines, prices, discounts, “cannot change after placement”
Billing Something to invoice and collect payment for Invoice number, tax, payment status, due date
Shipping Goods to pick, pack and deliver Parcels, weights, address, carrier, delivery slot
Inventory A demand on stock Product reservations, warehouse locations

Trying to put all of this into one Order class creates a large object full of optional fields and rules that conflict.

What a Bounded Context Contains

  • Its own ubiquitous language (glossary).

  • Its own domain model (aggregates, entities, value objects).

  • Its own code module and, often, data store.

  • Clear interfaces to other contexts: APIs, events, translation layers.

  • Usually one owning team.

Example: Separate Models Linked by ID

from dataclasses import dataclass

# Sales context
@dataclass
class SalesOrder:
    order_id: str
    customer_id: str
    total_cents: int
    status: str = "placed"

# Shipping context: its own model, built from a Sales event
@dataclass
class Shipment:
    shipment_id: str
    order_id: str                 # reference across contexts by ID only
    address: str
    parcels: int = 1
    status: str = "awaiting_pick"

def on_order_placed(event):
    """Shipping translates the Sales event into its own language."""
    return Shipment(f"s-{event['order_id']}", event["order_id"], event["shipping_address"])

placed = {"type": "OrderPlaced", "order_id": "o-1", "shipping_address": "12 MG Road, Pune"}
print(on_order_placed(placed))
# Shipment(shipment_id='s-o-1', order_id='o-1', address='12 MG Road, Pune', parcels=1, status='awaiting_pick')

Why They Matter

Benefit Explanation
Model clarity Each model stays small, precise and consistent
Language precision No more arguments about what “customer” or “order” means
Team autonomy Teams evolve their models without coordinating every change
Reduced coupling Integration happens through explicit contracts
Natural modularity Good candidates for modules or services
Legacy protection Anti-corruption layers keep legacy models from leaking in

Bounded Context vs Subdomain

  • A subdomain is part of the problem space (the business area, for example “shipping”).

  • A bounded context is part of the solution space (the boundary of a model in software).

  • Ideally they align one to one, but legacy systems often have one context spanning several subdomains, or the reverse.

Common Mistakes

  • One canonical enterprise model shared by everyone.

  • Contexts defined by technical layers (a “database context”) instead of business capabilities.

  • Shared database tables across contexts, which couple them silently.

  • Too many tiny contexts, which create integration overhead.

Interview Tip

Define a bounded context as the boundary where a model and its language are consistent, illustrate with “Order” meaning different things in Sales and Shipping, and explain benefits: precise models, team autonomy and explicit integration. Distinguishing subdomains (problem) from bounded contexts (solution) shows depth.

5

Which strategies help define bounded contexts in a large system?

Bounded contexts are found by looking for where the language and the rules change. Useful strategies: map the business into subdomains (core, supporting, generic); run collaborative workshops such as Event Storming to discover events, commands and natural groupings; watch for terms that mean different things to different groups; group by business capability and who owns the decisions; follow consistency and transaction needs; consider team structure (Conway’s law); and respect existing systems and constraints. Start with fewer, larger contexts and split when the model shows clear seams, then document the result in a context map.

Read full answer

Applies togreenfield design, splitting a monolith, planning microservices and aligning teams

Strategies

Strategy What to look for
Subdomain analysis Core (competitive advantage), supporting (needed, specific), generic (commodity: email, payments gateway)
Linguistic boundaries The same word with different meanings (“account” in Banking vs Identity), or different words for the same thing
Event Storming Clusters of domain events and commands with their own actors and policies; “pivotal events” (OrderPlaced, PaymentReceived) often mark boundaries
Business capabilities What the business does: pricing, ordering, fulfilment, billing, customer support
Ownership and decision rights Which department or role owns the rules and data
Consistency requirements Data that must change together belongs together; data that tolerates eventual consistency can be split
Rate of change Areas that change together, at the same pace, often belong together
Team topology One team per context avoids constant cross-team coordination
Existing systems Legacy systems or third-party products often form their own contexts, protected by anti-corruption layers

Example: Online Store

After an Event Storming session, events cluster like this:

Catalogue:    ProductAdded, PriceChanged
Ordering:     CartCheckedOut, OrderPlaced, OrderCancelled
Payments:     PaymentAuthorised, PaymentCaptured, RefundIssued
Fulfilment:   OrderPicked, ParcelShipped, DeliveryConfirmed
Customer:     CustomerRegistered, AddressChanged

Language checks confirm the split: “price” in Catalogue is a list price; in Ordering it is the price agreed at checkout (copied, not shared); in Payments it is an amount to capture.

Context Type Notes
Ordering Core Rich model; heavy investment
Pricing and promotions Core Often its own context as rules grow
Catalogue Supporting Content-heavy, simpler rules
Fulfilment Supporting May integrate a warehouse system via an anti-corruption layer
Payments Generic Wrap a payment provider
Identity Generic Use an identity platform

Heuristics for Good Boundaries

  • High cohesion inside, low coupling outside: most changes should touch one context.

  • Few synchronous dependencies: if two contexts must call each other for every operation, the boundary may be wrong.

  • Aggregates do not span contexts.

  • A context can be explained in its own language without constant references to another.

  • One owner who can make modelling decisions.

Warning Signs of Wrong Boundaries

Symptom Likely problem
Every feature changes several contexts Boundaries cut across a capability
Distributed transactions between contexts Data that must be consistent was split
Huge shared “common” model No real boundaries
Contexts named after technology (“database service”) Technical, not business, boundaries

Evolving Boundaries

Boundaries are hypotheses. Start with a modular monolith where contexts are modules with clear interfaces; moving a boundary there is cheap. Extract services only when a context is stable and has a reason to be deployed or scaled separately.

Interview Tip

List practical strategies (subdomains, language shifts, Event Storming, capabilities, ownership, consistency needs and team structure) and illustrate with an e-commerce split. Recommending starting coarse in a modular monolith and refining over time shows experience.

6

How do you integrate multiple bounded contexts within one system?

Bounded contexts integrate through explicit contracts, never by sharing internal models or database tables. The main mechanisms are domain events published by one context and consumed by others (loose coupling, eventual consistency), APIs (synchronous request-response, for example REST or gRPC, or in-process interfaces in a modular monolith), and translation layers (anti-corruption layers, published languages) that convert one model into another. Each relationship is described by a context-map pattern such as customer-supplier, conformist, shared kernel, open host service or anti-corruption layer, which makes clear who adapts to whom.

Read full answer

Applies tomodular monoliths, microservices, and systems integrating legacy or third-party software

Integration Mechanisms

Mechanism How it works Coupling Consistency
Domain or integration events Publisher emits OrderPlaced; subscribers react Low (publisher does not know consumers) Eventual
Synchronous API Caller requests data or an action Higher (runtime dependency) Immediate for the call
Anti-corruption layer (ACL) Translates another context’s model into yours Protects your model Either
Published language Shared, versioned schema for exchanged messages (JSON Schema, Protobuf, Avro) Contract-level only Either
Shared kernel Small shared model jointly owned by two teams High; use sparingly Immediate
Batch or file exchange Periodic export and import Low Delayed

Example: Ordering, Payments and Shipping

Ordering --OrderPlaced--> Payments (authorise payment)
Payments --PaymentCaptured--> Ordering (mark paid), Shipping (create shipment)
Shipping --ParcelShipped--> Ordering (update status), Notifications (email customer)
from collections import defaultdict

class EventBus:                       # in-process for a modular monolith; a broker in production
    def __init__(self):
        self.handlers = defaultdict(list)
    def subscribe(self, event_type, handler):
        self.handlers[event_type].append(handler)
    def publish(self, event):
        for h in self.handlers[event["type"]]:
            h(event)

bus, log = EventBus(), []

# Payments context: translates Ordering's event into its own command
def payments_on_order_placed(e):
    log.append(f"payments: authorise {e['amount_cents']} for {e['order_id']}")
    bus.publish({"type": "PaymentCaptured", "order_id": e["order_id"]})

# Shipping context
def shipping_on_payment_captured(e):
    log.append(f"shipping: create shipment for {e['order_id']}")

bus.subscribe("OrderPlaced", payments_on_order_placed)
bus.subscribe("PaymentCaptured", shipping_on_payment_captured)
bus.publish({"type": "OrderPlaced", "order_id": "o-1", "amount_cents": 99800})
print("\n".join(log))
# payments: authorise 99800 for o-1
# shipping: create shipment for o-1

Each context keeps its own model; events carry only the data others need, in a published, versioned format.

Context-Map Relationship Patterns

Pattern Meaning
Partnership Two teams succeed or fail together and coordinate closely
Customer-supplier Downstream needs influence the upstream’s priorities
Conformist Downstream simply adopts the upstream model (common with big vendors)
Anti-corruption layer Downstream translates to protect its model
Open host service Upstream offers a well-defined API or protocol for many consumers
Published language Shared documented exchange format
Shared kernel Small jointly owned shared model
Separate ways No integration; duplicate if cheaper

Integration Rules

  • Never share database tables across contexts.

  • Reference by ID; copy the data you need (for example the agreed price) instead of reaching into another context at runtime.

  • Version contracts and evolve them backward-compatibly.

  • Publish events reliably with the transactional outbox, so a state change and its event are not lost separately.

  • Make consumers idempotent, since events can be delivered more than once.

  • Prefer events for propagation and APIs for queries or commands that need an immediate answer.

Interview Tip

Explain events, APIs and translation layers, illustrate with an Ordering to Payments to Shipping flow, and name the context-map patterns that describe each relationship. Stressing “no shared tables, reference by ID, outbox and idempotent consumers” shows practical integration experience.

7

Why is ubiquitous language important in DDD, and how do you establish it?

A ubiquitous language is a shared, precise vocabulary that domain experts and developers use in conversations, documents, tests and code within one bounded context. It matters because translation between business talk and technical talk loses meaning: when experts say “place an order” and code says updateStatus(2), misunderstandings and bugs follow. With a ubiquitous language, the model is the language: class and method names (Order.place(), Refund.issue()) match what the business says, so the code can be reviewed with experts, and changes in understanding show up directly as changes in the model. You establish it through collaborative modelling with domain experts, a living glossary, naming the code after the language, and refining it continuously.

Read full answer

Applies toevery DDD project, especially complex domains like ordering, finance, insurance, logistics and healthcare

Why It Is Important

Benefit Explanation
Fewer misunderstandings One meaning per term within a context
Code that experts can read Method and class names reflect business concepts
Faster discovery Ambiguous or missing words reveal gaps in the model
Better tests Scenarios written in business terms (Given an order with no lines, When it is placed, Then it is rejected)
Clear boundaries When a word’s meaning changes, you have found a bounded-context edge

Example: Before and After

# Before: technical language
def update(o, s):
    if s == 2 and len(o["items"]) == 0:
        raise Exception("bad")
    o["s"] = s
# After: ubiquitous language
class EmptyOrderCannotBePlaced(Exception):
    pass

class Order:
    def __init__(self, order_id):
        self.order_id, self.lines, self.status = order_id, [], "draft"

    def place(self):
        if not self.lines:
            raise EmptyOrderCannotBePlaced(self.order_id)
        self.status = "placed"

try:
    Order("o-1").place()
except EmptyOrderCannotBePlaced as e:
    print("rejected:", e)        # rejected: o-1

A domain expert can read place() and EmptyOrderCannotBePlaced and confirm the rule.

How to Establish It

  1. Work directly with domain experts: interviews, shadowing, and modelling sessions instead of second-hand requirements.

  2. Event Storming or Domain Storytelling: map events, commands and actors on a wall using the experts’ words.

  3. Challenge vague terms: ask “what exactly is a ‘customer’ here, a payer, a user or a company?” and split terms when meanings differ.

  4. Maintain a glossary per bounded context: term, definition, examples, and what it is not.

  5. Use the language in code: class names, methods, events (OrderPlaced), exceptions and test names.

  6. Write examples and acceptance tests in the language (Given/When/Then scenarios).

  7. Refactor when the language changes: renaming a class is cheap compared with keeping an outdated concept.

  8. Keep it per context: “Order” in Sales and “Order” in Shipping can mean different things, and that is fine.

Glossary Example (Ordering Context)

Term Definition
Order A customer’s commitment to buy one or more products at agreed prices
Order line One product, quantity and agreed unit price within an order
Place (an order) Confirm a draft order; after this, lines cannot change
Cancel Withdraw a placed order before it is shipped
Agreed price The price at checkout, independent of later catalogue changes

Pitfalls

  • A glossary nobody uses: the language must appear in code and conversations.

  • Developers inventing names (“Manager”, “Processor”, “Data”) instead of business terms.

  • Forcing one language across the whole company: languages are per bounded context.

  • Ignoring disagreement: when experts disagree about a term, it often reveals two concepts or two contexts.

Interview Tip

Explain that a ubiquitous language removes translation between business and code, show a before and after naming example, and describe how to build it: expert collaboration, Event Storming, a per-context glossary, and using the terms in code and tests. Noting that changing meaning signals a context boundary shows strategic understanding.

8

How do entities and value objects differ in DDD?

An entity is a domain object defined by its identity and continuity over time: an Order with ID o-1 remains the same order even as its lines and status change. A value object is defined entirely by its attributes and has no identity: Money(499, "INR") equals any other Money(499, "INR"). Value objects are usually immutable (to change one you replace it) and are ideal for concepts like amounts, addresses, date ranges and quantities, which they validate and give behaviour to. Good models use value objects wherever identity is not needed, keeping entities few and focused on lifecycle and state changes.

Read full answer

Applies totactical DDD modelling in any object-oriented or functional language (Java, C#, Python, Kotlin, TypeScript)

Comparison

Aspect Entity Value object
Defined by Identity (ID) Attribute values
Equality Same ID means same entity All attributes equal means equal
Mutability Mutable state over its lifecycle Immutable; replaced rather than changed
Lifecycle Created, changed, possibly archived No lifecycle of its own
Examples Order, Customer, BankAccount, Shipment Money, Address, EmailAddress, DateRange, Quantity
Persistence Own row or document with an ID Embedded columns or serialised within the entity

Example: Order (Entity) With Money and Address (Value Objects)

from dataclasses import dataclass, field
from decimal import Decimal

@dataclass(frozen=True)
class Money:
    amount: Decimal
    currency: str

    def __post_init__(self):
        if self.amount < 0:
            raise ValueError("money cannot be negative")

    def add(self, other):
        if other.currency != self.currency:
            raise ValueError("currency mismatch")
        return Money(self.amount + other.amount, self.currency)

@dataclass(frozen=True)
class Address:
    line1: str
    city: str
    postcode: str

class Order:                                    # entity
    def __init__(self, order_id, shipping_address):
        self.order_id = order_id
        self.shipping_address = shipping_address
        self.total = Money(Decimal("0"), "INR")

    def __eq__(self, other):
        return isinstance(other, Order) and other.order_id == self.order_id
    def __hash__(self):
        return hash(self.order_id)

    def add_amount(self, money):
        self.total = self.total.add(money)      # replace the value, do not mutate it

    def change_address(self, new_address):
        self.shipping_address = new_address     # swap the whole value object

a1 = Address("12 MG Road", "Pune", "411001")
a2 = Address("12 MG Road", "Pune", "411001")
print(a1 == a2)                                      # True: same values, equal

o1 = Order("o-1", a1)
o2 = Order("o-1", Address("5 Park St", "Kolkata", "700016"))
print(o1 == o2)                                      # True: same identity

o1.add_amount(Money(Decimal("499"), "INR"))
print(o1.total)                                      # Money(amount=Decimal('499'), currency='INR')

frozen=True makes value objects immutable, and their constructors validate, so an invalid Money can never exist.

Why Prefer Value Objects

  • Fewer bugs: immutable values can be shared safely; there is no accidental aliasing.

  • Self-validation: an EmailAddress object is always a valid email.

  • Rich behaviour: Money.add handles currency rules; DateRange.overlaps handles date logic.

  • Clearer code: Money instead of a bare Decimal, avoiding “primitive obsession”.

  • Easy testing: no identity or lifecycle to set up.

Same Concept, Different Choice by Context

Whether something is an entity depends on the domain:

  • An address is usually a value object in an order, but an entity in a postal service that tracks delivery points over time.

  • A seat at a concert is an entity if specific seats are booked; a value object if tickets are general admission counts.

Entities in Aggregates

  • The aggregate root is an entity with a global ID (Order).

  • Internal entities (OrderLine) may have IDs that are unique only within the aggregate.

  • Other aggregates refer to the root by ID only.

Interview Tip

Define entities by identity and value objects by attributes, compare equality and mutability, and show both in an order example. Recommending value objects by default and noting that the choice depends on the domain (address example) shows mature modelling skills.

9

How do you identify aggregates, and what boundary rules apply to them?

An aggregate is a cluster of entities and value objects that must stay consistent together, treated as one unit for changes, with a single aggregate root as its entry point. You identify aggregates by asking which business invariants must be true immediately after every change: the objects needed to check one invariant belong in one aggregate, and everything else stays outside. The boundary rules are: only the root is referenced from outside, all changes go through the root, one aggregate is changed per transaction, other aggregates are referenced by ID, and consistency across aggregates is eventual (via domain events). Keep aggregates as small as the invariants allow.

Read full answer

Applies totactical DDD modelling for ordering, banking, booking, inventory and similar transactional domains

How to Identify Aggregates

  1. List the invariants in business language: “an order’s total must not exceed the customer’s credit limit”, “a placed order cannot change”, “an order must have at least one line”.

  2. Find the objects each invariant needs: lines, status and total for the order rules.

  3. Group those objects under one root: Order with its OrderLines.

  4. Leave out objects that can be updated independently: Customer, Product, Inventory have their own rules and lifecycles.

  5. Check concurrency and size: if many users would update the same aggregate at once, or it grows without bound, it is probably too large.

  6. Accept eventual consistency for rules that span aggregates, or rephrase them (“reserve stock after the order is placed”).

Boundary Rules

Rule Reason
External objects hold references only to the root Internal objects cannot be changed behind the root’s back
All changes go through root methods The root enforces every invariant
One aggregate per transaction Short transactions, fewer conflicts, easier scaling
Reference other aggregates by ID No large object graphs; clear boundaries
Delete the whole aggregate together Internal parts have no meaning on their own
Eventual consistency between aggregates Domain events update others after commit

Example: Order Aggregate

from dataclasses import dataclass

@dataclass(frozen=True)
class OrderLine:
    product_id: str            # reference to the Product aggregate by ID
    quantity: int
    unit_price_cents: int

class Order:
    MAX_LINES = 50

    def __init__(self, order_id, customer_id):
        self.order_id = order_id
        self.customer_id = customer_id        # Customer aggregate referenced by ID
        self._lines = []
        self.status = "draft"
        self.version = 0                      # for optimistic concurrency

    @property
    def lines(self):
        return tuple(self._lines)              # read-only view; no outside mutation

    def add_line(self, product_id, quantity, unit_price_cents):
        if self.status != "draft":
            raise ValueError("placed orders cannot change")
        if quantity <= 0:
            raise ValueError("quantity must be positive")
        if len(self._lines) >= self.MAX_LINES:
            raise ValueError("too many lines")
        self._lines.append(OrderLine(product_id, quantity, unit_price_cents))

    def total_cents(self):
        return sum(l.quantity * l.unit_price_cents for l in self._lines)

    def place(self):
        if not self._lines:
            raise ValueError("an order needs at least one line")
        self.status = "placed"
        return {"type": "OrderPlaced", "order_id": self.order_id, "total_cents": self.total_cents()}

order = Order("o-1", "c-42")
order.add_line("p-1", 2, 49900)
event = order.place()
print(event)   # {'type': 'OrderPlaced', 'order_id': 'o-1', 'total_cents': 99800}

Stock reservation happens in the Inventory aggregate, triggered by OrderPlaced, not inside the order’s transaction.

Common Mistakes

Mistake Problem Better
Customer aggregate containing all orders Huge object, constant contention Separate Order aggregate holding customer_id
Object references across aggregates Accidental cross-aggregate changes and lazy-loading problems Store IDs; load via repositories
Updating several aggregates in one transaction Lock contention and coupling Domain events plus eventual consistency, or a saga
Aggregates designed around screens Boundaries follow UI, not invariants Design around invariants

When a Cross-Aggregate Rule Must Be Strict

Ask the business how quickly it must hold. “Never oversell stock” might be handled by an Inventory aggregate that reserves stock atomically per product, with the order waiting for confirmation, rather than by one giant transaction across orders and stock.

Interview Tip

Explain that aggregates are defined by invariants, walk through finding them, and state the boundary rules: root-only access, one aggregate per transaction, references by ID, and eventual consistency between aggregates. Showing why Customer should not contain Orders demonstrates practical judgement.

10

What is a domain event, and when would you use one?

A domain event records something meaningful that happened in the domain, named in the past tense in the ubiquitous language: OrderPlaced, PaymentReceived, ShipmentDispatched. It is immutable, carries the facts needed by interested parties (IDs, amounts, timestamps), and is raised by an aggregate when its state changes. Use domain events to trigger follow-up work without coupling the aggregate to whoever reacts, to keep other aggregates or bounded contexts eventually consistent, to record history for auditing or event sourcing, and to make important business moments explicit in the model.

Read full answer

Applies toDDD aggregates, event-driven architectures, CQRS read models, integration between bounded contexts and event sourcing

Typical Uses

Use Example
Side effects within the same context OrderPlaced triggers a confirmation email
Consistency between aggregates OrderPlaced makes Inventory reserve stock
Integration between bounded contexts PaymentCaptured from Payments tells Shipping to prepare the parcel
Read models and projections Update an “orders by customer” view
Audit trail Store all events for compliance
Event sourcing Events are the source of truth for aggregate state
Analytics Stream events into a warehouse

Example: Raising and Dispatching Events

from dataclasses import dataclass
from datetime import datetime, timezone

@dataclass(frozen=True)
class OrderPlaced:
    order_id: str
    customer_id: str
    total_cents: int
    occurred_at: datetime

class Order:
    def __init__(self, order_id, customer_id):
        self.order_id, self.customer_id = order_id, customer_id
        self.lines, self.status, self.pending_events = [], "draft", []

    def add_line(self, product_id, qty, price_cents):
        self.lines.append((product_id, qty, price_cents))

    def place(self):
        if not self.lines:
            raise ValueError("an order needs at least one line")
        self.status = "placed"
        total = sum(q * p for _, q, p in self.lines)
        self.pending_events.append(
            OrderPlaced(self.order_id, self.customer_id, total, datetime.now(timezone.utc)))

handlers = {
    OrderPlaced: [
        lambda e: print(f"email: thanks for order {e.order_id}"),
        lambda e: print(f"inventory: reserve stock for {e.order_id}"),
    ]
}

def save_and_dispatch(order):
    # 1) save the aggregate (and, with an outbox, the events) in one transaction
    # 2) after commit, dispatch the events
    for event in order.pending_events:
        for handle in handlers.get(type(event), []):
            handle(event)
    order.pending_events.clear()

o = Order("o-1", "c-42")
o.add_line("p-1", 2, 49900)
o.place()
save_and_dispatch(o)
# email: thanks for order o-1
# inventory: reserve stock for o-1

The Order does not know about email or inventory; it only states what happened.

Designing Good Domain Events

  • Past tense, business terms: OrderCancelled, not UpdateOrderStatusEvent.

  • Immutable with an event ID and timestamp.

  • Enough data for consumers to act without calling back (order ID, customer ID, total), but not the whole aggregate.

  • Raised when the state change succeeds, and dispatched after commit so listeners never react to a rolled-back change.

  • Versioned when shared with other contexts; separate internal domain events from published integration events so internal models can change freely.

Reliability

  • Transactional outbox: write the event to an outbox table in the same transaction as the aggregate, then publish it to a broker asynchronously.

  • Idempotent handlers: events may be delivered more than once; record processed event IDs.

  • Ordering: guarantee order per aggregate (partition by aggregate ID) where it matters.

When Not to Use Them

  • To replace a simple method call that needs an immediate answer.

  • For trivial CRUD changes nobody cares about.

  • As a way to hide synchronous dependencies (a handler that must succeed for the original operation to be valid belongs in the same transaction or a saga).

Interview Tip

Define a domain event as an immutable, past-tense fact raised by an aggregate, give uses such as cross-aggregate consistency, integration and read models, and show raise-then-dispatch-after-commit. Mentioning the outbox, idempotent handlers, and the difference between domain and integration events shows production experience.

11

How do repositories work in DDD, and what is their main responsibility?

A repository provides collection-like access to aggregates: you ask it to get an aggregate by ID and to add or save one, and it hides how aggregates are stored (SQL, documents, event streams). Its main responsibility is to load and persist whole aggregates through their roots, so the domain model stays persistence-ignorant and every save keeps the aggregate’s invariants intact. There is normally one repository per aggregate type. Its interface belongs to the domain layer and its implementation to the infrastructure layer, which also makes domain logic easy to test with an in-memory version.

Read full answer

Applies tolayered and hexagonal (ports and adapters) architectures; ORMs such as Hibernate/JPA, Entity Framework and SQLAlchemy; event-sourced stores

Responsibilities

Responsibility Detail
Retrieve aggregates get(order_id) returns a fully loaded Order (root plus lines)
Persist aggregates add(order) and save(order) write all changes in one transaction
Hide storage details Callers never see SQL, tables or ORM sessions
Preserve boundaries Only aggregate roots have repositories; no OrderLineRepository
Concurrency control Check versions (optimistic locking) when saving
Domain-focused queries A few intention-revealing finders, such as find_placed_by_customer(customer_id)

Interface and Implementations

from abc import ABC, abstractmethod
import copy

class Order:
    def __init__(self, order_id, customer_id):
        self.order_id, self.customer_id = order_id, customer_id
        self.lines, self.status, self.version = [], "draft", 0

    def add_line(self, product_id, qty):
        if self.status != "draft":
            raise ValueError("placed orders cannot change")
        self.lines.append((product_id, qty))

    def place(self):
        if not self.lines:
            raise ValueError("an order needs at least one line")
        self.status = "placed"

class OrderRepository(ABC):                     # domain layer: the port
    @abstractmethod
    def get(self, order_id): ...
    @abstractmethod
    def save(self, order): ...

class ConcurrencyError(Exception):
    pass

class InMemoryOrderRepository(OrderRepository):  # infrastructure (or tests)
    def __init__(self):
        self._store = {}

    def get(self, order_id):
        return copy.deepcopy(self._store[order_id])

    def save(self, order):
        current = self._store.get(order.order_id)
        if current and current.version != order.version:
            raise ConcurrencyError(order.order_id)  # someone else saved first
        order.version += 1
        self._store[order.order_id] = copy.deepcopy(order)

# Application service using the repository
def place_order(repo, order_id):
    order = repo.get(order_id)
    order.place()
    repo.save(order)

repo = InMemoryOrderRepository()
o = Order("o-1", "c-42"); o.add_line("p-1", 2)
repo.save(o)
place_order(repo, "o-1")
print(repo.get("o-1").status, repo.get("o-1").version)   # placed 2

stale = repo.get("o-1"); fresh = repo.get("o-1")
repo.save(fresh)                                        # another user saves first
try:
    repo.save(stale)
except ConcurrencyError:
    print("conflict detected")                          # conflict detected

A SQL implementation would map the aggregate to orders and order_lines tables and use UPDATE ... WHERE id = ? AND version = ? for the same version check.

Design Guidelines

  • One repository per aggregate root, and it always returns complete aggregates.

  • Collection semantics: add, get, remove; avoid generic update(table, fields) methods.

  • Keep queries few and meaningful; for complex reporting, use separate read models (CQRS) instead of bloating repositories.

  • Transactions are usually controlled by the application service or a unit of work, not by domain objects.

  • Do not leak ORM types (sessions, query builders) into the domain.

Repository vs DAO

Repository Data Access Object (DAO)
Aggregate-oriented, domain language Table-oriented, CRUD per table
Returns domain objects with behaviour Often returns rows or data transfer objects
Interface lives in the domain Purely a persistence concern

Interview Tip

Explain that a repository gives collection-like access to whole aggregates while hiding storage, with one per aggregate root, the interface in the domain and the implementation in infrastructure. Showing optimistic version checks on save, and pointing to CQRS read models for complex queries, shows practical depth.

12

What is the difference between a repository and a service in DDD?

A repository is about storage: it retrieves and persists aggregates as if they were in an in-memory collection, and contains no business logic. A service is about behaviour that does not naturally belong to a single entity or value object. Domain services hold domain logic that spans several aggregates or concepts (for example, calculating a price using customer tier, promotions and the cart). Application services coordinate a use case: load aggregates through repositories, call domain methods or domain services, save the results, and publish events. In short, repositories answer “where do aggregates live?” and services answer “what work is done, and in what order?”.

Read full answer

Applies tolayered and hexagonal DDD architectures in any language

Comparison

Aspect Repository Domain service Application service
Purpose Load and save aggregates Domain logic across objects Orchestrate a use case
Contains business rules? No Yes No (delegates to the domain)
Layer Interface in domain; implementation in infrastructure Domain Application
Typical methods get(id), save(aggregate) calculate_price(order, customer), transfer(from_acc, to_acc, amount) place_order(command)
State Stateless, wraps storage Stateless Stateless; manages transactions
Depends on Database, ORM Domain objects Repositories, domain services, message bus

Example: Placing an Order With a Discount

class Order:
    def __init__(self, order_id, customer_id, subtotal_cents):
        self.order_id, self.customer_id = order_id, customer_id
        self.subtotal_cents, self.discount_cents, self.status = subtotal_cents, 0, "draft"

    def apply_discount(self, cents):
        if cents > self.subtotal_cents:
            raise ValueError("discount exceeds subtotal")
        self.discount_cents = cents

    def place(self):
        self.status = "placed"

class Customer:
    def __init__(self, customer_id, tier):
        self.customer_id, self.tier = customer_id, tier

# Repositories: storage only
class OrderRepository:
    def __init__(self): self._data = {}
    def get(self, oid): return self._data[oid]
    def save(self, order): self._data[order.order_id] = order

class CustomerRepository:
    def __init__(self): self._data = {}
    def get(self, cid): return self._data[cid]
    def save(self, c): self._data[c.customer_id] = c

# Domain service: business rule that needs both Order and Customer
class DiscountPolicy:
    RATES = {"gold": 10, "silver": 5}
    def discount_for(self, order, customer):
        return order.subtotal_cents * self.RATES.get(customer.tier, 0) // 100

# Application service: coordinates the use case
class PlaceOrderService:
    def __init__(self, orders, customers, policy):
        self.orders, self.customers, self.policy = orders, customers, policy

    def place(self, order_id):
        order = self.orders.get(order_id)
        customer = self.customers.get(order.customer_id)
        order.apply_discount(self.policy.discount_for(order, customer))
        order.place()
        self.orders.save(order)
        return {"type": "OrderPlaced", "order_id": order_id,
                "total_cents": order.subtotal_cents - order.discount_cents}

orders, customers = OrderRepository(), CustomerRepository()
customers.save(Customer("c-42", "gold"))
orders.save(Order("o-1", "c-42", 100_000))
print(PlaceOrderService(orders, customers, DiscountPolicy()).place("o-1"))
# {'type': 'OrderPlaced', 'order_id': 'o-1', 'total_cents': 90000}
  • Repositories fetch and store Order and Customer.

  • DiscountPolicy (domain service) holds a business rule involving two aggregates.

  • PlaceOrderService (application service) runs the steps, but every rule lives in the domain.

Common Mistakes

Mistake Fix
Business rules in repositories (save_and_apply_discount) Move rules into aggregates or domain services
Fat application services with all the logic (“anaemic domain model”) Push rules into entities and domain services
Domain services doing persistence Let application services call repositories
A “service” for every entity (OrderService with setStatus) Put behaviour on the entity itself

Interview Tip

State clearly that repositories handle persistence of aggregates while services handle behaviour, then distinguish domain services (cross-object business rules) from application services (orchestration and transactions). A short example where all three appear makes the separation obvious.

13

How do you handle complex domain logic spanning several entities and value objects?

Put each rule where its data and responsibility naturally live. Logic about one value goes into the value object (Money handles currency arithmetic). Rules that protect one aggregate’s consistency go into the aggregate root (Order checks that lines are valid). Logic that spans several aggregates or needs outside information goes into a domain service (pricing using customer tier and promotions), a specification (reusable business predicates), or a policy object (a swappable rule). Processes that run over time across aggregates are coordinated with domain events and sagas or process managers, while application services only orchestrate. The goal is a rich, expressive model, not a large service full of if statements.

Read full answer

Applies tocomplex business domains such as pricing, ordering, insurance underwriting, banking and logistics

Where Logic Belongs

Logic type Home Example
Rules about a single value Value object Money.add, DateRange.overlaps, Email validation
Invariants of one aggregate Aggregate root methods Order.add_line rejects changes after placement
Rules spanning aggregates or needing external data Domain service PricingService.price(order, customer, promotions)
Reusable business conditions Specification EligibleForFreeShipping
Interchangeable rules Policy / strategy DiscountPolicy per market
Multi-step processes over time Saga / process manager reacting to events Order, then payment, then shipment
Coordination of a use case Application service Load, call domain, save, publish

Example: Pricing an Order

from dataclasses import dataclass
from decimal import Decimal

@dataclass(frozen=True)
class Money:                                       # value object
    amount: Decimal
    currency: str = "INR"
    def __add__(self, o): return Money(self.amount + o.amount, self.currency)
    def __sub__(self, o): return Money(self.amount - o.amount, self.currency)
    def times(self, n): return Money(self.amount * n, self.currency)
    def percent(self, p): return Money((self.amount * p / 100).quantize(Decimal("0.01")), self.currency)

@dataclass(frozen=True)
class OrderLine:
    product_id: str
    category: str
    quantity: int
    unit_price: Money
    def subtotal(self): return self.unit_price.times(self.quantity)

class Order:                                       # aggregate root
    def __init__(self, order_id, customer_tier):
        self.order_id, self.customer_tier, self.lines = order_id, customer_tier, []
        self.discount = Money(Decimal("0"))

    def add_line(self, line):
        if line.quantity <= 0:
            raise ValueError("quantity must be positive")
        self.lines.append(line)

    def subtotal(self):
        total = Money(Decimal("0"))
        for l in self.lines:
            total = total + l.subtotal()
        return total

    def apply_discount(self, discount):
        if discount.amount > self.subtotal().amount:
            raise ValueError("discount cannot exceed subtotal")
        self.discount = discount

    def total(self):
        return self.subtotal() - self.discount

class ElectronicsPromotion:                        # policy
    def discount(self, order):
        eligible = Money(Decimal("0"))
        for l in order.lines:
            if l.category == "electronics":
                eligible = eligible + l.subtotal()
        return eligible.percent(10)

class TierDiscount:                                # policy
    RATES = {"gold": 5}
    def discount(self, order):
        return order.subtotal().percent(self.RATES.get(order.customer_tier, 0))

class PricingService:                              # domain service combining policies
    def __init__(self, policies):
        self.policies = policies
    def price(self, order):
        best = max((p.discount(order) for p in self.policies), key=lambda m: m.amount)
        order.apply_discount(best)                 # the aggregate still guards its invariant
        return order.total()

order = Order("o-1", "gold")
order.add_line(OrderLine("tv", "electronics", 1, Money(Decimal("40000"))))
order.add_line(OrderLine("book", "books", 2, Money(Decimal("500"))))
print(PricingService([ElectronicsPromotion(), TierDiscount()]).price(order).amount)
# 37000.00

Each piece is small and named in business terms: Money, OrderLine, Order, two policies, and one domain service choosing the best discount (10 percent of 40,000 = 4,000 beats 5 percent of 41,000 = 2,050).

Techniques for Managing Complexity

  • Make implicit concepts explicit: if code keeps checking “is this a priority customer with an active contract”, introduce a PriorityCustomer specification or value object.

  • Replace conditionals with polymorphism or policies when rules vary by market, product type or customer.

  • Keep aggregates small; use domain events to propagate changes across aggregates.

  • Test the domain in isolation with plain unit tests in business language.

  • Refactor towards deeper insight: when experts explain a rule more clearly, change the model to match.

Interview Tip

Explain the placement rules (value objects, aggregate roots, domain services, specifications and policies, sagas for long processes) and show a pricing example that uses several of them. Emphasising that application services stay thin and the model stays rich shows strong DDD understanding.

14

What is the difference between a domain service and an application service?

A domain service contains business logic that does not naturally belong to one entity or value object, typically because it involves several aggregates or a concept the business names as an action (“transfer money”, “calculate shipping cost”). It lives in the domain layer, uses the ubiquitous language, and knows nothing about databases, HTTP or messaging. An application service implements a use case: it receives a command, loads aggregates through repositories, calls domain objects and domain services, saves results, manages the transaction, and publishes events. It contains no business rules, only coordination. Put simply, domain services decide what the business rule is, and application services decide how a request is carried out.

Read full answer

Applies tolayered, hexagonal and clean architectures using DDD in Java, C#, Kotlin, Python and TypeScript

Comparison

Aspect Domain service Application service
Layer Domain Application
Contains Business rules and calculations Use-case orchestration
Knows about Entities, value objects, other domain services Repositories, transactions, security, messaging, domain services
Naming Domain verbs: FundsTransfer, ShippingCostCalculator Use cases: PlaceOrderHandler, TransferFundsService
Inputs Domain objects Commands or DTOs from the outside world
Side effects None beyond changing the domain objects passed in Persists, publishes events, sends notifications
Testing Pure unit tests Integration or tests with fakes

Example: Bank Transfer

from decimal import Decimal

class InsufficientFunds(Exception):
    pass

class Account:                                         # aggregate root
    def __init__(self, account_id, balance):
        self.account_id, self.balance = account_id, Decimal(balance)
    def withdraw(self, amount):
        if amount > self.balance:
            raise InsufficientFunds(self.account_id)
        self.balance -= amount
    def deposit(self, amount):
        self.balance += amount

class FundsTransfer:                                   # domain service: rule across two accounts
    DAILY_LIMIT = Decimal("100000")
    def transfer(self, source, target, amount, transferred_today):
        if amount <= 0:
            raise ValueError("amount must be positive")
        if transferred_today + amount > self.DAILY_LIMIT:
            raise ValueError("daily transfer limit exceeded")
        source.withdraw(amount)
        target.deposit(amount)

class AccountRepository:
    def __init__(self, accounts): self._a = {a.account_id: a for a in accounts}
    def get(self, aid): return self._a[aid]
    def save(self, acc): self._a[acc.account_id] = acc

class TransferFundsService:                            # application service: orchestration
    def __init__(self, repo, domain_service, publish):
        self.repo, self.domain, self.publish = repo, domain_service, publish

    def handle(self, cmd):
        source, target = self.repo.get(cmd["from"]), self.repo.get(cmd["to"])
        self.domain.transfer(source, target, Decimal(cmd["amount"]), Decimal("0"))
        # in production: one database transaction, or a saga if the accounts live apart
        self.repo.save(source); self.repo.save(target)
        self.publish({"type": "FundsTransferred", **cmd})

events = []
repo = AccountRepository([Account("A", "5000"), Account("B", "100")])
TransferFundsService(repo, FundsTransfer(), events.append).handle(
    {"from": "A", "to": "B", "amount": "1200"})
print(repo.get("A").balance, repo.get("B").balance, events[0]["type"])   # 3800 1300 FundsTransferred

This example changes two aggregates. In a single database this may be acceptable as a deliberate exception to the one-aggregate-per-transaction guideline; at scale, or across services, the transfer becomes a saga (withdraw, then deposit, with compensation).

Signs of Misplaced Logic

Symptom Fix
Application service full of if rules Move rules into aggregates or domain services
Domain service calling repositories or sending emails Move infrastructure calls to the application service
A domain service for logic that belongs to one entity Put the method on the entity
Every use case needing a domain service Probably an anaemic model; enrich entities

Interview Tip

Define the domain service as business logic spanning domain objects and the application service as use-case orchestration with transactions and infrastructure. A transfer example showing both, plus warning signs such as fat application services, makes the distinction memorable.

15

How do you implement aggregates so they stay transactionally consistent?

To keep aggregates consistent, make the aggregate the unit of transaction: load it whole, change it only through the root’s methods (which check every invariant), and save it atomically in one transaction, using optimistic concurrency (a version number) so concurrent changes are detected instead of overwritten. Change one aggregate per transaction; for rules spanning aggregates, use domain events with eventual consistency, publishing them reliably with a transactional outbox. Keep aggregates small so transactions are short and conflicts rare, and push unique or cross-aggregate constraints down to the database or to a dedicated aggregate when they must be strict.

Read full answer

Applies toDDD implementations with relational databases, document stores or event stores; ORMs such as JPA, Entity Framework and SQLAlchemy

Key Considerations

Consideration Approach
Invariants Enforced inside root methods before state changes
Atomic save Root and its children written in one database transaction
Concurrency Version column checked on update (optimistic locking); retry or report conflicts
One aggregate per transaction Cross-aggregate effects via events or sagas
Reliable events Outbox table written in the same transaction
Size Small aggregates to keep transactions fast
Uniqueness across aggregates Unique index in the database, or a dedicated aggregate (for example a UsernameRegistry)
Idempotency Commands carry IDs so retries do not apply twice

Example: Atomic Save With Version Check and Outbox (SQL)

BEGIN;

UPDATE orders
SET status = 'placed', version = version + 1
WHERE id = 'o-1' AND version = 7;          -- 0 rows updated means someone else changed it: abort

INSERT INTO order_lines (order_id, line_no, product_id, quantity, unit_price_cents)
VALUES ('o-1', 3, 'p-9', 1, 19900);

INSERT INTO outbox (id, aggregate_id, type, payload)
VALUES ('evt-123', 'o-1', 'OrderPlaced', '{"order_id": "o-1", "total_cents": 119700}');

COMMIT;

A relay process later reads the outbox and publishes OrderPlaced to the message broker, so the state change and the event can never get out of step.

Example: Optimistic Concurrency in Code

import copy

class ConcurrencyConflict(Exception):
    pass

class Order:
    def __init__(self, order_id):
        self.order_id, self.lines, self.status, self.version = order_id, [], "draft", 0
    def add_line(self, product_id, qty):
        if self.status != "draft":
            raise ValueError("placed orders cannot change")
        self.lines.append((product_id, qty))
    def place(self):
        if not self.lines:
            raise ValueError("an order needs at least one line")
        self.status = "placed"

class OrderRepository:
    def __init__(self):
        self.rows, self.outbox = {}, []
    def get(self, oid):
        return copy.deepcopy(self.rows[oid])
    def save(self, order, events=()):
        stored = self.rows.get(order.order_id)
        if stored and stored.version != order.version:
            raise ConcurrencyConflict(order.order_id)
        order.version += 1
        self.rows[order.order_id] = copy.deepcopy(order)   # "one transaction":
        self.outbox.extend(events)                          # state and events together

repo = OrderRepository()
o = Order("o-1"); o.add_line("p-1", 1); repo.save(o)

alice, bob = repo.get("o-1"), repo.get("o-1")
alice.place(); repo.save(alice, [{"type": "OrderPlaced", "order_id": "o-1"}])
bob.add_line("p-2", 3)
try:
    repo.save(bob)
except ConcurrencyConflict:
    print("conflict: reload and retry")     # conflict: reload and retry
print(repo.get("o-1").status, len(repo.outbox))   # placed 1

Bob’s change is rejected because Alice saved first. When Bob reloads, he finds a placed order, and the invariant “placed orders cannot change” holds.

Cross-Aggregate Consistency

  • Eventual: OrderPlaced leads Inventory to reserve stock in its own transaction; failures trigger compensation (cancel the order or back-order).

  • Sagas or process managers coordinate multi-step processes with compensating actions.

  • If the business truly needs both to change atomically, reconsider the boundary: maybe they are one aggregate, or the rule can be rephrased.

Pessimistic Locking (When Needed)

For hot aggregates with frequent conflicts, SELECT ... FOR UPDATE serialises changes, at the cost of waiting and the risk of deadlocks. Prefer optimistic locking by default.

Interview Tip

Describe the aggregate as the transaction unit: load whole, change through the root, save atomically with a version check, and publish events via an outbox. Stating “one aggregate per transaction, others eventually consistent” and showing a concurrency conflict example demonstrates solid implementation knowledge.

16

How do you handle performance problems when loading large aggregates?

Slow loading of a large aggregate is usually a design signal: the aggregate holds more than its invariants need. The first fix is to redesign the boundary. Split it into smaller aggregates referenced by ID (an Order should not contain a customer’s full history), and keep only the data needed to enforce invariants inside. Then apply technical measures: load efficiently (one query or a document per aggregate, avoid N+1 queries), use separate read models (CQRS) for screens and reports instead of loading aggregates, cache read-mostly aggregates, store summaries instead of whole collections, and, for event-sourced aggregates, use snapshots. Use lazy loading carefully, because it can hide N+1 queries and break aggregate boundaries.

Read full answer

Applies toDDD with relational databases and ORMs (JPA, Entity Framework, SQLAlchemy), document stores and event-sourced systems

Diagnose First

Symptom Likely cause
Aggregate has thousands of child entities Boundary too large (for example Customer holding all Orders)
Many queries per load N+1 lazy loading
Loading for display only Using the write model for reads
Slow event-sourced rebuilds Long event streams without snapshots
Frequent concurrency conflicts as well Many users updating the same large aggregate

Strategy 1: Shrink the Aggregate

Before: Customer { profile, addresses, orders[10,000], payments[...] }
After:  Customer { profile, addresses }
        Order    { order_id, customer_id, lines[...] }   (separate aggregate)
        Payment  { payment_id, order_id, ... }           (separate aggregate)

Ask which invariant needs all the orders loaded at once. Usually none: “a customer can have at most 3 unpaid orders” can be enforced with a counter kept on the customer, or a query at command time.

Strategy 2: Keep Summaries Instead of Collections

class Customer:
    MAX_OPEN_ORDERS = 3

    def __init__(self, customer_id, open_orders=0):
        self.customer_id = customer_id
        self.open_orders = open_orders           # summary, not a list of orders

    def register_new_order(self):
        if self.open_orders >= self.MAX_OPEN_ORDERS:
            raise ValueError("too many open orders")
        self.open_orders += 1

    def order_closed(self):                       # reacts to an OrderPaid or OrderCancelled event
        self.open_orders = max(0, self.open_orders - 1)

c = Customer("c-42", open_orders=2)
c.register_new_order()
try:
    c.register_new_order()
except ValueError as e:
    print(e)          # too many open orders

The aggregate stays tiny while the invariant still holds.

Strategy 3: Efficient Loading

  • Fetch the aggregate in one round trip: a join or a small number of batched queries (selectinload in SQLAlchemy, JOIN FETCH or entity graphs in JPA).

  • Store the aggregate as one document (PostgreSQL JSONB, MongoDB) when it is always loaded and saved together.

  • Index the foreign keys used to load child entities.

Strategy 4: CQRS Read Models

Screens and reports often need data from several aggregates or huge lists. Build denormalised read models (tables, search indexes or caches) updated from domain events, and query those directly. The write model then loads aggregates only for commands.

Strategy 5: Snapshots for Event-Sourced Aggregates

Store a snapshot of state every N events (for example every 100), then load the latest snapshot and replay only the events after it.

Strategy 6: Caching (Carefully)

Cache read-mostly aggregates (product catalogue entries, configuration), using version numbers to detect stale data. Do not cache aggregates under heavy concurrent writes without careful invalidation.

About Lazy Loading

Lazy loading of child collections can help when some operations need only the root, but:

  • It can cause N+1 queries.

  • It can fail outside a transaction or session.

  • It hides the fact that the aggregate is too big.

Prefer explicit, intention-revealing loading over relying on lazy proxies.

Interview Tip

Start by treating a large aggregate as a design problem: split boundaries, reference by ID, keep summaries for invariants. Then add technical fixes (efficient fetching, documents, CQRS read models, snapshots, caching) and note the risks of lazy loading. That order shows sound DDD judgement.

17

When would you use the specification pattern in DDD?

The specification pattern wraps a business rule that answers yes or no about an object in its own named class, with a method such as is_satisfied_by(candidate). Specifications can be combined with and, or and not. Use one when a condition is a meaningful business concept (“eligible for free shipping”, “overdue invoice”, “premium customer”) that is reused in several places, when rules must be composed or configured, or when the same rule drives validation, selection (queries) and construction. It keeps such rules explicit, testable and out of scattered if statements. For one-off conditions, a plain method is simpler.

Read full answer

Applies toDDD domain layers in Java, C#, Python and TypeScript; rule-heavy domains such as e-commerce, lending, insurance and compliance

Three Uses (from Evans and Fowler)

Use Example
Validation Does this order satisfy CanBeShippedInternationally?
Selection / querying Find all invoices satisfying Overdue
Construction to order Build a shipment that satisfies FitsInStandardBox

Example: Free Shipping Eligibility

from dataclasses import dataclass

class Specification:
    def is_satisfied_by(self, candidate):
        raise NotImplementedError
    def __and__(self, other): return AndSpec(self, other)
    def __or__(self, other): return OrSpec(self, other)
    def __invert__(self): return NotSpec(self)

class AndSpec(Specification):
    def __init__(self, a, b): self.a, self.b = a, b
    def is_satisfied_by(self, c): return self.a.is_satisfied_by(c) and self.b.is_satisfied_by(c)

class OrSpec(Specification):
    def __init__(self, a, b): self.a, self.b = a, b
    def is_satisfied_by(self, c): return self.a.is_satisfied_by(c) or self.b.is_satisfied_by(c)

class NotSpec(Specification):
    def __init__(self, s): self.s = s
    def is_satisfied_by(self, c): return not self.s.is_satisfied_by(c)

@dataclass
class Order:
    total_cents: int
    country: str
    customer_tier: str
    has_oversized_item: bool

class MinimumOrderValue(Specification):
    def __init__(self, cents): self.cents = cents
    def is_satisfied_by(self, o): return o.total_cents >= self.cents

class ShipsDomestically(Specification):
    def is_satisfied_by(self, o): return o.country == "IN"

class GoldCustomer(Specification):
    def is_satisfied_by(self, o): return o.customer_tier == "gold"

class ContainsOversizedItem(Specification):
    def is_satisfied_by(self, o): return o.has_oversized_item

free_shipping = (ShipsDomestically()
                 & (MinimumOrderValue(99_900) | GoldCustomer())
                 & ~ContainsOversizedItem())

orders = [
    Order(120_000, "IN", "standard", False),
    Order(20_000, "IN", "gold", False),
    Order(150_000, "US", "gold", False),
    Order(150_000, "IN", "gold", True),
]
print([free_shipping.is_satisfied_by(o) for o in orders])   # [True, True, False, False]

The rule reads almost like the business statement: “domestic orders worth at least 999 rupees, or from gold customers, without oversized items, ship free”.

When to Use It

  • The rule has a business name and appears in several places (checkout, cart banner, admin reports).

  • Rules are combined differently per market, campaign or product.

  • You need to explain decisions (“not eligible because the order contains an oversized item”).

  • You want the same rule for in-memory checks and database queries.

Specifications and Repositories

For querying, a specification can also produce a query expression so the database does the filtering:

class OverdueInvoices:
    def __init__(self, today): self.today = today
    def is_satisfied_by(self, inv): return inv["due"] < self.today and not inv["paid"]
    def to_sql(self): return ("due_date < %s AND paid = false", [self.today])

spec = OverdueInvoices("2026-11-04")
print(spec.to_sql())   # ('due_date < %s AND paid = false', ['2026-11-04'])

A repository method such as find_matching(spec) uses to_sql(), keeping the rule’s definition in one place. Libraries such as Ardalis.Specification (.NET) and Spring Data JPA’s Specification provide this.

Trade-offs

Benefit Cost
Rules named in the ubiquitous language More classes
Reusable and composable Over-engineering for simple, one-off checks
Easy unit tests per rule In-memory and SQL versions can drift unless generated from one definition
Explainable decisions Composite specifications can become hard to read if deeply nested

Interview Tip

Describe specifications as named, composable boolean business rules, show composition with and, or and not, and list the three uses: validation, selection and construction. Mentioning query translation for repositories, and warning against over-engineering simple checks, shows balanced judgement.

18

Which modelling strategies enforce invariants within an aggregate?

Invariants are enforced by making invalid states impossible to create or reach. Main strategies: encapsulate state so it changes only through intention-revealing methods on the aggregate root; validate in constructors and factories so objects start valid; use value objects that validate themselves (Money, Quantity, EmailAddress); check rules before mutating and fail with domain-specific exceptions; model states and lifecycles explicitly (state machines, or separate types per state); return read-only views of internal collections; and keep the aggregate small, so all its invariants can be checked in one transaction. Database constraints serve as an extra safety net, not the main rule holder.

Read full answer

Applies totactical DDD in Java, C#, Kotlin, Python and TypeScript; ordering, banking, booking and inventory domains

Strategies

Strategy What it prevents
Private state, public behaviour (order.place(), not order.status = ...) Bypassing rules with setters
Valid-on-creation constructors and factories Half-built objects
Self-validating value objects Invalid amounts, quantities, emails, date ranges
Guard clauses before changes Partial updates that leave the aggregate inconsistent
Explicit state machine Illegal transitions (shipping an unpaid order)
Read-only collections Callers adding lines directly to a list
Domain exceptions (OrderAlreadyPlaced) Vague failures; makes rules visible
Small aggregates Invariants that cannot be checked atomically
Database constraints as backup Bugs that slip past the model

Example: Order Aggregate

from dataclasses import dataclass

class DomainError(Exception): pass
class OrderNotDraft(DomainError): pass
class InvalidTransition(DomainError): pass

@dataclass(frozen=True)
class Quantity:
    value: int
    def __post_init__(self):
        if not 1 <= self.value <= 100:
            raise DomainError("quantity must be between 1 and 100")

@dataclass(frozen=True)
class OrderLine:
    product_id: str
    quantity: Quantity
    unit_price_cents: int

class Order:
    TRANSITIONS = {"draft": {"placed", "cancelled"}, "placed": {"paid", "cancelled"},
                   "paid": {"shipped"}, "shipped": set(), "cancelled": set()}
    MAX_TOTAL_CENTS = 10_000_000

    def __init__(self, order_id, customer_id):
        if not order_id or not customer_id:
            raise DomainError("order needs an id and a customer")
        self._id, self._customer_id = order_id, customer_id
        self._lines, self._status = [], "draft"

    @property
    def status(self): return self._status
    @property
    def lines(self): return tuple(self._lines)            # read-only view

    def add_line(self, product_id, qty, unit_price_cents):
        if self._status != "draft":
            raise OrderNotDraft(self._id)
        line = OrderLine(product_id, Quantity(qty), unit_price_cents)
        if self._total() + qty * unit_price_cents > self.MAX_TOTAL_CENTS:
            raise DomainError("order total limit exceeded")   # check before mutating
        self._lines.append(line)

    def _total(self):
        return sum(l.quantity.value * l.unit_price_cents for l in self._lines)

    def _move_to(self, new_status):
        if new_status not in self.TRANSITIONS[self._status]:
            raise InvalidTransition(f"{self._status} -> {new_status}")
        self._status = new_status

    def place(self):
        if not self._lines:
            raise DomainError("an order needs at least one line")
        self._move_to("placed")

    def mark_paid(self): self._move_to("paid")
    def ship(self): self._move_to("shipped")

o = Order("o-1", "c-42")
o.add_line("p-1", 2, 49_900)
o.place()
for action in (o.ship, lambda: o.add_line("p-2", 1, 100), lambda: Quantity(0)):
    try:
        action()
    except DomainError as e:
        print(type(e).__name__, e)
# InvalidTransition placed -> shipped
# OrderNotDraft o-1
# DomainError quantity must be between 1 and 100

Checklist for Each Invariant

  1. Name it in the ubiquitous language (“a placed order cannot change”).

  2. Find the single place that enforces it (usually one root method).

  3. Check before mutating, so a failure leaves the aggregate unchanged.

  4. Write a test that tries to break it.

  5. Decide if it is truly immediate: if it spans aggregates, handle it with events and eventual consistency instead.

Types per State (Alternative)

In strongly typed languages, represent states as separate types (DraftOrder, PlacedOrder) whose methods allow only valid operations, so illegal transitions do not compile. This is common in functional DDD with F#, Kotlin sealed classes or TypeScript discriminated unions.

Interview Tip

List the strategies (encapsulation, valid construction, value objects, guard clauses, state machines, read-only collections, small aggregates) and demonstrate a few in one aggregate. Stressing “check before mutating” and treating database constraints as a backup shows careful design.

19

How do you handle concurrency and synchronisation within aggregates?

Because an aggregate is a consistency boundary, concurrency is handled at the aggregate level: two requests that change the same aggregate must not overwrite each other’s work. The default approach is optimistic concurrency: each aggregate has a version number, and a save succeeds only if the version is unchanged since it was loaded. Otherwise the second writer gets a conflict, reloads and retries the command (or asks the user). Use pessimistic locking only for very hot aggregates where conflicts are frequent. Reduce contention by keeping aggregates small, splitting hot data, and using commutative operations or queues where order does not matter. Inside a process, aggregates are not shared between threads; each request works on its own loaded copy.

Read full answer

Applies toDDD with relational databases (version columns), document stores (ETags, conditional writes), event stores (expected version), and ORMs such as JPA `@Version` and Entity Framework concurrency tokens

Optimistic Concurrency (Default)

UPDATE orders
SET status = 'placed', version = version + 1
WHERE id = 'o-1' AND version = 4;
-- 1 row updated: success. 0 rows: someone else changed the order; raise a conflict.
import copy, random

class Conflict(Exception): pass

class Store:
    def __init__(self): self.data = {}
    def load(self, key): return copy.deepcopy(self.data[key])
    def save(self, agg, expected_version):
        if self.data[agg["id"]]["version"] != expected_version:
            raise Conflict(agg["id"])
        agg["version"] = expected_version + 1
        self.data[agg["id"]] = copy.deepcopy(agg)

def with_retry(store, key, change, attempts=3):
    for _ in range(attempts):
        agg = store.load(key)
        expected = agg["version"]
        change(agg)                          # re-run the command on fresh state
        try:
            store.save(agg, expected)
            return agg
        except Conflict:
            continue
    raise Conflict(key)

store = Store()
store.data["acc-1"] = {"id": "acc-1", "balance": 1000, "version": 0}

def withdraw(amount):
    def change(acc):
        if acc["balance"] < amount:
            raise ValueError("insufficient funds")
        acc["balance"] -= amount
    return change

# Simulate an interleaving: a concurrent write lands between load and save
original_save = store.save
def flaky_save(agg, expected):
    if random.random() < 0.5 and expected == 0:
        store.data["acc-1"] = {"id": "acc-1", "balance": 900, "version": 1}   # other writer
    original_save(agg, expected)
store.save = flaky_save

random.seed(1)
result = with_retry(store, "acc-1", withdraw(300))
print(result["balance"], result["version"])   # 600 2

Retrying re-runs the command against the latest state, so the business rule (“insufficient funds”) is checked again against real data. The concurrent 100 withdrawal and this 300 withdrawal are both applied.

Choosing a Strategy

Strategy How When
Optimistic (version, ETag, expected version) Detect conflicts at save Default; conflicts are rare
Pessimistic (SELECT ... FOR UPDATE, row locks) Block others while changing Very hot aggregates; short transactions
Single writer per aggregate Route all commands for one ID to one queue, partition or actor High throughput on a few hot aggregates
Commutative updates Increments merged without conflicts (counters, CRDTs) Counters, likes, metrics
Smaller aggregates Split hot parts out Different users change different parts

Reducing Conflicts

  • Keep aggregates small: one per order, not one per customer containing all orders.

  • Split independent data: if address changes and loyalty points updates conflict on Customer, they may belong to different aggregates.

  • Avoid unnecessary writes: do not bump versions for reads.

  • Use events for cross-aggregate effects instead of updating several aggregates together.

User-Facing Conflicts

For long edits (a user editing a draft for minutes), send the version or ETag to the client and return HTTP 409 Conflict or 412 Precondition Failed (with If-Match) when it is stale, so the user can review the latest data.

Event-Sourced Aggregates

Append new events with an expected stream version; the event store rejects the append if another event was written first (for example EventStoreDB’s expected revision, or a unique constraint on (stream_id, version)).

Interview Tip

Explain optimistic concurrency with a version check and command retry as the default, mention pessimistic locks and single-writer queues for hot aggregates, and describe design moves that reduce contention. Showing the SQL WHERE version = ? pattern and HTTP ETags shows end-to-end awareness.

20

How do domain events help design a loosely coupled system?

Domain events decouple parts of a system by letting a component announce what happened (OrderPlaced) without knowing who reacts. The publisher does its own work, records the event, and moves on. Subscribers in the same or other bounded contexts react independently: reserving stock, sending email, updating read models. This removes direct calls and dependencies between modules, lets you add new reactions without changing the publisher, allows each part to scale and fail independently, and replaces distributed transactions with eventual consistency. The costs are indirect flow, eventual consistency and the need for reliable, idempotent event handling.

Read full answer

Applies tomodular monoliths, microservices, CQRS and event-driven architectures, using brokers such as Kafka, RabbitMQ, Amazon SNS/SQS or in-process event buses

Coupled vs Event-Driven

Direct calls (tightly coupled):

OrderService.place():
    save order
    inventory.reserve(...)      # fails if Inventory is down
    billing.create_invoice(...)
    email.send_confirmation(...)
    loyalty.add_points(...)     # every new feature edits this method

Domain events (loosely coupled):

Order.place() -> raises OrderPlaced
Inventory, Billing, Email and Loyalty each subscribe to OrderPlaced

Example

from collections import defaultdict

class EventBus:
    def __init__(self):
        self.subscribers = defaultdict(list)
    def subscribe(self, event_type, handler):
        self.subscribers[event_type].append(handler)
    def publish(self, event):
        for handler in self.subscribers[event["type"]]:
            try:
                handler(event)
            except Exception as exc:                 # one failing subscriber does not stop others
                print(f"handler failed, will retry: {exc}")

bus = EventBus()
bus.subscribe("OrderPlaced", lambda e: print("inventory: reserve", e["order_id"]))
bus.subscribe("OrderPlaced", lambda e: print("email: confirm", e["order_id"]))

def loyalty_handler(e):
    raise RuntimeError("loyalty service unavailable")
bus.subscribe("OrderPlaced", loyalty_handler)       # added later, publisher unchanged

bus.publish({"type": "OrderPlaced", "order_id": "o-1", "total_cents": 99800})
# inventory: reserve o-1
# email: confirm o-1
# handler failed, will retry: loyalty service unavailable

With a real broker, each subscriber has its own queue or consumer group, so a failure in one is retried without affecting the others.

Benefits

Benefit Explanation
Open for extension New subscribers need no change to the publisher
Fewer runtime dependencies The order is placed even if email is down
Independent scaling Heavy subscribers (analytics) scale separately
Clear business flow Events document what matters in the domain
Smaller transactions Each aggregate changes in its own transaction
Auditability Events form a history of business actions

Costs and How to Handle Them

Cost Mitigation
Eventual consistency Design UIs and processes for pending states (“payment processing”)
Lost events Transactional outbox; durable brokers
Duplicate delivery Idempotent handlers keyed by event ID
Ordering Partition by aggregate ID; include versions
Hard-to-follow flows Correlation IDs, tracing, event catalogues and documentation
Schema changes Versioned event contracts; additive changes; separate internal and integration events
Hidden coupling via event content Publish only what consumers need, in a stable published language

Domain Events vs Integration Events

  • Domain events: inside a bounded context, can carry rich domain types, may change with the model.

  • Integration events: published to other contexts, use a stable, versioned schema, often translated from domain events.

When Not to Use Events

  • When the caller needs an immediate answer (checking stock before showing “in stock”).

  • When a step must succeed for the operation to be valid (charging a card before confirming a ticket); use a synchronous call or a saga with explicit states instead.

Interview Tip

Contrast direct calls with event publication, show that new subscribers can be added without touching the publisher, and list the trade-offs: eventual consistency, outbox, idempotency, ordering and observability. Distinguishing domain events from integration events shows mature design thinking.

21

What is event sourcing, and how does it differ from standard persistence?

Event sourcing stores an aggregate as the ordered sequence of domain events that happened to it (OrderCreated, LineAdded, OrderPlaced), rather than storing only its current state. To load an aggregate, you replay its events. To change it, you append new events. Standard (state-based) persistence overwrites rows with the latest values and loses the history of how they got there. Event sourcing gives a complete audit trail, time travel (state at any past moment), and natural event streams for projections and integration. In exchange, it adds complexity: event schema evolution, rebuilding read models, snapshots, and eventual consistency for queries, which are usually served by CQRS read models.

Read full answer

Applies tofinance and ledgers, ordering and booking systems, compliance-heavy domains, collaborative tools; stores such as EventStoreDB, Marten (PostgreSQL), Axon Server, or Kafka with care

State-Based vs Event-Sourced

Aspect State-based persistence Event sourcing
What is stored Current state (rows, documents) Every change, as immutable events
Write operation UPDATE or overwrite Append events to a stream
History Lost (unless separate audit tables) Complete by design
Reading current state Direct read Replay events (or load a snapshot, then later events)
Querying SQL on current data Projections into read models
Debugging What is the state? What happened, and in what order?
Concurrency Version column Expected stream version on append
Complexity Lower Higher

Example: Event-Sourced Order

from dataclasses import dataclass

@dataclass(frozen=True)
class OrderCreated:  order_id: str; customer_id: str
@dataclass(frozen=True)
class LineAdded:     product_id: str; qty: int; price_cents: int
@dataclass(frozen=True)
class LineRemoved:   product_id: str
@dataclass(frozen=True)
class OrderPlaced:   total_cents: int

class Order:
    def __init__(self):
        self.lines, self.status, self.version, self.new_events = {}, None, 0, []

    @classmethod
    def from_history(cls, events):
        order = cls()
        for e in events:
            order._apply(e)
            order.version += 1
        return order

    def _apply(self, e):                     # state changes only here
        if isinstance(e, OrderCreated):
            self.order_id, self.status = e.order_id, "draft"
        elif isinstance(e, LineAdded):
            self.lines[e.product_id] = (e.qty, e.price_cents)
        elif isinstance(e, LineRemoved):
            self.lines.pop(e.product_id, None)
        elif isinstance(e, OrderPlaced):
            self.status = "placed"

    def _raise(self, e):
        self._apply(e)
        self.new_events.append(e)

    # commands check rules, then raise events
    def add_line(self, product_id, qty, price_cents):
        if self.status != "draft":
            raise ValueError("placed orders cannot change")
        self._raise(LineAdded(product_id, qty, price_cents))

    def place(self):
        if not self.lines:
            raise ValueError("an order needs at least one line")
        total = sum(q * p for q, p in self.lines.values())
        self._raise(OrderPlaced(total))

stream = [OrderCreated("o-1", "c-42"), LineAdded("p-1", 2, 49_900),
          LineAdded("p-2", 1, 9_900), LineRemoved("p-2")]
order = Order.from_history(stream)
order.place()
print(order.status, order.version, order.new_events)
# placed 4 [OrderPlaced(total_cents=99800)]
print(Order.from_history(stream[:3]).lines)   # time travel: state before the removal
# {'p-1': (2, 49900), 'p-2': (1, 9900)}

The repository appends order.new_events to the stream order-o-1 with expected version 4, so a concurrent append is detected.

Key Building Blocks

Building block Purpose
Event store Append-only streams per aggregate, with optimistic concurrency
Apply / evolve functions Rebuild state from events
Snapshots Speed up loading of long streams
Projections Build read models (tables, search indexes) from events
Upcasters / versioning Handle old event formats when schemas change
Outbox or subscriptions Deliver events reliably to other contexts

Challenges

  • Event schema evolution: events are permanent, so changes must be backward-compatible or upcast.

  • Querying requires projections; rebuilding them from scratch can take time.

  • Deleting personal data (GDPR): use crypto-shredding (encrypt personal fields with per-person keys and delete the key) or keep personal data outside events.

  • Learning curve and more moving parts.

  • Eventual consistency between writes and read models.

Interview Tip

Define event sourcing as storing the sequence of events and replaying it to get state, contrast it with overwriting current state, and show a small example with commands, events, apply and time travel. Covering snapshots, projections, schema evolution and GDPR shows real-world awareness.

22

How does CQRS complement domain-driven design?

CQRS (Command Query Responsibility Segregation) separates the write side (commands that change state) from the read side (queries that return data). In DDD, the write side uses the rich domain model: commands load aggregates through repositories, aggregates enforce invariants, and changes raise domain events. The read side uses simple, denormalised read models shaped for each screen or report, updated from those events (or queried directly from the database). The two fit together because aggregates are designed for consistency, not for queries: CQRS keeps the domain model small and focused on rules, while queries get fast, purpose-built views without bending aggregates to fit them.

Read full answer

Applies toDDD systems with complex business rules and demanding read patterns (dashboards, search, lists across aggregates); often combined with event sourcing, though it does not require it

How the Pieces Fit

Command side                               Query side
------------                               ----------
PlaceOrder command                         GET /customers/c-42/orders
  -> application service                     -> read model: customer_orders table
  -> Order aggregate (invariants)               (denormalised, indexed for this query)
  -> repository.save
  -> OrderPlaced event  ---- projection ---> updates customer_orders

Example

from collections import defaultdict

# --- write side: domain model ---
class Order:
    def __init__(self, order_id, customer_id):
        self.order_id, self.customer_id, self.lines, self.status = order_id, customer_id, [], "draft"
    def add_line(self, sku, qty, price):
        if self.status != "draft":
            raise ValueError("placed orders cannot change")
        self.lines.append((sku, qty, price))
    def place(self):
        if not self.lines:
            raise ValueError("empty order")
        self.status = "placed"
        return {"type": "OrderPlaced", "order_id": self.order_id, "customer_id": self.customer_id,
                "total": sum(q * p for _, q, p in self.lines), "items": len(self.lines)}

# --- read side: projection into a query-friendly view ---
customer_orders = defaultdict(list)          # read model keyed for the screen
def project(event):
    if event["type"] == "OrderPlaced":
        customer_orders[event["customer_id"]].append(
            {"order_id": event["order_id"], "total": event["total"], "items": event["items"]})

def handle_place_order(order):               # command handler
    event = order.place()
    # save the aggregate here, then publish the event
    project(event)

for oid, lines in [("o-1", [("p-1", 2, 499)]), ("o-2", [("p-2", 1, 1299), ("p-3", 3, 99)])]:
    o = Order(oid, "c-42")
    for l in lines:
        o.add_line(*l)
    handle_place_order(o)

print(customer_orders["c-42"])               # query: no aggregates loaded
# [{'order_id': 'o-1', 'total': 998, 'items': 1}, {'order_id': 'o-2', 'total': 1596, 'items': 2}]

Why It Complements DDD

DDD concern How CQRS helps
Aggregates should be small and rule-focused Queries no longer need aggregates to hold display data
Repositories should stay simple Complex queries move to read models
Domain events capture business facts Events drive projections naturally
Different contexts need different views Each read model can be shaped per use
Performance Reads scale independently (replicas, caches, search engines)

Levels of CQRS

Level Description
Separate methods Commands return nothing (or an ID); queries change nothing (Bertrand Meyer’s CQS)
Separate models, same database Domain model for writes; SQL views or query objects for reads
Separate stores Read models in another database or search index, updated from events
With event sourcing Event store for writes; projections for all reads

Start at the simplest level that solves the problem; separate stores add eventual consistency and operations work.

Trade-offs

  • Eventual consistency: read models may lag; handle “read your own writes” (return data from the command, or briefly poll).

  • More moving parts: projections, rebuilds, monitoring of projection lag.

  • Duplication: data stored in several shapes.

  • Overkill for simple CRUD where reads and writes use the same shape.

Interview Tip

Explain that CQRS lets aggregates focus on invariants while read models serve queries, show the command, event, projection and query flow, and describe the levels from simple method separation to separate stores. Noting that CQRS does not require event sourcing, and is overkill for simple CRUD, shows balanced understanding.

23

When would you choose event sourcing in a DDD context?

Choose event sourcing for a bounded context or aggregate when the history of changes is itself valuable to the business, not just the current state. Typical cases: financial ledgers and accounts, regulated domains needing a full audit trail, workflows where you must know how and why a state was reached, temporal queries (“what did we know at the time?”), many different read models fed from the same facts, and domains naturally described as events (bookings, claims, trades). Avoid it for simple CRUD, for contexts without a strong need for history, or for teams without experience with its operational complexity. It is a per-context decision, not an all-or-nothing architecture.

Read full answer

Applies tocore domains in finance, insurance, logistics, healthcare, gaming and collaborative tools; tools such as EventStoreDB, Marten, Axon and custom PostgreSQL event tables

Good Fits

Situation Why event sourcing helps
Money and ledgers Balances must be explainable from transactions; accounting already works this way
Strict audit and compliance Every change is recorded with who, what and when, by design
Temporal queries Rebuild state as of any date; “as known at” reporting
Complex workflows and lifecycles Claims, orders and bookings evolve through many meaningful steps
Multiple read models Projections for search, analytics, dashboards from one stream of facts
Debugging and replay Replay events to reproduce bugs or test new logic on real history
Business analysis Events like “item removed from cart” carry insight that state alone loses
Collaboration and offline sync Merging sequences of operations

Poor Fits

Situation Why
Simple CRUD (user preferences, reference data) History adds little; complexity is not justified
Heavy ad-hoc querying on current state only Projections add work for no gain
Frequent large schema changes with no stable domain language Old events become hard to interpret
Strong delete requirements on raw data Immutable events complicate erasure (crypto-shredding needed)
Team new to DDD and distributed patterns Steep learning curve; mistakes are costly

Decision Questions

  1. Does the business talk in events (“claim filed”, “payment reversed”)?

  2. Do we need to explain or audit how each state was reached?

  3. Will we need temporal or “as of” queries?

  4. Do several read models need the same facts?

  5. Can we handle projections, versioning and eventual consistency?

Several yes answers suggest event sourcing for that context.

Example: Bank Account

events = [
    ("AccountOpened", 0),
    ("MoneyDeposited", 5000),
    ("MoneyWithdrawn", 1200),
    ("MoneyDeposited", 300),
    ("WithdrawalReversed", 1200),
]

def balance(history):
    total = 0
    for kind, amount in history:
        if kind in ("MoneyDeposited", "WithdrawalReversed"):
            total += amount
        elif kind == "MoneyWithdrawn":
            total -= amount
    return total

print(balance(events), balance(events[:3]))   # 5300 3800  (now, and after the third event)

The balance is always explainable from the events, and a reversal is a new fact, not an edit, exactly how accountants work.

Mixed Approach

Within one system:

  • Event-sourced: Account, Payment, Claim aggregates in the core domain.

  • State-based: Customer profile, Product catalogue, Settings.

  • Read models built from events for both kinds where useful.

Prerequisites for Success

  • Clear event naming in the ubiquitous language.

  • An event versioning strategy (upcasting, weak schemas, additive changes).

  • Snapshots for long streams.

  • Projection rebuild tooling and lag monitoring.

  • Privacy strategy for personal data.

Interview Tip

Name concrete fits (ledgers, audit, temporal queries, many projections, event-shaped domains) and poor fits (simple CRUD, heavy current-state querying, inexperienced teams), and stress that it is chosen per bounded context. A ledger example where corrections are new events makes the reasoning tangible.

24

How do you handle events that trigger side effects in other bounded contexts?

Handle them as asynchronous integration events with reliable delivery. The source context commits its change and its event together (a transactional outbox or change data capture), then publishes the event to a broker using a stable, versioned contract (an integration event, not the internal domain object). Each consuming context subscribes, translates the event into its own model (an anti-corruption layer where needed), and runs the side effect in its own transaction. Handlers are idempotent (deduplicate by event ID), retry with backoff, send poison messages to a dead-letter queue, and, for multi-step processes that can fail, are coordinated by a saga or process manager with compensating actions.

Read full answer

Applies tomodular monoliths and microservices using Kafka, RabbitMQ, Amazon SNS/SQS, Azure Service Bus or Google Pub/Sub

End-to-End Flow

Ordering context                         Broker              Shipping context
----------------                         ------              ----------------
1. Order.place() in a DB transaction
2. Same transaction: INSERT INTO outbox
3. Relay publishes OrderPlaced v1  ---->  orders topic  ----> 4. Consumer receives event
                                                              5. Skip if event_id already processed
                                                              6. Translate to CreateShipment
                                                              7. Save shipment + processed event_id
                                                                 in one local transaction

Idempotent Consumer Example

processed_ids = set()           # in production: a table with a unique key on event_id
shipments = {}

def translate(event):           # anti-corruption layer: Ordering's terms -> Shipping's terms
    return {"shipment_id": f"s-{event['order_id']}",
            "order_ref": event["order_id"],
            "address": event["delivery"]["address"],
            "priority": "express" if event.get("express") else "standard"}

def on_order_placed(event):
    if event["event_id"] in processed_ids:
        return "duplicate ignored"
    cmd = translate(event)
    shipments[cmd["shipment_id"]] = cmd           # same local transaction as recording the id
    processed_ids.add(event["event_id"])
    return "shipment created"

evt = {"event_id": "e-1", "type": "OrderPlaced", "version": 1, "order_id": "o-1",
       "delivery": {"address": "12 MG Road, Pune"}, "express": True}
print(on_order_placed(evt), on_order_placed(evt), len(shipments))
# shipment created duplicate ignored 1

Key Practices

Practice Purpose
Transactional outbox or CDC (Debezium) The state change and the event are never out of sync
Integration events with versioned schemas Internal models can change without breaking consumers
Anti-corruption layer in the consumer Keeps the consumer’s model clean
Idempotent handlers At-least-once delivery creates duplicates
Retries with backoff, then dead-letter queue Transient failures recover; poison messages do not block the queue
Ordering by aggregate key Events for one order processed in sequence (Kafka partition key)
Correlation and causation IDs Trace a business flow across contexts
Monitoring consumer lag and DLQ size Detect stuck or failing integrations

Multi-Step Processes: Sagas

When the side effect is part of a larger process that can fail, a saga coordinates steps and compensations:

OrderPlaced -> Payments: authorise
  PaymentAuthorised -> Inventory: reserve
    StockReserved -> Shipping: create shipment -> OrderConfirmed
    StockUnavailable -> Payments: void authorisation -> Ordering: cancel order
  • Choreography: each context reacts to events (simple flows).

  • Orchestration: a process manager sends commands and tracks state (complex flows, clearer visibility), for example with Temporal, Camunda or AWS Step Functions.

Things to Avoid

  • Synchronous chains of calls across contexts for side effects (fragile and slow).

  • Publishing before commit (consumers may act on changes that are later rolled back).

  • Sharing domain classes between contexts as event payloads.

  • Assuming exactly-once delivery without idempotency.

Interview Tip

Describe the full path (outbox, integration event, broker, idempotent consumer with translation, local transaction) and add retries, DLQs and ordering. Mentioning sagas with compensation for failure-prone processes, and the choice between choreography and orchestration, shows strong distributed-design knowledge.

25

How does DDD handle domain logic that changes over time?

DDD expects the domain model to evolve as understanding and the business change, and it keeps that evolution manageable. Continuous collaboration with domain experts and a living ubiquitous language reveal changes early. Refactoring toward deeper insight reshapes the model when a better concept appears. Bounded contexts confine each change to one model. Explicit rules (value objects, specifications, policies) can be swapped or versioned instead of rewritten. Domain events let new behaviour be added without editing existing code. Tests written in business language protect existing rules, and anti-corruption layers and versioned contracts shield other contexts from internal changes.

Read full answer

Applies tolong-lived business systems in pricing, regulation-driven domains (tax, insurance), ordering and logistics

Mechanisms for Change

Mechanism How it helps
Ubiquitous language New or changed terms signal model changes; the code is renamed to match
Refactoring toward deeper insight Replace awkward models when experts explain a concept better
Bounded contexts A pricing change does not ripple into shipping
Policies and strategies New rule versions plug in without editing aggregates
Specifications Rules composed and reconfigured
Domain events New reactions added as new subscribers
Effective-dated rules Old and new rules coexist by date
Behaviour tests in domain terms Catch regressions while refactoring
Versioned integration contracts Other contexts migrate on their own schedule

Example: Discount Rules Changing by Date

from datetime import date

class Policy2025:
    def discount(self, subtotal): return subtotal * 5 // 100

class Policy2026:                                   # new rule: tiered discount
    def discount(self, subtotal):
        return subtotal * (10 if subtotal >= 50_000 else 5) // 100

class DiscountPolicies:
    """Effective-dated policies: the model keeps history without if-chains in Order."""
    def __init__(self):
        self.schedule = [(date(2025, 1, 1), Policy2025()), (date(2026, 4, 1), Policy2026())]
    def for_date(self, d):
        current = None
        for start, policy in self.schedule:
            if d >= start:
                current = policy
        return current

class Order:
    def __init__(self, subtotal, placed_on):
        self.subtotal, self.placed_on = subtotal, placed_on
    def total(self, policies):
        return self.subtotal - policies.for_date(self.placed_on).discount(self.subtotal)

policies = DiscountPolicies()
print(Order(60_000, date(2026, 3, 1)).total(policies))   # 57000  (old 5 percent rule)
print(Order(60_000, date(2026, 5, 1)).total(policies))   # 54000  (new tiered rule)

Orders placed before the change keep their original rule, which matters for refunds and audits.

Refactoring Toward Deeper Insight

A typical evolution:

  1. The first model has Order.discount_percent set by a manager.

  2. Conversations reveal discounts actually come from promotions with eligibility rules and dates.

  3. The model gains Promotion (with a specification for eligibility) and a PricingPolicy domain service.

  4. Code, tests and glossary are renamed to the new terms; the old field is migrated.

Evans calls such moments breakthroughs: the model becomes simpler and closer to the business.

Keeping Changes Safe

  • Characterisation and behaviour tests in business language (“Given a gold customer, when the order exceeds 500, then the discount is 10 percent”).

  • Feature flags or policy configuration to roll out rule changes gradually.

  • Event versioning (upcasters) when event-sourced aggregates change shape.

  • Data migration plans when value objects or aggregates change.

  • Expand-and-contract for contracts with other contexts: add the new field, migrate consumers, remove the old field.

Organisational Practices

  • Regular modelling sessions (Event Storming refreshers) as the business changes.

  • Domain experts reviewing scenarios and examples.

  • Treating the glossary as a maintained artefact.

  • Architecture decision records explaining why models changed.

Interview Tip

Explain that DDD treats the model as continuously evolving, then show concrete mechanisms: language-driven refactoring, bounded contexts, swappable or effective-dated policies, events for new behaviour, and tests in business language. The dated discount policy example shows how old and new rules can coexist safely.

26

What is a context map in DDD, and what is it for?

A context map is a diagram and description of all bounded contexts in a system and the relationships between them: who is upstream (its model influences others) and who is downstream, and which integration pattern each relationship uses (customer-supplier, conformist, anti-corruption layer, shared kernel, open host service, published language, partnership or separate ways). Its purpose is to make the real landscape visible, including politics, team dependencies and legacy systems, so you can plan integration, spot risks (a core context conforming to a messy legacy model), align teams, and decide where to invest in translation or redesign.

Read full answer

Applies tostrategic DDD for large systems, monolith decomposition, team topology planning and integration with legacy or third-party systems

Relationship Patterns

Pattern Meaning Typical use
Partnership Two contexts plan and change together Closely aligned teams delivering one capability
Shared kernel A small, jointly owned subset of the model Shared value objects like Money, with strict change control
Customer-supplier Upstream (supplier) prioritises downstream (customer) needs Internal teams with negotiated APIs
Conformist Downstream adopts the upstream model as is Integrating a dominant vendor or a team that will not change
Anti-corruption layer (ACL) Downstream translates the upstream model into its own Protecting a core domain from legacy or external models
Open host service (OHS) Upstream offers a well-defined protocol for many consumers Public or platform APIs
Published language Documented shared format for exchanges Versioned event schemas, industry standards (ISO 20022, HL7 FHIR)
Separate ways No integration; capabilities duplicated Integration costs more than it saves
Big ball of mud A region without clear models Mark legacy areas honestly and isolate them

Example: E-Commerce Context Map

[Catalogue] --OHS/PL--> [Ordering] <--Customer/Supplier-- [Pricing]
                            |
                     OrderPlaced (PL)
                            v
[Payments] <--ACL-- [Payment Provider (external)]
                            |
                    PaymentCaptured (PL)
                            v
                       [Shipping] --ACL--> [Legacy Warehouse System (big ball of mud)]

[Ordering] and [Invoicing] share a small Shared Kernel: Money, TaxCode

What the map tells the team:

  • Ordering is core and is protected: it consumes Catalogue through a published API rather than reading its tables.

  • Payments and Shipping use ACLs so the external provider and legacy warehouse models do not leak in.

  • The shared kernel between Ordering and Invoicing must change only by joint agreement.

  • Pricing is a supplier to Ordering, so Ordering’s needs should shape Pricing’s API roadmap.

What to Record per Relationship

Item Example
Direction Catalogue (upstream) to Ordering (downstream)
Pattern Open host service with published language
Mechanism REST API plus ProductPriceChanged events
Contract owner and versioning Catalogue team; semantic versioning, 6-month deprecation
Team relationship Separate teams; weekly sync
Risks Catalogue outages block checkout; mitigate with a local cache

Why It Is Useful

  • Shared understanding of a large system on one page.

  • Integration planning: choose ACLs where models differ, OHS where many consumers exist.

  • Risk discovery: hidden dependencies, shared databases, contexts conforming to poor models.

  • Team alignment: shows where coordination is needed (Conway’s law).

  • Modernisation roadmap: where to extract, isolate or rewrite.

Good Practices

  • Draw the map as it is, not as you wish it were; then draw a target map.

  • Keep it lightweight and current (a diagram plus a short table in the repository).

  • Revisit it when teams, contexts or integrations change.

Interview Tip

Define the context map as the overview of bounded contexts and their upstream and downstream relationships, list the main patterns, and walk through an example map explaining why each pattern was chosen. Stressing that it should reflect reality, including legacy mud and team politics, shows strategic maturity.

27

What is an anti-corruption layer in DDD, and when would you use one?

An anti-corruption layer (ACL) is a translation boundary that a downstream bounded context places between itself and an upstream system whose model differs (a legacy application, a third-party API or another team’s context). It converts the external model, terms and protocols into the downstream’s own ubiquitous language and back, so foreign concepts, odd naming and design flaws do not leak into and “corrupt” the domain model. Use one when integrating with legacy systems, external vendors, or contexts whose models are unstable or poor, especially when protecting a core domain. It is typically built from adapters, translators (mappers) and facades.

Read full answer

Applies tolegacy modernisation (strangler fig), integrations with payment, shipping or ERP vendors, mergers of systems, and microservices consuming other teams' APIs

What an ACL Contains

Component Role
Facade or client Simplifies the external API (handles authentication, retries, pagination)
Adapter Implements a port defined by the domain (ShippingProvider)
Translator / mapper Converts external data and codes into domain objects and back
Error mapping Turns vendor error codes into domain-meaningful outcomes

Example: Legacy Warehouse System

The legacy system returns cryptic codes:

legacy_response = {"ORD_NO": "000123", "STAT_CD": "03", "WH": "PN1", "QTY_SHP": "0002"}

The Shipping context wants clean concepts:

from dataclasses import dataclass
from enum import Enum

class ShipmentStatus(Enum):
    AWAITING_PICK = "awaiting_pick"
    PACKED = "packed"
    DISPATCHED = "dispatched"

@dataclass(frozen=True)
class ShipmentUpdate:
    order_id: str
    status: ShipmentStatus
    warehouse: str
    shipped_quantity: int

class WarehouseStatusUnknown(Exception):
    pass

class LegacyWarehouseTranslator:                       # the anti-corruption layer
    STATUS = {"01": ShipmentStatus.AWAITING_PICK,
              "02": ShipmentStatus.PACKED,
              "03": ShipmentStatus.DISPATCHED}
    WAREHOUSES = {"PN1": "Pune-1", "BL2": "Bengaluru-2"}

    def to_domain(self, raw):
        try:
            status = self.STATUS[raw["STAT_CD"]]
        except KeyError:
            raise WarehouseStatusUnknown(raw["STAT_CD"])
        return ShipmentUpdate(
            order_id="o-" + raw["ORD_NO"].lstrip("0"),
            status=status,
            warehouse=self.WAREHOUSES.get(raw["WH"], raw["WH"]),
            shipped_quantity=int(raw["QTY_SHP"]),
        )

legacy_response = {"ORD_NO": "000123", "STAT_CD": "03", "WH": "PN1", "QTY_SHP": "0002"}
print(LegacyWarehouseTranslator().to_domain(legacy_response))
# ShipmentUpdate(order_id='o-123', status=<ShipmentStatus.DISPATCHED: 'dispatched'>, warehouse='Pune-1', shipped_quantity=2)

The rest of the Shipping model only ever sees ShipmentUpdate and ShipmentStatus, never STAT_CD = "03".

When to Use an ACL

Situation Why
Integrating legacy systems Keep old schemas and codes out of the new model
Third-party APIs (payments, shipping, CRM) Vendor models change on the vendor’s schedule; you might switch vendors
Another team’s context with a different language Avoid becoming a conformist when it would hurt your core model
Strangler-fig migration New services talk to the old system through ACLs while functionality moves
Merging companies or systems Different models of customers or products

When It May Not Be Worth It

  • The upstream model is clean and close to yours (conformist is acceptable).

  • The integration is small and not part of the core domain.

  • You own both sides and can simply align the models (partnership or shared kernel).

Design Tips

  • Define the port (interface) in your domain language, and implement it in the ACL.

  • Translate both directions (commands out, data in).

  • Map errors into domain outcomes (PaymentDeclined rather than ERR_51).

  • Test the translator heavily with real samples from the external system.

  • Monitor for unknown codes or schema changes.

  • Keep the ACL at the edge (infrastructure layer); it can be a module, a library or a separate service.

Interview Tip

Define the ACL as a translation layer protecting a downstream model from a foreign one, show a translator turning legacy codes into domain objects, and list when to use it: legacy, vendors, strangler migrations and messy upstream contexts. Mentioning when a conformist relationship is acceptable instead shows balanced judgement.

28

How might you implement a policy in DDD, and what are its advantages?

In DDD a policy has two common meanings. The first is a business rule or decision encapsulated as a swappable object (the strategy pattern in domain language): DiscountPolicy, OverbookingPolicy or CancellationFeePolicy, injected into aggregates or domain services so the rule can vary by market, customer type or date without changing the aggregate. The second, from Event Storming, is a reactive rule, “whenever event X happens, then issue command Y” (“when a payment fails three times, suspend the subscription”), usually implemented as an event handler or process manager. Both make rules explicit, named, testable and replaceable.

Read full answer

Applies topricing, fees, eligibility, limits, workflow automation, and sagas in DDD systems

Kind 1: Decision Policy (Strategy)

from abc import ABC, abstractmethod
from datetime import datetime, timedelta

class CancellationFeePolicy(ABC):
    @abstractmethod
    def fee_cents(self, booking, now): ...

class FlexiblePolicy(CancellationFeePolicy):
    def fee_cents(self, booking, now):
        return 0 if booking.starts_at - now > timedelta(hours=24) else booking.price_cents // 2

class StrictPolicy(CancellationFeePolicy):
    def fee_cents(self, booking, now):
        return booking.price_cents if booking.starts_at - now < timedelta(days=7) else booking.price_cents // 2

class Booking:
    def __init__(self, booking_id, price_cents, starts_at, fee_policy):
        self.booking_id, self.price_cents, self.starts_at = booking_id, price_cents, starts_at
        self.fee_policy, self.status = fee_policy, "confirmed"

    def cancel(self, now):
        if self.status != "confirmed":
            raise ValueError("only confirmed bookings can be cancelled")
        fee = self.fee_policy.fee_cents(self, now)
        self.status = "cancelled"
        return {"type": "BookingCancelled", "booking_id": self.booking_id, "fee_cents": fee}

now = datetime(2026, 11, 4, 10, 0)
starts = now + timedelta(days=3)
print(Booking("b-1", 10_000, starts, FlexiblePolicy()).cancel(now)["fee_cents"])  # 0
print(Booking("b-2", 10_000, starts, StrictPolicy()).cancel(now)["fee_cents"])    # 10000

The Booking aggregate keeps its own invariants (only confirmed bookings can be cancelled) while the fee rule is delegated to the policy chosen for that booking.

Kind 2: Reactive Policy (“Whenever … Then …”)

class SuspendAfterRepeatedFailures:
    """Whenever a payment fails three times in a row, suspend the subscription."""
    def __init__(self, send_command):
        self.failures, self.send = {}, send_command

    def on_payment_failed(self, event):
        sid = event["subscription_id"]
        self.failures[sid] = self.failures.get(sid, 0) + 1
        if self.failures[sid] == 3:
            self.send({"type": "SuspendSubscription", "subscription_id": sid})

    def on_payment_succeeded(self, event):
        self.failures.pop(event["subscription_id"], None)

commands = []
policy = SuspendAfterRepeatedFailures(commands.append)
for _ in range(3):
    policy.on_payment_failed({"subscription_id": "sub-7"})
print(commands)   # [{'type': 'SuspendSubscription', 'subscription_id': 'sub-7'}]

In production, the failure counter lives in durable storage (or the subscription aggregate itself), and handlers are idempotent.

Advantages

Advantage Explanation
Explicit business rules Named in the ubiquitous language; easy to discuss with experts
Open for extension New markets or customer types get new policy classes
Smaller aggregates Variable rules move out; aggregates keep core invariants
Testability Each policy tested in isolation with simple inputs
Configuration and A/B testing Choose policies per tenant, region or experiment
Effective dating Keep old policies for historical orders and audits
Decoupled automation Reactive policies link events to commands without coupling contexts

Implementation Tips

  • Choose the policy at creation time (via a factory) and record which one applied, so later recalculations are consistent.

  • Keep policies pure where possible: inputs in, decision out, no persistence.

  • Make reactive policies idempotent and observable; they are part of business processes.

  • Avoid policy explosion: if many policies differ only by numbers, parameterise one policy instead.

Interview Tip

Describe both meanings: decision policies as strategies injected into the model, and reactive “whenever X then Y” policies from Event Storming implemented as event handlers. Showing one of each and listing advantages like explicit rules, extensibility and testability gives a complete answer.

29

How can DDD coexist with a microservices architecture?

DDD and microservices fit together because DDD supplies the boundaries that microservices need. Bounded contexts are the natural candidates for service boundaries: each service owns one context’s model, language and data. Aggregates define the consistency units inside a service, so transactions stay local. Domain events become the integration events that connect services asynchronously. Context-map patterns (anti-corruption layers, open host services, published languages) describe how services talk. The key modelling caution: a bounded context may contain several services, but a service should not span several contexts, and you should not split an aggregate across services.

Read full answer

Applies todesigning or decomposing systems into microservices; the modelling side of service boundaries (operational concerns such as deployment and scaling belong to microservices practice)

Mapping DDD Concepts to Microservices

DDD concept Microservices counterpart
Bounded context Service (or a small group of services) with its own codebase and data store
Ubiquitous language API resource names, event names and internal model
Aggregate Unit of consistency within a service’s database transaction
Domain event Integration event published to a broker (via an outbox)
Context map Service dependency and integration diagram
Anti-corruption layer Adapter or translation module in the consuming service
Open host service and published language Public API and versioned event schemas
Subdomain type (core, supporting, generic) Where to invest in custom services vs buy or use SaaS

Example: Online Store

Ordering service (core)        owns Order aggregate, publishes OrderPlaced
Pricing service (core)         owns Promotion and PriceList, answers price quotes
Payments service (generic)     wraps an external provider through an ACL
Shipping service (supporting)  consumes PaymentCaptured, owns Shipment aggregate
Catalogue service (supporting) open host service for product data

Each service has its own database. Ordering stores customer_id and the agreed price at checkout (copied, not queried live), so it does not depend on Pricing or Catalogue for historical orders.

Modelling Rules That Keep Services Healthy

  1. One aggregate per transaction, inside one service: cross-service consistency uses events and sagas.

  2. Reference other contexts by ID and copy the data you need into your own model.

  3. Do not share domain classes across services; share only published contracts.

  4. Keep services aligned with business capabilities, not technical layers (“database service”) or entities (“customer CRUD service”).

  5. Avoid chatty synchronous chains: if every request needs three other services, the boundaries are likely wrong.

  6. Separate internal domain events from integration events, so internal refactoring does not break consumers.

Warning Signs of Poor DDD Alignment

Symptom Likely modelling problem
Distributed transactions between services An aggregate or invariant was split
Every feature changes several services Boundaries cut across a capability
Services sharing a database No real bounded contexts
Services named after nouns with only CRUD endpoints Entity services instead of capabilities
Huge “common” library of domain classes Shared model where contexts should differ

Start With a Modular Monolith

Many teams first build a modular monolith with bounded contexts as modules, explicit interfaces and separate schemas. Once boundaries are proven stable, contexts can be extracted into services with little remodelling. This reduces the cost of getting boundaries wrong early.

When Not to Force It

  • Small products with one team and simple logic may not need microservices or full DDD.

  • Generic subdomains (authentication, email) are often better as SaaS or libraries than custom services.

Interview Tip

Explain that bounded contexts guide service boundaries, aggregates keep transactions local, and domain events become integration events, then give an e-commerce example and the warning signs of bad boundaries. Recommending a modular monolith first, and never splitting aggregates across services, shows practical wisdom.

30

Which factors influence refactoring a legacy system with a DDD approach?

Whether to refactor a legacy system with DDD depends on business value and pain, not on fashion. Key factors: domain complexity (DDD pays off when rules are rich and changing), strategic importance (is this the core domain that differentiates the business?), pain level (slow delivery, frequent bugs, rules nobody understands), availability of domain experts, team skills and capacity, legacy constraints (shared databases, missing tests, vendor lock-in), risk tolerance and timelines, and organisational support. If the decision is yes, refactor incrementally: identify bounded contexts, add characterisation tests, isolate the legacy behind anti-corruption layers, and use the strangler fig pattern to move one capability at a time.

Read full answer

Applies tomodernising monoliths, ERP-heavy or decades-old systems, and planning DDD adoption in existing codebases

Decision Factors

Factor Favours DDD refactoring Argues against
Domain complexity Many rules, exceptions, workflows Mostly CRUD and reports
Strategic value Core domain, competitive advantage Generic or supporting areas (buy or keep)
Change frequency Frequent business changes, slowed by the code Stable, rarely changed
Pain Bugs, fear of change, long lead times System works and is cheap to maintain
Domain expert access Experts available to model with No access to people who know the rules
Team skills DDD experience or willingness to learn No capacity for training
Test coverage Can add characterisation tests Untestable and no time to add tests
Data coupling Shared database can be split gradually Dozens of systems write to the same tables
Budget and timeline Room for incremental investment Fixed short deadline
Organisational support Business sponsors and stable teams Frequent reorganisation, no ownership

Incremental Approach

  1. Map the current landscape: draw a context map of the legacy system as it is, including “big ball of mud” areas.

  2. Identify subdomains: focus on the core domain; consider buying or leaving generic parts.

  3. Choose a first slice: a valuable, reasonably separable capability (for example pricing rules).

  4. Add characterisation tests around current behaviour before changing it.

  5. Build the new model in its own bounded context with a clean ubiquitous language.

  6. Isolate with an anti-corruption layer: translate between legacy data and the new model.

  7. Strangle gradually: route requests for that capability to the new context, keep the legacy for the rest.

  8. Migrate data with dual writes or change data capture, then switch the source of truth.

  9. Repeat for the next capability; retire legacy pieces as they become unused.

Example: Legacy Order Pricing

def legacy_price(row):                       # legacy: status codes, magic numbers
    p = row["AMT"]
    if row["CTYPE"] == "G" and row["AMT"] > 5000:
        p = p * 0.9
    if row["PROMO"] == "Y":
        p = p - 100
    return round(p, 2)

class PricingPolicy:                         # new model in the Pricing context
    def price(self, subtotal, customer_tier, has_promo):
        total = subtotal * 0.9 if customer_tier == "gold" and subtotal > 5000 else subtotal
        return round(total - (100 if has_promo else 0), 2)

def via_acl(row):                            # anti-corruption layer
    return PricingPolicy().price(row["AMT"], {"G": "gold"}.get(row["CTYPE"], "standard"),
                                 row["PROMO"] == "Y")

samples = [{"AMT": 6000, "CTYPE": "G", "PROMO": "Y"}, {"AMT": 3000, "CTYPE": "S", "PROMO": "N"}]
print(all(legacy_price(r) == via_acl(r) for r in samples))   # True: characterisation check

Running the old and new implementations side by side (“parallel run”) on real data builds confidence before switching.

Risks and Mitigations

Risk Mitigation
Big-bang rewrite failure Incremental strangler approach
Hidden business rules in legacy code Characterisation tests; parallel runs; expert reviews
Shared database coupling Views, CDC, and gradual ownership transfer
Losing momentum Deliver visible business value with each slice
Over-engineering Apply full DDD only to the core domain

Interview Tip

List the decision factors (complexity, strategic value, pain, expert access, skills, legacy constraints, support), recommend applying DDD where the core domain is, and describe an incremental path with characterisation tests, ACLs and the strangler fig pattern. A parallel-run example shows you know how to reduce migration risk.

31

How can DDD principles be applied at different scales of a project?

DDD applies at several scales. At the enterprise or system scale, strategic design divides the business into subdomains, draws bounded contexts and a context map, and decides where to invest (core vs supporting vs generic). At the context or team scale, each team builds a ubiquitous language and a domain model for its context, choosing integration patterns with neighbours. At the code scale, tactical patterns (aggregates, entities, value objects, domain events, repositories, domain services) shape classes and modules. Even small projects benefit from the lightweight parts (a shared language and value objects) without the full machinery, and you choose how much DDD to apply per subdomain.

Read full answer

Applies toorganisations of any size, from single-team products to multi-team platforms and enterprise portfolios

Scales and Their Practices

Scale Main questions DDD practices
Enterprise / portfolio Where does the business compete? Which areas exist? Subdomain classification, core domain chart, context maps across systems
System / product How is the system divided? How do parts talk? Bounded contexts, context-map patterns, integration events, ACLs
Team / context What does our model look like? Ubiquitous language, Event Storming, glossary, modelling sessions
Module / service How is the code organised? Layered or hexagonal architecture, application vs domain services
Class / function How do we express rules? Aggregates, entities, value objects, specifications, policies, domain events

Example: One Company at Each Scale

  • Enterprise: a retailer classifies pricing and personalised recommendations as core, inventory and fulfilment as supporting, and payments and identity as generic (buy or use SaaS).

  • System: the e-commerce platform has contexts Catalogue, Ordering, Pricing, Payments and Shipping, with a context map showing ACLs to the warehouse system.

  • Team: the Ordering team runs Event Storming and keeps a glossary (Order, Order line, Place, Agreed price).

  • Code:

from dataclasses import dataclass
from decimal import Decimal

@dataclass(frozen=True)
class Money:
    amount: Decimal
    currency: str = "INR"

class Order:
    def __init__(self, order_id):
        self.order_id, self.lines, self.status = order_id, [], "draft"
    def add_line(self, sku, qty, price: Money):
        if self.status != "draft":
            raise ValueError("placed orders cannot change")
        self.lines.append((sku, qty, price))
    def place(self):
        if not self.lines:
            raise ValueError("an order needs at least one line")
        self.status = "placed"
        return {"type": "OrderPlaced", "order_id": self.order_id}

o = Order("o-1"); o.add_line("p-1", 1, Money(Decimal("499"))); print(o.place())
# {'type': 'OrderPlaced', 'order_id': 'o-1'}

Scaling DDD Effort to Value

Subdomain type Recommended depth
Core Full strategic and tactical DDD; best people; continuous modelling
Supporting Lighter model; simpler architecture; may be CRUD with a few rules
Generic Buy, use open source or SaaS; integrate through an ACL

Small Projects

For a small app or a single team:

  • Use a ubiquitous language and name code after business concepts.

  • Use value objects and intention-revealing methods.

  • Keep modules aligned to business capabilities (a modular monolith).

  • Skip heavy patterns (CQRS, event sourcing, many contexts) unless the domain demands them.

Large Organisations

  • Context maps across teams and systems, kept current.

  • Team boundaries aligned with bounded contexts (team topologies).

  • Published languages and versioned contracts between contexts.

  • Domain architects or communities of practice to share modelling skills.

Interview Tip

Walk through the scales (enterprise subdomains, system contexts and maps, team languages and models, and code-level tactical patterns), give an example at each, and stress matching DDD depth to subdomain value. Mentioning that small projects can use just the lightweight practices shows pragmatism.

32

How does DDD help understand and align complex organisational structures?

DDD helps with organisational complexity because software boundaries and team boundaries influence each other (Conway’s law: systems mirror the communication structures of the organisations that build them). Strategic design makes this explicit. Subdomains reveal which business capabilities matter most, bounded contexts give each team clear ownership of a model and its language, and context maps show upstream and downstream dependencies, power relationships and coordination needs between teams. Using these tools, you can align teams to bounded contexts, choose integration patterns that match how teams actually work together, and spot organisational friction, such as one model owned by three departments.

Read full answer

Applies tomulti-team product organisations, enterprise IT, platform teams, and team topology design

How DDD Concepts Map to Organisation

DDD concept Organisational meaning
Subdomain (core, supporting, generic) Where to put the strongest teams and investment
Bounded context A unit of ownership: ideally one team per context
Ubiquitous language Shared vocabulary between a team and its business stakeholders
Context map patterns Team relationships: partnership, customer-supplier, conformist
Anti-corruption layer A team protecting itself from another team’s or vendor’s model
Shared kernel Two teams agreeing to co-own a small piece
Separate ways Teams deciding integration is not worth it

Context-Map Patterns as Team Relationships

Pattern What it says about the teams
Partnership Teams succeed or fail together and plan jointly
Customer-supplier Downstream needs feed the upstream team’s backlog
Conformist Downstream has no influence and adopts the upstream model
Open host service Upstream serves many consumers with a stable API
ACL Downstream cannot rely on upstream’s model quality or stability

A map full of conformist relationships around a core domain signals a power or priority problem that needs management attention, not just technical work.

Using DDD to Align Teams

  1. Run Event Storming with several departments to see how work actually flows and where language changes.

  2. Identify bounded contexts from language and capability shifts.

  3. Assign clear ownership: one team per context (a team may own several small ones).

  4. Draw the context map with team relationships, not just API calls.

  5. Adjust structure or boundaries where they conflict: either change the software boundary to match the team, or reorganise teams to match a better boundary (the “inverse Conway manoeuvre”).

  6. Define contracts (published languages, SLAs) between teams for each relationship.

Example

Consider a bank with one “Customer” team handling onboarding, credit checks and marketing preferences. Event Storming would typically reveal three languages: Onboarding (“applicant”, “KYC check”), Credit (“exposure”, “limit”), and Marketing (“consent”, “segment”). Splitting into three contexts with three teams:

  • Reduces cross-team meetings, since each team owns its own rules.

  • Makes dependencies explicit: Credit is downstream of Onboarding via an ApplicantVerified event.

  • Lets Marketing use a SaaS platform (generic) through an ACL.

Signals of Organisational Misalignment

Signal Possible cause
Endless meetings to agree on one data model Several contexts forced into one model
One team blocked by another for every change Missing customer-supplier agreement, or a wrong boundary
A context owned by nobody (or by everyone) Ownership gap
A team juggling unrelated languages Too many contexts for one team
Core domain team conforming to a legacy model Need for an ACL or investment in the upstream

Benefits

  • Clear ownership and autonomy for teams.

  • Better communication through explicit relationships and contracts.

  • Investment aligned to strategy (core domain gets the best people).

  • Faster delivery with fewer cross-team dependencies.

Interview Tip

Connect DDD to Conway’s law, explain how subdomains, bounded contexts and context-map patterns describe team ownership and relationships, and mention the inverse Conway manoeuvre. A short example of splitting one overloaded team along language boundaries makes the answer concrete.

33

How does DDD help build a pluggable component architecture?

DDD makes components pluggable by giving each one a clear boundary and a stable contract. Bounded contexts become modules with explicit public interfaces. Inside a context, the domain layer defines ports (repository interfaces, provider interfaces, policies) in its own language, and adapters in the infrastructure layer implement them (hexagonal, or ports and adapters, architecture). Because the domain depends only on these abstractions, you can plug in a different database, payment provider, pricing policy or notification channel without touching business rules. Domain events let new components subscribe to behaviour without the publisher knowing about them, and anti-corruption layers make external systems replaceable.

Read full answer

Applies tomodular monoliths, plugin-based products, multi-tenant SaaS with per-customer rules, and systems integrating swappable vendors

Sources of Pluggability

DDD element What becomes pluggable
Ports defined in the domain (repositories, gateways) Storage and external services
Policies and specifications Business rules per market, tenant or date
Domain events New reactions (loyalty, analytics, notifications)
Anti-corruption layers External vendors and legacy systems
Bounded contexts as modules Whole capabilities (swap a custom module for a SaaS product)
Published languages Any component that speaks the contract

Example: Swappable Payment Providers and Pricing Policies

from abc import ABC, abstractmethod

# --- domain layer: ports in the ubiquitous language ---
class PaymentGateway(ABC):
    @abstractmethod
    def charge(self, order_id, amount_cents) -> bool: ...

class PricingPolicy(ABC):
    @abstractmethod
    def total(self, subtotal_cents) -> int: ...

class Order:
    def __init__(self, order_id, subtotal_cents):
        self.order_id, self.subtotal_cents, self.status = order_id, subtotal_cents, "draft"

    def checkout(self, pricing: PricingPolicy, payments: PaymentGateway):
        total = pricing.total(self.subtotal_cents)
        if not payments.charge(self.order_id, total):
            raise ValueError("payment declined")
        self.status = "paid"
        return total

# --- infrastructure layer: adapters (plug-ins) ---
class FakeGateway(PaymentGateway):
    def charge(self, order_id, amount_cents): return True

class VendorGateway(PaymentGateway):     # would wrap a vendor SDK through an ACL
    def __init__(self): self.calls = []
    def charge(self, order_id, amount_cents):
        self.calls.append((order_id, amount_cents)); return True

class StandardPricing(PricingPolicy):
    def total(self, s): return s

class FestivalPricing(PricingPolicy):
    def total(self, s): return s * 80 // 100

# --- composition root: choose plug-ins per environment or tenant ---
print(Order("o-1", 10_000).checkout(StandardPricing(), FakeGateway()))   # 10000
gw = VendorGateway()
print(Order("o-2", 10_000).checkout(FestivalPricing(), gw), gw.calls)    # 8000 [('o-2', 8000)]

The Order aggregate never changes when a new gateway or pricing policy is added.

Event-Based Plug-ins

from collections import defaultdict

subscribers = defaultdict(list)
def on(event_type):
    def register(fn):
        subscribers[event_type].append(fn); return fn
    return register

def publish(event):
    return [fn(event) for fn in subscribers[event["type"]]]

@on("OrderPaid")
def award_points(e): return f"loyalty +{e['total'] // 100} points"

@on("OrderPaid")
def notify(e): return f"sms sent for {e['order_id']}"

print(publish({"type": "OrderPaid", "order_id": "o-2", "total": 8000}))
# ['loyalty +80 points', 'sms sent for o-2']

Removing or adding a subscriber module changes nothing in Ordering.

Rules for Clean Pluggability

  • Dependencies point inward: infrastructure depends on the domain, never the reverse.

  • Define interfaces in domain terms (PaymentGateway.charge), not vendor terms.

  • Keep plug-in selection in one composition root (dependency injection, configuration, feature flags).

  • Test with fakes: in-memory adapters make domain tests fast.

  • Version published contracts so external plug-ins keep working.

  • Enforce boundaries with tooling (ArchUnit, Spring Modulith, import-linter for Python).

Interview Tip

Explain that bounded contexts give module boundaries, domain-defined ports with infrastructure adapters make technology swappable, policies make rules swappable, and events let new components subscribe. A small example swapping payment gateways and pricing policies without changing the aggregate makes the point clearly.

34

How does DDD help manage consistency in distributed systems?

DDD reduces distributed-systems complexity by deciding where strong consistency is really needed. Aggregates mark the only places that must be immediately consistent, so each transaction stays inside one aggregate and one service’s database. Everything else is eventually consistent, connected by domain events published reliably (outbox) and handled idempotently. Bounded contexts keep models and data owned by one team or service, which avoids shared databases and distributed transactions. Sagas or process managers coordinate multi-step business processes with compensating actions, and context maps make the integration contracts explicit. The business itself is asked how stale or temporarily inconsistent data may be, which turns technical consistency choices into domain decisions.

Read full answer

Applies tomicroservices, multi-region systems, event-driven architectures and any system where data lives in more than one place

How DDD Tools Map to Consistency

DDD tool Consistency role
Aggregate Strong consistency boundary; one per transaction
Reference by ID Avoids cross-service object graphs and distributed locks
Domain events Propagate changes for eventual consistency
Outbox Atomically store state change and event
Idempotent handlers Safe with at-least-once delivery
Saga / process manager Multi-step consistency with compensation
Bounded context Single owner per model and data store
Ubiquitous language Makes pending and compensation states explicit (“payment pending”, “order cancelled due to stock”)

Example: Order, Payment and Stock

Business rule: “Do not ship an order unless it is paid and stock is reserved.”

Ordering: Order placed (status: pending)          -> OrderPlaced
Payments: authorise payment                        -> PaymentAuthorised | PaymentFailed
Inventory: reserve stock                           -> StockReserved | StockUnavailable
Ordering saga:
   PaymentAuthorised + StockReserved -> confirm order
   StockUnavailable -> void payment authorisation, cancel order
   PaymentFailed    -> release stock, cancel order
class OrderSaga:
    def __init__(self, order_id, send):
        self.order_id, self.send = order_id, send
        self.paid = self.reserved = False
        self.state = "pending"

    def handle(self, event):
        if self.state != "pending":
            return                                   # ignore late or duplicate events
        t = event["type"]
        if t == "PaymentAuthorised":
            self.paid = True
        elif t == "StockReserved":
            self.reserved = True
        elif t == "StockUnavailable":
            self.state = "cancelled"
            if self.paid:
                self.send({"type": "VoidAuthorisation", "order_id": self.order_id})
            self.send({"type": "CancelOrder", "order_id": self.order_id, "reason": "out of stock"})
        elif t == "PaymentFailed":
            self.state = "cancelled"
            if self.reserved:
                self.send({"type": "ReleaseStock", "order_id": self.order_id})
            self.send({"type": "CancelOrder", "order_id": self.order_id, "reason": "payment failed"})
        if self.paid and self.reserved and self.state == "pending":
            self.state = "confirmed"
            self.send({"type": "ConfirmOrder", "order_id": self.order_id})

sent = []
s = OrderSaga("o-1", sent.append)
for e in ["PaymentAuthorised", "StockUnavailable", "StockReserved"]:
    s.handle({"type": e})
print(s.state, [c["type"] for c in sent])   # cancelled ['VoidAuthorisation', 'CancelOrder']

Each step is a local transaction in one context; the saga gives an overall business outcome without a distributed transaction.

Asking the Business

Question Typical answer
Can the order show “pending” for a few seconds? Usually yes
What if stock runs out after payment? Refund or back-order, which becomes an explicit domain process
Must the loyalty balance update instantly? Usually no
Must account balances never go negative? Yes, so balance changes stay inside one account aggregate

These answers decide which rules become aggregate invariants (strong) and which become eventual processes.

Pitfalls DDD Helps Avoid

  • Distributed transactions (2PC) across services, which are fragile and slow.

  • Shared databases that couple services silently.

  • Large aggregates spanning services.

  • Hidden inconsistency: unmodelled intermediate states that confuse users and support teams.

Interview Tip

Explain that aggregates define the only strong consistency boundaries, events and sagas handle everything else, and bounded contexts give single ownership of data. Showing a saga with compensation and framing consistency as a business decision (“how stale can this be?”) demonstrates mature distributed design.

35

What challenges arise when implementing DDD in a large multidisciplinary team?

The main challenges are people and coordination, not code. Typical ones: limited access to domain experts, inconsistent language across business, product, design, QA and engineering, disagreement on bounded context boundaries, uneven DDD knowledge (some people see it as just “entities and repositories”), coordination overhead between teams sharing contexts, legacy constraints and shared databases, pressure for quick delivery that skips modelling, over-engineering by enthusiasts, and keeping documentation and context maps current. They are addressed with clear ownership per context, regular collaborative modelling, a living glossary, shared training, lightweight governance, and starting with the core domain.

Read full answer

Applies toorganisations with several teams and roles (product managers, designers, analysts, developers, QA, operations, domain experts) adopting DDD

Challenges and Mitigations

Challenge Symptoms Mitigations
Limited domain expert access Requirements arrive second-hand; models guess at rules Schedule regular modelling sessions; embed experts or product owners; record examples
Language drift between roles Designers, testers and developers use different terms Per-context glossary; use the terms in tickets, designs, tests and code
Boundary disagreements Endless debates; contexts that keep changing Event Storming with all roles; start coarse; review boundaries with data on change frequency
Uneven DDD knowledge Patterns misused; anaemic models Shared training, pairing, book clubs, example code, a community of practice
Cross-team coordination Teams blocked on each other One owner per context; context map with explicit relationships and contracts
Legacy and shared data Changes ripple unpredictably Anti-corruption layers, strangler migration, gradual data ownership
Delivery pressure Modelling skipped; quick hacks in the core Timebox modelling; focus DDD effort on the core domain only
Over-engineering CQRS and event sourcing everywhere Apply heavy patterns only where justified; architecture decision records
Documentation decay Context maps and glossaries out of date Keep them in the repository; review them in regular rituals
Distributed teams and time zones Fewer shared modelling sessions Remote whiteboards (Miro, Mural), recorded sessions, written decisions
Measuring value Hard to justify time spent modelling Track lead time, defect rates and rework in core areas

Making Collaboration Work Across Roles

Role Contribution
Domain experts Rules, exceptions, real examples
Product managers Priorities and which subdomains are core
Designers User journeys that reveal events and states
Developers Models, boundaries, technical constraints
QA Examples and edge cases as executable scenarios
Operations / support Real-world failure cases and states users get stuck in

Practices such as Event Storming, Domain Storytelling and Example Mapping give every role a shared, visual way to contribute.

Lightweight Governance

  • Context owners who approve changes to their model and contracts.

  • Architecture decision records for boundary and pattern choices.

  • Shared kernel rules: changes only by joint agreement.

  • Regular architecture syncs across teams, kept short and focused on the context map.

Signs It Is Working

  • Business and technical people use the same terms in meetings and code.

  • Most features change one context.

  • Fewer bugs caused by misunderstood rules.

  • New team members learn the domain from the model and tests.

Interview Tip

Focus on people challenges (expert access, language drift, boundary debates, skill gaps, coordination and delivery pressure) and pair each with a mitigation: clear ownership, collaborative modelling, a living glossary, training and lightweight governance. Mentioning Event Storming as the tool that brings every role together shows practical experience.

36

What are common pitfalls when moving an existing project to DDD?

Common pitfalls when adopting DDD in an existing project: treating DDD as a set of code patterns (repositories and entities everywhere) while ignoring strategic design and the ubiquitous language; attempting a big-bang rewrite; applying DDD to every part of the system instead of the core domain; drawing bounded contexts along technical layers or database tables; creating anaemic domain models with logic left in services; designing aggregates that are too large; sharing one database across new contexts; skipping domain experts; over-using CQRS and event sourcing; and not protecting the new model from legacy concepts with anti-corruption layers. Avoid them by starting small, focusing on value, and changing incrementally.

Read full answer

Applies toteams introducing DDD into existing monoliths, legacy systems or microservice estates

Pitfalls and Remedies

Pitfall Why it hurts Remedy
Tactical patterns only (“DDD-lite”) Classes renamed, nothing understood better Start with language, subdomains and contexts
Big-bang rewrite Long delays, hidden rules lost, high risk Strangler fig: move one capability at a time
DDD everywhere Effort wasted on generic or CRUD areas Full DDD for the core; simple approaches elsewhere
Technical or table-based boundaries Contexts that do not match business language Find boundaries through Event Storming and language shifts
Anaemic domain model Rules stay scattered in services Move behaviour into aggregates, value objects and policies
Huge aggregates Slow loads, lock contention Design around invariants; reference by ID
Shared database between contexts Hidden coupling; no real boundaries Separate schemas, ownership, and integration through events or APIs
No domain expert involvement Model reflects developers’ guesses Regular modelling sessions with experts
CQRS and event sourcing by default Complexity without benefit Use them only where history or read scale justifies it
Legacy concepts leaking into the new model New code inherits old confusion Anti-corruption layers
No tests before refactoring Behaviour accidentally changed Characterisation tests and parallel runs
Ignoring team structure Boundaries clash with how teams work Align contexts and team ownership
Pattern jargon with the business Experts disengage Talk in business terms, not “aggregate roots”

Example: Anaemic Model Before and After

# Before: data holder plus a service with all the rules
class OrderData:
    def __init__(self): self.status, self.lines = "draft", []

def add_line_service(order, sku, qty):
    if order.status == "draft" and qty > 0:
        order.lines.append((sku, qty))

# After: behaviour lives with the data it protects
class Order:
    def __init__(self): self.status, self._lines = "draft", []
    def add_line(self, sku, qty):
        if self.status != "draft":
            raise ValueError("placed orders cannot change")
        if qty <= 0:
            raise ValueError("quantity must be positive")
        self._lines.append((sku, qty))
    @property
    def lines(self): return tuple(self._lines)

legacy = OrderData(); add_line_service(legacy, "p-1", 0)   # silently ignored: the bug hides
o = Order()
try:
    o.add_line("p-1", 0)
except ValueError as e:
    print(len(legacy.lines), e)                            # 0 quantity must be positive

The old service silently ignored invalid input; the domain model makes the rule explicit and visible.

A Safer Transition Path

  1. Pick one valuable, painful area in the core domain.

  2. Run Event Storming with experts to learn the language and events.

  3. Add characterisation tests around existing behaviour.

  4. Create a bounded context module with its own model and schema.

  5. Connect through an anti-corruption layer to the legacy code.

  6. Move behaviour gradually, validating with tests or parallel runs.

  7. Review and adjust boundaries as understanding grows.

  8. Share results (fewer defects, faster changes) to build support.

Interview Tip

List the pitfalls (patterns without strategy, big-bang rewrites, DDD everywhere, technical boundaries, anaemic models, large aggregates, shared databases, no experts, CQRS and event sourcing by default) with a remedy for each, then outline an incremental transition path. That combination of diagnosis and plan is what interviewers look for.

37

How do you measure the success of a DDD implementation?

Measure DDD by business and delivery outcomes, not by how many patterns appear in the code. Useful signals: faster and safer change in the core domain (lead time, deployment frequency, change failure rate), fewer defects caused by misunderstood rules, changes staying inside one bounded context (low cross-context coupling), less coordination between teams, a shared language visible in code, tickets and conversations, quicker onboarding, and business stakeholder satisfaction with how well the software matches reality. Combine quantitative metrics with qualitative feedback, and compare before and after in the areas where DDD was applied.

Read full answer

Applies toengineering leadership reviews, architecture retrospectives and justifying DDD investment

Metrics

Area Metric What improvement looks like
Delivery speed Lead time for changes in core contexts Shorter over time
Stability Change failure rate, incidents linked to domain logic Lower
Quality Defects caused by wrong business rules Fewer; caught earlier by domain tests
Modularity Share of changes touching only one context High (for example most PRs stay in one context)
Coupling Cross-context synchronous calls; shared tables Decreasing
Team autonomy Cross-team dependencies per feature; waiting time Lower
Language alignment Glossary terms used in code and tickets Consistent naming; fewer “what does X mean” questions
Onboarding Time for a new developer to deliver in a context Shorter
Business fit Expert and stakeholder satisfaction surveys Higher; fewer rework requests
Rework Features reopened due to misunderstood requirements Lower

Measuring Context Isolation From Version Control

from collections import Counter

# Each commit lists files changed; contexts are top-level folders like ordering/, pricing/
commits = [
    ["ordering/order.py", "ordering/tests/test_order.py"],
    ["pricing/policy.py"],
    ["ordering/order.py", "shipping/shipment.py"],
    ["shipping/acl/warehouse.py", "shipping/tests/test_acl.py"],
]

def contexts(files):
    return {f.split("/")[0] for f in files}

spread = Counter(len(contexts(c)) for c in commits)
single = spread[1] / len(commits)
print(dict(spread), f"{single:.0%} of commits touch one context")
# {1: 3, 2: 1} 75% of commits touch one context

Tracking this over time shows whether boundaries are working: a falling share means features keep cutting across contexts.

Qualitative Signals

  • Domain experts can read tests or key model code and confirm the rules.

  • Meetings use the glossary terms without translation.

  • Fewer debates about where code belongs.

  • Developers explain the domain confidently, and design discussions reference the context map.

  • Context maps and glossaries stay current, because people actually use them.

Using the Measures Well

  • Set a baseline before adopting DDD in an area.

  • Compare the core domain (where DDD was applied) with other areas.

  • Look at trends, not single numbers; many factors affect delivery.

  • Combine with DORA metrics (lead time, deployment frequency, change failure rate, time to restore).

  • Avoid vanity metrics such as the number of aggregates or events.

Warning Signs

Sign Possible problem
Most features change several contexts Boundaries are wrong
Rule-related bugs not decreasing Model does not capture rules; experts not involved
Heavy ceremony, slower delivery Over-engineering; DDD applied where it is not needed
Glossary ignored Ubiquitous language never really adopted

Interview Tip

Say that success is measured by outcomes: faster, safer change, fewer rule-related defects, changes isolated to one context, less cross-team coordination and better business alignment. Mentioning a concrete measure such as the share of commits touching one context, plus DORA metrics and qualitative expert feedback, shows a thoughtful approach.

38

Which tools and frameworks support DDD, and why?

DDD is a way of thinking, not a framework, but several tools make it easier. Collaborative modelling tools (Event Storming on physical or online whiteboards such as Miro and Mural, Domain Storytelling with Egon.io, Context Mapper for describing contexts in a DSL) help discover the domain. Frameworks support tactical patterns and messaging: Axon Framework (Java, CQRS and event sourcing), Spring Modulith and jMolecules (module boundaries and DDD annotations on the JVM), Marten, Wolverine, MediatR and NServiceBus (.NET), the eventsourcing library for Python, and event stores such as EventStoreDB. Architecture testing tools (ArchUnit, import-linter) enforce boundaries, and workflow engines (Temporal, Camunda) run sagas. Choose tools that serve the model; none of them replace talking to domain experts.

Read full answer

Applies toteams practising DDD in Java, Kotlin, C#, Python, TypeScript and Go

Modelling and Discovery

Tool Use
Event Storming (sticky notes, Miro, Mural) Discover events, commands, aggregates, policies and context boundaries
Domain Storytelling (Egon.io) Capture workflows as pictographic stories in domain language
Example Mapping Turn rules into concrete examples and tests
Context Mapper DSL and tooling for context maps; can generate diagrams
C4 model, Structurizr Document architecture at context and container levels

Framework and Library Support

Ecosystem Tools Why they help
Java / Kotlin Axon Framework, Spring Modulith, jMolecules, Spring Data Aggregates, commands, events, event sourcing; verified module boundaries
.NET Marten, Wolverine, MediatR, NServiceBus, MassTransit, EF Core owned types Event sourcing on PostgreSQL, command handling, messaging and sagas, value object mapping
Python eventsourcing, SQLAlchemy (imperative mapping), pydantic or dataclasses Event-sourced aggregates; persistence-ignorant domain models; value objects
Node.js / TypeScript NestJS CQRS module, Emmett Command and query buses, event sourcing
Event stores EventStoreDB, Marten, Axon Server, PostgreSQL tables Append-only streams with optimistic concurrency
Messaging Kafka, RabbitMQ, cloud queues; Debezium for outbox and CDC Reliable integration events between contexts
Workflows and sagas Temporal, Camunda, AWS Step Functions Long-running processes with compensation

Enforcing Boundaries

# import-linter configuration (setup.cfg or .importlinter) for a Python modular monolith
contract = """
[importlinter]
root_package = shop

[importlinter:contract:contexts-independent]
name = Bounded contexts must not import each other's internals
type = independence
modules =
    shop.ordering
    shop.pricing
    shop.shipping
"""
print(contract.count("shop."))   # 3  (three contexts checked)

The same idea on the JVM uses ArchUnit rules or Spring Modulith’s ApplicationModules.of(...).verify(), which fail the build when one module reaches into another’s internals.

Testing Support

  • Behaviour-driven tests (pytest with clear Given/When/Then names, Cucumber or SpecFlow) written in the ubiquitous language.

  • Aggregate test fixtures in Axon and similar frameworks: given past events, when a command arrives, then expect new events.

  • Contract testing (Pact) for published languages between contexts.

Choosing Tools Wisely

  • Prefer plain code for the domain model; frameworks should stay at the edges.

  • Avoid framework lock-in in the core: annotations are fine if they do not distort the model.

  • Adopt event sourcing and CQRS frameworks only where those patterns are justified.

  • Use boundary enforcement early; it is cheap and prevents erosion.

Interview Tip

Group tools by purpose (discovery, tactical frameworks, event stores and messaging, boundary enforcement, workflows, testing), name a few per ecosystem, and explain why each helps. Stressing that the domain model should be plain code and that no tool replaces collaboration with experts shows good judgement.

39

How do you train and transfer DDD knowledge to a team new to it?

Teach DDD by doing it on the team’s own domain, not only through theory. Start with a short shared introduction to the core ideas (ubiquitous language, bounded contexts, aggregates), then run hands-on Event Storming with domain experts on a real problem. Next, model and build a small, real slice together through pairing or mob programming, guided by someone experienced. Support it with reading groups (Evans, Vernon’s Implementing Domain-Driven Design and Domain-Driven Design Distilled, Learning Domain-Driven Design by Vlad Khononov), reference examples in the codebase, a living glossary, architecture decision records, and a community of practice. Emphasise strategic thinking first, introduce tactical patterns gradually, and avoid heavy patterns until they are needed.

Read full answer

Applies toengineering teams, product managers, analysts and QA engineers adopting DDD, onboarding new hires into DDD codebases

A Practical Learning Plan

Phase Activities Outcome
1. Foundations (1 to 2 sessions) Short talk on why DDD, core vs generic subdomains, bounded contexts, ubiquitous language Shared vocabulary for DDD itself
2. Discovery workshop Big-picture Event Storming on the team’s real domain with experts Events, language and candidate contexts
3. Design-level modelling Event Storming at aggregate level for one context Aggregates, commands, policies, invariants
4. Build a slice Pair or mob program the first aggregate, tests and repository Working reference implementation
5. Review and refine Code reviews focused on language and invariants; retros Patterns understood in context
6. Expand Context map, integration patterns, events, ACLs Strategic skills
7. Sustain Book club, community of practice, internal talks, glossary maintenance Knowledge spreads and stays current

Roles Need Different Depth

Role Focus
Developers Strategic and tactical design, modelling in code, testing
Product managers and analysts Subdomains, ubiquitous language, Event Storming facilitation
QA Examples and scenarios in domain terms, invariants as test cases
Domain experts Short intro; mainly participating in modelling sessions
Architects and leads Context maps, team alignment, governance

Reference Material in the Codebase

A small, well-commented example helps more than slides:

# ordering/domain/order.py  (reference aggregate for the team)
class Order:
    """Aggregate root. Invariant: a placed order's lines never change."""

    def __init__(self, order_id, customer_id):
        self.order_id, self.customer_id = order_id, customer_id   # other aggregate by ID
        self._lines, self.status = [], "draft"

    def add_line(self, sku, qty, unit_price_cents):
        if self.status != "draft":
            raise ValueError("placed orders cannot change")
        self._lines.append((sku, qty, unit_price_cents))

    def place(self):
        if not self._lines:
            raise ValueError("an order needs at least one line")
        self.status = "placed"
        return {"type": "OrderPlaced", "order_id": self.order_id}   # domain event

def test_placed_order_cannot_change():          # test named in the ubiquitous language
    order = Order("o-1", "c-1")
    order.add_line("p-1", 1, 499)
    order.place()
    try:
        order.add_line("p-2", 1, 99)
        assert False, "expected rejection"
    except ValueError:
        pass

test_placed_order_cannot_change()
print("reference example passes")   # reference example passes

Knowledge Transfer Practices

  • Pairing and mob programming on domain code.

  • Modelling reviews where experts check the language and rules.

  • Glossary and context map stored in the repository and reviewed regularly.

  • ADRs explaining why boundaries and patterns were chosen.

  • Internal guild or community of practice with monthly sessions.

  • Rotation of developers across contexts to spread understanding.

Common Mistakes When Teaching DDD

  • Starting with tactical patterns and jargon, so people think DDD equals repositories and entities.

  • Only theory, with no practice on the real domain.

  • Introducing CQRS and event sourcing too early.

  • Leaving domain experts out of the learning process.

  • No follow-up: one workshop, then old habits return.

Interview Tip

Describe learning by doing: a short foundation, Event Storming on the real domain, then building a reference slice with pairing, supported by books, a glossary, ADRs and a community of practice. Stressing strategy before tactics and tailoring depth by role shows experience leading teams.

40

What kind of project shows clear benefits of DDD over other approaches?

DDD shows clear benefits in projects with complex, changing business rules, several groups of experts using different language, and a long lifespan. The classic illustration is the cargo shipping example in Eric Evans’s book (also published as the open-source DDD Sample application). There, a cargo booking and routing system becomes manageable once the team models concepts such as Cargo, Itinerary, Leg, HandlingEvent and RouteSpecification, separates booking, routing and tracking, and keeps rules in the model rather than in procedural services. The same pattern of benefit appears in insurance claims, lending, ordering and pricing, logistics and healthcare scheduling: fewer misunderstandings, rules that are easier to change, and teams that can work independently.

Read full answer

Applies todeciding when DDD is worth it, and explaining its value in interviews using a concrete scenario

The Cargo Example (Evans)

Problem without DDD DDD solution
“Route” meant different things to booking clerks and operations Ubiquitous language: RouteSpecification (what the customer needs: origin, destination, deadline) vs Itinerary (the actual planned legs)
Rerouting logic scattered across screens Cargo aggregate checks whether its itinerary still satisfies its route specification
Tracking mixed into booking code HandlingEvents (load, unload, customs) recorded separately; cargo status derived from them
Routing algorithm tangled with domain rules Routing as an external service behind an interface
from dataclasses import dataclass

@dataclass(frozen=True)
class RouteSpecification:              # what the customer asked for
    origin: str
    destination: str
    deadline_day: int
    def is_satisfied_by(self, itinerary):
        return (itinerary.legs[0].load == self.origin and
                itinerary.legs[-1].unload == self.destination and
                itinerary.legs[-1].arrive_day <= self.deadline_day)

@dataclass(frozen=True)
class Leg:
    load: str
    unload: str
    arrive_day: int

@dataclass(frozen=True)
class Itinerary:                       # how we plan to move it
    legs: tuple

class Cargo:
    def __init__(self, tracking_id, spec):
        self.tracking_id, self.spec, self.itinerary = tracking_id, spec, None
    def assign_route(self, itinerary):
        self.itinerary = itinerary
    def misrouted(self):
        return self.itinerary is not None and not self.spec.is_satisfied_by(self.itinerary)

cargo = Cargo("ABC123", RouteSpecification("Mumbai", "Rotterdam", deadline_day=20))
cargo.assign_route(Itinerary((Leg("Mumbai", "Dubai", 4), Leg("Dubai", "Rotterdam", 18))))
print(cargo.misrouted())                               # False
cargo.spec = RouteSpecification("Mumbai", "Hamburg", 20)   # customer changes destination
print(cargo.misrouted())                               # True: rerouting needed

The question operations staff actually ask, “is this cargo misrouted?”, is answered directly by the model.

A Typical Modern Scenario: E-Commerce Pricing

Consider an online retailer whose prices depend on customer tier, campaigns, bundles, regional tax and marketplace sellers:

Before (CRUD plus services) After (DDD)
Discount if chains in checkout, cart and invoices PricingPolicy and promotion specifications in a Pricing context
“Price” meant list price, sale price and invoiced amount Language split: ListPrice (Catalogue), Quote (Pricing), AgreedPrice (Ordering)
Every campaign required changes across several services New campaign = new policy configuration in one context
Disputes about historical prices Orders store the agreed price and policy version

Typical results teams report in such cases are fewer pricing defects, faster campaign launches and clear ownership, because changes stay in one bounded context.

Why DDD Beat the Alternatives in These Cases

  • Complex rules became explicit objects that experts could review.

  • Different meanings were separated into bounded contexts instead of compromised into one model.

  • Change was localised: new rules plugged into policies or specifications.

  • Integration was deliberate through events and anti-corruption layers.

When DDD Would Not Show Clear Benefits

  • A simple CRUD back office or content site.

  • A short-lived prototype.

  • A data pipeline with little business logic.

Interview Tip

Use a concrete scenario, ideally Evans’s cargo example or a pricing domain, to show the problem (ambiguous language, scattered rules) and how DDD solved it (ubiquitous language, aggregates, specifications, bounded contexts). If you describe your own project, be specific about the before and after, and acknowledge when DDD would have been overkill.

Sign in to keep reading

You've opened 2 full answers. Sign in to read all 40 Domain Driven Design answers, mark what you know and pick up where you left off.

Report a mistake

What's wrong?

All System Design subjects