Domain-Driven Design (DDD) & Clean Architecture Master Interview Bank
Strategic DDD (Bounded Contexts, Ubiquitous Language), Tactical DDD (Aggregates, Aggregate Roots, Entities, Value Objects, Domain Events), and Hexagonal Architecture.
Curriculum Roadmap & Learning Path
3 StagesPart 1: Basic & Foundational Concepts (Junior / Entry-Level)
10 QuestionsWhat is Domain-Driven Design (DDD) and what problem does it solve?
Domain-Driven Design (introduced by Eric Evans) is an approach to software development that centers the entire system design around a deep, evolving model of the core business problem (The Domain): Problem It Solves: In large enterprise software, complexity is usually not in the technical framework (React, Spring, Docker); it is in the.
What is the difference between Strategic DDD and Tactical DDD?
Strategic DDD (The Big Picture - High-Level Architecture): Focuses on decomposing a large complex enterprise into clear subsystems • Ubiquitous Language, Bounded Contexts, Subdomains (Core, Supporting, Generic), and Context Maps • Determines microservice boundaries and team ownership.
What is the Ubiquitous Language and why is it essential?
A single, unambiguous, shared vocabulary created jointly by software developers and business domain experts: Rule: The exact same terminology used in business discussions must be used verbatim in requirements docs, user stories, class names, method.
What is a Bounded Context?
A linguistic and conceptual boundary within which a specific domain model and Ubiquitous Language applies strictly and consistently: In an enterprise e-commerce system, the word "Product" means completely different things to different teams • In Sales Context: A Product has a price, marketing copy, and photos.
What are the three types of Subdomains (Core, Supporting, Generic)?
Core Domain: The primary competitive advantage of your business • Supporting Subdomain: Complements the core business • Generic Subdomain: Universal business problems with zero competitive differentiation (e.g. Billing, Identity/Auth, Invoicing).
What is the difference between an Entity and a Value Object?
The most fundamental distinction in Tactical DDD: Entity: Defined by its persistent Identity (ID), not by its attributes • Value Object: Defined entirely by the combination of its attributes, with NO identity • Example: Money(amount: 50, currency: "USD") or Address(street, zip).
What is an Aggregate and an Aggregate Root?
Aggregate: A cluster of associated domain objects (Entities and Value Objects) treated as a single unit for data changes and transactional • Example: An Order (Aggregate Root) containing multiple OrderItem entities and a ShippingAddress value object.
What is a Domain Invariant?
A business rule that must be true at all times within an Aggregate's lifecycle: Examples • "The total cost of an Order cannot exceed the customer's credit limit." • "An order cannot have more than 50 items." • "A shipment cannot be created without at least one item.".
What is a Domain Service and when should you use it?
A stateless service that encapsulates business domain logic that naturally does not belong to any single Entity or Value Object: Use Case: Operations that involve multiple aggregates or external calculations (e.g. FundsTransferService.transfer(fromAccount, toAccount, amount)).
What is an Anemic Domain Model and why is it considered an Anti-Pattern?
An anemic model is where domain classes are just dumb property bags with public getters and setters (get/set), containing zero business logic: All validation, calculations, and invariants are pushed into bloated procedural service classes (OrderService).
Part 2: Core Architecture & Implementation (Mid-Level)
10 QuestionsWhat is a Domain Event and how does it represent business facts?
A record of something meaningful that has already happened in the domain in the past: Characteristics: Immutable, named in the past tense (OrderPlaced, PaymentReceived, UserRegistered) • Captures the exact point-in-time snapshot of the state change.
What is the difference between Domain Events, Integration Events, and Application Events?
Domain Event: Internal to a single Bounded Context • Integration Event: Published externally across network boundaries (via Kafka, RabbitMQ, EventBridge) to notify other Bounded Contexts (e.g • Application Event: Framework-level events (e.g. user logged in, HTTP request started, cache cleared).
What is the difference between Domain Services, Application Services, and Infrastructure Services?
Three distinct service layers in DDD architectures: Domain Service: Pure business logic that spans multiple aggregates (e.g. PricingEngineService) • Application Service: Orchestration layer (Use Cases).
What are Context Maps and the standard Context Relationships?
A Context Map visualizes the structural and political relationships between different Bounded Contexts in an enterprise: Shared Kernel: Two contexts share a common core domain model and database subset (requires tight coordination) • Customer / Supplier (Upstream / Downstream - U/D): Upstream (U) provides data; Downstream (D) consumes it.
How does the Anti-Corruption Layer (ACL) protect domain models?
When integrating with an external vendor or legacy system: Never let external terminology and bad data structures leak into your domain! • The ACL acts as a bidirectional translator • Takes raw external JSON/XML, parses it, validates it, and maps it into clean, strongly typed internal Domain Entities and Value Objects.
What is the Repository Pattern in DDD and what is its strict contract?
A Repository simulates an in-memory collection of Aggregate Roots: Rule 1: Only Aggregate Roots can have Repositories! • Rule 2: The repository interface lives in the Domain Layer, but its implementation lives in the Infrastructure Layer (DIP).
How should Aggregate boundaries be sized?
The #1 beginner mistake in DDD is creating massive, bloated aggregates (e.g. a Customer aggregate containing all historical orders, invoices, reviews, and tickets): Large aggregates cause severe database locking contention, high memory consumption, and transaction deadlocks! • Best Practice (Small Aggregates).
What is the difference between Immediate Consistency and Eventual Consistency in DDD?
Immediate (Strong) Consistency: Enforced strictly within the boundary of a single Aggregate using database ACID transactions • Eventual Consistency: Used across multiple Aggregates or across Bounded Contexts • When Aggregate A changes, it publishes a Domain Event • A background handler updates Aggregate B moments later.
How do Factories work in Domain-Driven Design?
When creating an Aggregate Root requires complex validation, default invariants, or assembly of nested value objects: Encapsulate the creation logic inside a dedicated Factory (method or class) • Guarantees that an entity can never exist in an invalid, half-initialized state.
What is Event Storming and how does it discover Bounded Contexts?
A rapid, collaborative workshop method that brings together developers and business domain experts around a large paper roll: Orange Sticky Notes (Domain Events): Participants write down all business events in past tense ("Order Placed", "Invoice Generated") • Blue Notes (Commands): What triggered the event?
Part 3: Advanced Architecture & Production Patterns (Senior / Lead)
30 QuestionsHow do you implement the Outbox Pattern with Domain Events in production?
To ensure Domain Events are never lost if the message broker is unreachable: When saving an Aggregate, the Repository extracts all uncommitted domain events recorded by the aggregate • In the same atomic database transaction, it writes the aggregate row AND inserts the events into an outbox table.
What is the SAGA Pattern (Choreography vs Orchestration) in DDD microservices?
Manages distributed business transactions across multiple Bounded Contexts without 2PC: Choreography: Event-driven • OrderService emits OrderCreated -> PaymentService listens and charges card -> emits PaymentCompleted -> InventoryService reserves stock • Simple for small workflows; difficult to track and debug as services scale.
What are Compensating Transactions in Sagas?
Because distributed transactions cannot execute a database ROLLBACK across independent microservices, Sagas use compensating actions: A compensating transaction is an explicit business operation that semantically reverses a prior committed action • Original action: CreditCardCharged (100) -> Compensating action: RefundIssued (100).
What is CQRS (Command Query Responsibility Segregation) in DDD?
Splits the application into two independent models: Write Side (Commands): Uses Tactical DDD • Read Side (Queries): Bypasses domain aggregates and repositories completely! • Allows scaling read performance independently (e.g. 100,000 queries/sec on read replicas) without burdening transactional write aggregates.
What is Event Sourcing and how does it integrate with DDD Aggregates?
In an Event-Sourced aggregate, the state of the entity is reconstructed dynamically by replaying its domain events: The database stores an events stream table: (aggregateid, version, eventtype, payload) • When loading an aggregate • Fetch all events where aggregate_id = 'ORD-101' ordered by version • Instantiate an empty Order object.
How do you model Complex Business Rules using the Specification Pattern?
Encapsulates a business rule or validation predicate into an independent, reusable boolean specification object: Allows chaining specifications using boolean logic (and, or, not).
How do you handle Concurrency and Race Conditions on Aggregate Roots?
Use Optimistic Concurrency Control (OCC): Store a version integer on the Aggregate Root • When committing updates via the repository • If another concurrent request already updated the aggregate (version is already 4), the update affects 0 rows.
What is the Open Host Service (OHS) and Published Language (PL)?
When an Upstream Bounded Context must serve multiple Downstream consumer teams: Instead of building custom custom integrations for each client • Open Host Service (OHS): Upstream exposes a stable, documented public subsystem (REST API, gRPC service).
What is the Separate Ways pattern in Strategic DDD?
When the coordination, political overhead, and network integration cost between two teams exceeds the benefit of software integration: Both teams deliberately choose to go their separate ways and build independent solutions tailored to their specific needs.
How do you model Temporal / Time-Series data in DDD?
Time is an explicit first-class citizen in business domains: Never store just a mutable status without context • Use explicit Date Range Value Objects: DateRange(start: Date, end: Date) with intersection and overlap methods (rangeA.overlaps(rangeB)).
What is the Customer / Supplier relationship in Context Mapping?
An Upstream (Supplier) / Downstream (Customer) relationship where the Upstream team's priorities are directly driven by Downstream needs: Downstream team submits feature requests and requirements • Upstream team plans and prioritizes their sprint backlogs to satisfy Downstream deliverables.
How do you implement Idempotency in Domain Event Consumers?
Message brokers (Kafka, RabbitMQ) provide at-least-once delivery, meaning event handlers will occasionally receive the exact same event multiple times: Idempotent Consumer Pattern • Consumer inspects incoming eventId (UUID) • Queries a local processed_events database table • If eventId exists -> Acknowledge and discard immediately!.
What is the difference between Domain Exceptions and Technical Exceptions?
Technical Exceptions: Unexpected infrastructure failures (network timeout, database connection dropped, disk full) • Domain Exceptions: Expected business invariant violations (e.g. InsufficientFundsException, ProductOutOfStockException, OrderAlreadyShippedException).
How do you prevent Microservices from becoming a "Distributed Monolith" using DDD?
A distributed monolith happens when microservices are cut along technical layers (UI service, Logic service, Database service) or share database tables: DDD Solution • Cut microservices strictly along Bounded Context boundaries • Shared Nothing: Each microservice owns its private database.
When is Domain-Driven Design (DDD) an Anti-Pattern?
Applying full Tactical DDD to simple software: Simple CRUD applications: If an app simply reads and writes forms to database tables with minimal business rules, applying Aggregates • Short-lived throwaway prototypes / MVPs: Focus on product-market fit first before investing in deep domain models.
Ubiquitous Language in Practice: Resolving linguistic ambiguity across departments.
In large enterprises, different departments use the same word with completely different meanings: To Sales, an Account is a sales prospect with a budget and contract negotiations • To Engineering / Security, an Account is a login username, password hash, and permission roles.
Subdomains Classification: Core Domain vs Supporting vs Generic Subdomains.
Prioritizing engineering talent and budget: Core Domain: The unique secret sauce that provides competitive advantage and differentiates your business from competitors (e.g., Netflix.
Event Storming Workshop Methodology: Rapid domain discovery.
A collaborative, rapid modeling workshop uniting domain business experts with software engineers using colored sticky notes: Domain Events (Orange Sticky Notes): Written in past tense (OrderPlaced, InvoicePaid, AccountSuspended) arranged chronologically on a wall.
Context Mapping Patterns: Relationships between Bounded Contexts.
How different teams and systems integrate across context boundaries: Shared Kernel: Two teams share a small common subset of code and database tables • Partnership: Two teams succeed or fail together; features are planned jointly • Customer-Supplier: Upstream (Supplier) builds what Downstream (Customer) requires.
The 4 Aggregate Design Rules by Vaughn Vernon.
Essential guidelines for high-performance, maintainable Aggregates: Rule 1: Model True Business Invariants: An aggregate boundary should encapsulate only data that must be strictly consistent within a single • Rule 2: Design Small Aggregates: Large aggregates cause severe optimistic locking conflicts and memory bloat.
Entity vs Value Object Deep Dive.
Dimension Entity Value Object.
Domain Services vs Application Services.
Domain Service: Holds pure business logic that does not naturally belong to a single Entity or spans multiple Aggregate Roots (e.g • Application Service (Use Case Orchestrator): The outer boundary coordinator • Opens database transaction • Loads Aggregate from Repository.
Domain Events Lifecycle: Internal emission vs Outbox publishing.
How events travel from aggregate mutations to external message brokers: Emitted Inside Aggregate: Calling order.cancel("Customer request") records an internal event in an uncommitted in-memory list.
Anti-Corruption Layer (ACL) Architecture: Facade, Adapter, and Translator.
When your clean modern domain must communicate with a 20-year-old legacy SOAP mainframe: Never let the legacy system's confusing abbreviations (CUSTMSTRREC_01) leak into your clean domain model! • The ACL Trio • Facade: Simplifies the messy legacy API into a manageable interface.
Modeling Invariants: Eliminating public setters in Aggregate Roots.
Anemic Domain Anti-Pattern: Entities full of getters and public setters (order.setStatus("PAID"), order.setDiscount(0.2)) • Rich Domain Model: Private setters.
CQRS and Event Sourcing in DDD: State reconstruction and projections.
Event-Sourced Aggregate: Has zero internal update statements.
Factory Pattern in DDD: Enforcing invariants during object creation.
When creating an Aggregate Root requires complex business validation, loading child entities, or establishing initial invariants: Direct instantiation via new Order() can lead to partially configured or invalid domain objects • Domain Factory: Encapsulates atomic creation.
Integrating Legacy Systems: Bubble Contexts and Autonomous Bubbles.
When replacing a legacy system in phases: Bubble Context: A clean, isolated island of new development carved out inside or alongside the legacy architecture • Communicates with the legacy system strictly through an Anti-Corruption Layer (ACL).
Testing in DDD: Unit testing Domain Entities in pure isolation.
Because true Tactical DDD models have zero dependencies on databases, ORMs, frameworks, or networks: Domain unit tests execute in microseconds.
Socio-Technical Architecture: Aligning Team Topologies with Bounded Contexts.
Conway's Law states: "Organizations design systems that mirror their own communication structures": If 3 separate teams work inside a single shared Bounded Context, they will suffer from constant merge conflicts, blocked deployments, and • Socio-Technical Alignment (Team Topologies).