FullStack Engineering CourseLesson 8 of 20 15 min
Architecture Styles: DDD, Clean Architecture and Microservices
What architecture decides
Architecture is the set of decisions that are expensive to change later: how the system is split into parts, how the parts talk to each other, where data lives, and which way dependencies point. Good architecture keeps the cost of change low as the system and the team grow. This lesson covers the main styles for structuring .NET systems:
- Domain-driven design (DDD): how to model the business and where to draw boundaries.
- Clean and hexagonal architecture: how to structure the code inside one service.
- Monoliths, modular monoliths and microservices: how to split a system into deployable units.
- Backend-for-Frontend (BFF) and micro-frontends: how front ends fit in.
Domain-driven design: the strategic part
Domain-driven design is an approach where the code is shaped around the business domain (the area of business the software serves), worked out together with domain experts. Its strategic part is about boundaries:
- Ubiquitous language: developers and domain experts use the same words for the same things, in conversation and in code. If billing staff say "remittance", the code has a Remittance class, not PaymentResponseDto.
- Subdomains: the business splits into areas. In healthcare revenue cycle management these might be patient registration, eligibility, claims, payments and denials. The core subdomain is where the business competes (for example, denial prediction); supporting and generic subdomains (user management, email) can be simpler or bought.
- Bounded contexts: a boundary inside which one model and one language apply. The word "claim" can mean different things in Claims (a bill being prepared) and Payments (an amount owed). Each context keeps its own model, rather than one huge shared Claim class that serves everyone badly.
- Context map: a picture of the bounded contexts and how they relate: who calls whom, who adapts to whom, and where an anti-corruption layer (lesson 10) protects one model from another.
Bounded contexts are the most useful idea in DDD for architecture. They are natural boundaries for modules, teams and, when needed, microservices.
Domain-driven design: the tactical part
Inside a bounded context, DDD offers building blocks for the domain model:
| Building block | What it is | Example |
|---|---|---|
| Entity | An object with an identity that stays the same as its data changes | Claim 42, still the same claim after its amount changes |
| Value object | An object defined only by its values, with no identity, and usually immutable | Money(1200, "INR"), DateRange, Address |
| Aggregate | A cluster of objects changed together as one unit, with one entry point (the aggregate root) that enforces the rules | Claim (root) with its ClaimLines |
| Domain event | A record that something important happened in the domain | ClaimSubmitted, ClaimDenied |
| Repository | Loads and saves whole aggregates, hiding the database | IClaimRepository |
| Domain service | Domain logic that does not belong to one entity | A pricing calculation that needs several aggregates |
The aggregate is the key idea. Its root is the only way to change anything inside it, so it can protect the business rules (invariants: conditions that must always be true). Outside code cannot add a line to a submitted claim, because the only way in is the root's methods:
public sealed record Money(decimal Amount, string Currency) // value object
{
public static Money Zero(string currency) => new(0m, currency);
public Money Add(Money other) =>
other.Currency == Currency ? this with { Amount = Amount + other.Amount }
: throw new InvalidOperationException("Currencies differ.");
}
public sealed class Claim // aggregate root
{
private readonly List<ClaimLine> _lines = [];
private readonly List<object> _events = [];
public ClaimId Id { get; }
public ClaimStatus Status { get; private set; } = ClaimStatus.Draft;
public IReadOnlyList<ClaimLine> Lines => _lines; // read-only from outside
public IReadOnlyList<object> DomainEvents => _events;
public Claim(ClaimId id) => Id = id;
public Money Total => _lines.Aggregate(Money.Zero("INR"), (sum, line) => sum.Add(line.Charge));
public void AddLine(string procedureCode, Money charge)
{
if (Status != ClaimStatus.Draft)
throw new DomainException("Lines can only be added to a draft claim."); // invariant
_lines.Add(new ClaimLine(procedureCode, charge));
}
public void Submit()
{
if (_lines.Count == 0) throw new DomainException("A claim needs at least one line.");
Status = ClaimStatus.Submitted;
_events.Add(new ClaimSubmitted(Id, Total)); // other parts of the system react to this
}
}Rules of thumb for aggregates:
- Keep them small. Big aggregates mean big transactions and more concurrency conflicts.
- Change one aggregate per transaction. When a change in one aggregate should cause a change in another, publish a domain event and handle it separately.
- Refer to other aggregates by ID (ClaimId, PatientId), not by object reference.
DDD has a cost. For simple CRUD screens (create, read, update and delete with little logic), a rich domain model is unnecessary ceremony. Use the tactical patterns where the business rules are complex, typically in the core subdomain.
Clean and hexagonal architecture
Clean architecture, hexagonal architecture (also called ports and adapters) and onion architecture are variations of one idea: the business logic sits in the centre and depends on nothing technical. Databases, web frameworks, message brokers and external APIs sit at the edge and depend on the centre. This is dependency inversion (lesson 3) applied to a whole project.
- Domain: entities, value objects, aggregates, domain events and business rules. No references to EF Core, ASP.NET Core or any infrastructure.
- Application: use cases (SubmitClaim, ApproveClaim). It coordinates the domain and defines the interfaces it needs, called ports (IClaimRepository, IPayerGateway, IClock).
- Infrastructure: adapters that implement the ports: EF Core repositories, HTTP clients, Service Bus publishers.
- Presentation (or API): controllers or minimal API endpoints that turn HTTP into use-case calls.
src/
Claims.Domain/ Claim, ClaimLine, Money, ClaimSubmitted, DomainException (references nothing)
Claims.Application/ SubmitClaimHandler, IClaimRepository, IPayerGateway (references Domain)
Claims.Infrastructure/ SqlClaimRepository (EF Core), PayerApiGateway (HttpClient) (references Application)
Claims.Api/ endpoints, Program.cs: wires everything together (references all)The project references enforce the dependency rule: Claims.Domain cannot use EF Core because it has no reference to it. The benefits:
- Business rules can be unit tested without a database or a web server.
- Infrastructure can change (SQL Server to PostgreSQL, one payer API to another) without touching the business logic.
- The business logic is easy to find, instead of being spread across controllers and repositories.
The costs are more projects, more interfaces and more mapping between layers. For a small service, a single project with folders that follow the same rule is often enough.
Vertical slice architecture is a popular alternative. Instead of organising code by technical layer, it organises it by feature: everything for "submit claim" (endpoint, validation, handler, data access) lives together in one folder. Changes to one feature touch one place. Many teams combine the two: vertical slices for the application code, with a shared domain model at the centre.
Monolith, modular monolith or microservices
This decision shapes deployment, data and teams more than any other:
| Monolith | Modular monolith | Microservices | |
|---|---|---|---|
| What it is | One deployable application with one database, and little internal structure | One deployable application, split into modules with clear boundaries, each owning its data | Many small services, each deployed independently with its own database |
| Deployment | One unit | One unit | Each service on its own |
| Calls between parts | In-process method calls | In-process calls through module interfaces | Network calls (HTTP, gRPC, messages) |
| Data | One shared database | One database, separate schemas per module | A database per service |
| Strengths | Simple to build, test, debug and deploy | Simple to run, with boundaries ready for a later split | Independent deployment and scaling; teams work without waiting on each other |
| Weaknesses | Turns into a "big ball of mud" as it grows | Needs discipline to keep the boundaries | Network failures, eventual consistency, distributed debugging, much more operational work |
| Fits | Small teams and new products | Most systems, most of the time | Large organisations with many teams and parts that need different scaling |
Microservices solve organisational problems (many teams that keep blocking each other) more than technical ones, and they bring every problem from the resilience lesson. A common path is to start with a modular monolith whose modules follow the bounded contexts, and extract a module into a service only when there is a clear reason:
- It needs to scale very differently from the rest (for example, file ingestion).
- It needs a different release pace, or a separate team owns it.
- It has different technical needs (a different runtime, stricter isolation or compliance rules).
If you do run microservices, follow these rules:
- Each service owns its data. No other service reads or writes its tables directly; they go through its API or its events. A shared database couples services so tightly that they cannot be deployed independently.
- Draw service boundaries along bounded contexts, not technical layers. A "database service" or a "validation service" creates chatty, fragile calls.
- Prefer asynchronous messaging between services for anything that does not need an immediate answer (lesson 9).
- Invest in the platform first: CI/CD, observability, distributed tracing and resilience defaults (lessons 7, 15 and 16).
Conway's law says that a system's structure mirrors the communication structure of the organisation that builds it. Use it on purpose: align service and module boundaries with team boundaries, so each team can change its part without coordinating with others.
Backend-for-Frontend (BFF)
Different clients need different things. A mobile app wants small payloads and few round trips; an admin web app wants rich, detailed data. A single general-purpose API either over-serves one or under-serves the other. A Backend-for-Frontend is a small API built for one specific front end, owned by the team that builds that front end:
- It combines calls to several services into one response shaped for its screen, so the client makes one call instead of five.
- It removes fields the client does not need, and adapts formats.
- It can handle authentication for browser apps. The BFF keeps the access tokens on the server and gives the browser only a secure, HTTP-only session cookie (one JavaScript cannot read). Tokens never reach the browser, which protects them from theft by malicious scripts (XSS). This is now the recommended pattern for browser-based apps, covered in the security lessons.
Keep business logic out of the BFF. It should shape and combine data, not make business decisions; those stay in the services. Otherwise the same rule ends up written in several BFFs.
Micro-frontends
Micro-frontends apply the microservice idea to the user interface. A large web app is split into parts (for example, claims, payments and reporting), each built, tested and deployed by its own team, and combined into one app for the user. Ways to combine them:
- Build time: each part is an npm package installed into a shell app. Simple, but every change needs the shell to be rebuilt and redeployed.
- Run time with Module Federation (Webpack, Rspack or Vite plugins): the shell loads each part's JavaScript from its own URL while the page runs, so teams deploy independently.
- Server-side or edge composition: the page is assembled from fragments on the server or at the CDN.
- iframes: the strongest isolation, but awkward for navigation, styling and sharing state.
| Benefits | Costs |
|---|---|
| Teams deploy their part of the UI independently | Several copies of React or other libraries can load unless they are shared carefully |
| Each part can be upgraded on its own schedule | A consistent look needs a shared design system (lesson 18) |
| A failure in one part can be isolated (error boundaries) | Shared state, routing and authentication across parts are harder |
| Large codebases stay manageable | More build, hosting and testing setup |
Like microservices, micro-frontends solve team-scaling problems. A single team rarely needs them; a well-structured monorepo with clear module boundaries (Nx or Turborepo) gives most of the benefits at lower cost.
Check your understanding
| Question | Short answer |
|---|---|
| What is a bounded context? | A boundary within which one domain model and one language apply; the same word can mean different things in different contexts. |
| Entity or value object? | An entity has an identity that persists as its data changes; a value object is defined only by its values and is usually immutable. |
| What is an aggregate root for? | It is the only entry point for changing the aggregate, so it can enforce the business rules for everything inside. |
| Why change only one aggregate per transaction? | Smaller transactions and fewer conflicts; other aggregates react to domain events instead. |
| What is the dependency rule in clean architecture? | Dependencies point inwards: the domain depends on nothing; infrastructure depends on the application's interfaces (ports). |
| Clean architecture or vertical slices? | Clean architecture organises by layer and protects the domain; vertical slices organise by feature. Many teams combine them. |
| Why start with a modular monolith? | It is simple to run, and its module boundaries make a later split into services easy if a real need appears. |
| Why must each microservice own its data? | A shared database couples services so they cannot change or deploy independently. |
| What is Conway's law? | A system's structure mirrors the organisation's communication structure, so align boundaries with teams. |
| What is a BFF? | An API built for one front end that shapes and combines data for it, and can keep tokens on the server for browser apps. |
| When are micro-frontends worth it? | When several teams must deploy parts of one large UI independently; otherwise a modular monorepo is simpler. |
Summary
- Use DDD's strategic ideas everywhere: a shared language with domain experts, and bounded contexts as boundaries.
- Use rich domain models (aggregates, value objects, domain events) where business rules are complex, not for simple CRUD.
- Keep business logic at the centre and infrastructure at the edge; let project references enforce the direction.
- Start with a modular monolith aligned to bounded contexts, and extract services only for a clear reason.
- If you run microservices, give each its own data, draw boundaries by domain, and invest in the platform first.
- Use a BFF per front end to shape data and keep tokens out of the browser, and micro-frontends only when several teams share one large UI.
The next lesson covers how services work together without tight coupling: event-driven design with Azure Service Bus, Event Hubs and Kafka, dead-letter queues, the Outbox and Inbox patterns, sagas, CQRS and eventual consistency.
Comments