Dev guide :: Architecture Principles

Architecture Principles Handbook

Architecture is how a system divides responsibilities, protects important rules, manages information, and handles change. This handbook explains software architecture without programming examples. It is intended for anyone who needs to understand, discuss, or assess a system design.

The central questions are practical: Who owns each decision? What must remain true? Which parts change together? What happens when something fails? Which extra complexity is worth maintaining?

Running example: a company sells training courses. Learners reserve seats, companies pay invoices, instructors record attendance, and eligible learners receive certificates. Each approach below explains a different way of organizing these responsibilities.

Reading guide: start with the principles, compare approaches using the decision guide, then read the worked example. These approaches are not competing products. Some describe business modeling, others describe internal structure, deployment, communication, or information storage. The recommendations are contextual judgments; the linked sources explain the underlying approaches.

Foundational principles

Separate concerns

Give responsibilities with different purposes clear homes. Deciding whether a learner qualifies for a refund is different from sending a confirmation email. Separating those responsibilities allows the email provider to change without changing refund eligibility.

Limit: dividing every small task creates coordination overhead. Separate responsibilities when they have different owners, rules, or reasons to change.

How to recognize a concern: ask what knowledge is required to change it. A refund deadline requires commercial-policy knowledge; an email layout requires communication and presentation knowledge; a payment connection requires knowledge of a provider's protocol. Different expertise and change triggers suggest different responsibilities.

Worked example: marketing wants a new confirmation design while operations changes the cancellation deadline from seven days to ten. These changes should be understandable and verifiable independently. A shared cancellation workflow can coordinate both responsibilities without owning their internal details.

When separation hurts: moving one tightly connected decision into several components can scatter the explanation. Keep the eligibility decision together even if it considers several facts. Review question: can a business expert find the complete rule without reconstructing it from many locations?

Keep related responsibilities together: cohesion

Cohesion means that the responsibilities within a component belong together. Cancellation deadlines, eligibility, and fees often change together, so they should remain easy to understand together. “Everything relates to a customer” is too broad a reason to put all behavior in one component.

How to assess it: look at actual changes. If changing one policy repeatedly requires coordinated edits in five places, those responsibilities may be separated along the wrong lines. Conversely, if unrelated policies share one component and frequently interfere, that component may need a clearer division.

Example: a course's public description belongs with catalog management, while its attendance requirements belong with teaching. Sharing a course identifier does not make these responsibilities cohesive. Their users, rules, and change schedules differ.

Tradeoff: cohesion is contextual. A small system may keep related capabilities together initially and separate them when their differences become important. Avoid deciding boundaries from nouns alone; investigate decisions and workflows.

Reduce unnecessary dependencies: coupling

Coupling is how much one part relies on another part's details. Bookings should need to know whether a payment succeeded, without understanding the payment provider's internal records. Clear agreements reduce the number of things that must change together.

Limit: communication cannot disappear. Replacing direct calls with messages does not remove business dependencies; it changes how they are managed.

Different kinds of coupling: parts can depend on a shared data format, on a particular order of actions, on simultaneous availability, or on coordinated releases. Two services can communicate through a queue and still be tightly coupled if every message change forces both to release together.

Example: billing should publish the business meaning of a settled invoice rather than expose the layout of its internal invoice table. Consumers then depend on a stable agreement instead of incidental storage choices.

When to accept it: some decisions genuinely require close coordination. Seat allocation and confirmation must agree on capacity. Trying to remove that relationship may simply hide it. Review question: which dependencies protect correctness, and which exist only because internal details are convenient to access?

Hide internal details

Other parts should ask the booking component to reserve a seat rather than directly rearrange its records. The owner can then change its internal organization while preserving the agreed behavior. This principle is called information hiding.

What to hide: details likely to change, such as storage layout, provider response formats, caching, and intermediate calculations. Expose useful business capabilities and their guarantees: what a reservation means, how long it lasts, and which failures callers must handle.

Example: bookings moves from calculating availability on demand to maintaining a dedicated availability record. Callers continue requesting reservations through the same capability. If callers had been reading and updating the old records directly, every caller would need to understand the migration.

Limit: hiding details must not hide observable consequences. If a reservation is temporary, callers need to know that. A clear boundary conceals implementation while making business behavior explicit.

Make ownership explicit

Give each important fact and rule an authoritative owner. Bookings owns seat allocation; billing owns invoice status. Other parts may keep copies, but must know whether those copies can be outdated and where corrections belong.

Ownership includes: deciding valid changes, resolving conflicting updates, explaining results, and supporting recovery. Naming a team is insufficient if several other components can bypass that team's rules by changing its information directly.

Example: teaching corrects an attendance error. Billing may retain attendance information for reporting, but it requests or receives the corrected fact from teaching rather than maintaining a competing version. The correction should also reach certificate eligibility according to a defined agreement.

Tradeoff: centralized authority does not require one giant component. Different facts have different owners. A cross-department workflow needs an explicit coordinator or interaction protocol so responsibilities do not fall between owners.

Protect invariants

An invariant is a condition that must remain true: confirmed bookings cannot exceed capacity, refunds cannot exceed the eligible amount, and certificates require completion. These rules must survive simultaneous requests and partial failures, not just the normal sequence of actions.

Scope matters: “a booking has a valid status” is local to a booking; “confirmed seats never exceed course capacity” spans the seat allocation decision. Merely checking availability on a screen is insufficient, because another learner can reserve the last seat before confirmation.

Worked example: two learners see one remaining place. Both submit requests. The authoritative reservation operation must make one succeed and the other receive a clear outcome. Payment timing also needs a policy: a temporary hold can expire, but expiration and confirmation must not both win.

When immediate enforcement is unnecessary: a reporting total can sometimes lag without violating business policy. Distinguish strict rules from freshness preferences. Review question: which forbidden state could appear during a race or failure, and what boundary prevents it?

Distinguish dependency from execution

A dependency describes what one part must know about to be defined or changed. Execution describes what happens while the system runs. A refund operation can invoke an external provider through an agreed capability without making refund policy depend on that provider's specific technology. This distinction matters in Clean, Onion, and Hexagonal Architecture.

Example: the business defines “request a refund and report accepted, rejected, or uncertain.” A provider adapter fulfills that agreement. At runtime the request reaches the provider; when defining the business policy, the provider's own terminology and connection format are unnecessary.

Why it matters: a diagram of runtime calls can make it seem that business rules must depend on every tool they use. Defining the required capability independently allows technical implementations to depend on the business agreement instead.

Limit: the agreement must represent real behavior. Pretending that every refund completes immediately conceals uncertainty rather than isolating technology. Review both structural dependencies and runtime failure paths.

Design for failure and repetition

A payment provider may accept a charge even when its response is lost. Retrying must not charge the learner twice. The design needs a way to recognize repeated attempts, investigate uncertain results, and recover unfinished work.

Separate failure from uncertainty: a declined payment is a known business result. A timeout means the result may be unknown. Automatically treating every timeout as a decline can release a seat after the learner has actually paid.

Recovery plan: track the business attempt, reuse its identity for a safe retry, ask the provider for its status where supported, and route unresolved cases to a visible investigation process. Limit retries and distinguish temporary outages from permanent rejection.

Compensation: a completed action may need a new action to counteract it. Refunding a charge is not erasing the original payment; it is another business occurrence that can itself fail. Review question: can staff explain what happened and resume safely without guessing?

Spend complexity deliberately

Every boundary, queue, service, and copied data store has a cost. Prefer the simplest design that meets the actual requirements. Performance, availability, security, auditability, and ease of change are quality goals; define them in observable terms, such as how quickly a failed booking must be recovered.

Make the comparison concrete: compare delivery effort, operating cost, likely changes, failure recovery, and the consequences of postponing a decision. “We may become large” is weaker evidence than measured congestion or teams repeatedly blocked by shared releases.

Example: separate video processing because it already consumes resources that disrupt bookings. Keep a small course catalog in the existing application because a separate deployment would create more operational work than benefit.

Reversibility: decisions about authoritative data and external contracts are often harder to reverse than internal organization. Invest proportionately in those decisions. Record assumptions and a trigger for reassessment instead of building every possible future requirement now.

Layered Architecture

Runtime flow: a cancellation passes through presentation, policy, and storage responsibilities. Arrows show requests, not deployment boundaries.

flowchart TD
    UI[Website or employee interface] -->|Requests cancellation| Business[Business operation]
    Business -->|Applies| Policy[Cancellation policy]
    Business -->|Records outcome through| Data[Data access]
    Data -->|Persists| Store[(Booking records)]

Main idea: organize the application into broad responsibilities, commonly presentation, business logic, and data access. Think of a reception desk, an operations department, and a records office. Logical layers can run in one application; separately deployed parts are often called tiers.

Problem solved: user interaction, policy, and storage become tangled without a clear organization.

Example: a website receives a cancellation request, the business layer evaluates eligibility, and the data layer records the outcome.

Use when: workflows are conventional, responsibilities are predictable, and a familiar structure helps the team.

Avoid elaborate layering when: the system is a tiny record-management tool, or most layers only pass information onward without making useful decisions.

Tradeoff: technical responsibilities are easy to locate, but one business feature may require changes across every layer.

Common mistake: allowing screens or storage operations to make business decisions, leaving the business layer empty.

How the layers cooperate

Presentation explains available actions and displays outcomes. Business logic decides what those actions mean and which rules apply. Data access retrieves and persists information. Some layered designs require communication through adjacent layers; others allow selected shortcuts. The permitted direction should be explicit so exceptions do not quietly erase the structure.

Worked cancellation scenario

  1. The screen collects the booking reference and cancellation request.
  2. The business operation loads relevant facts and evaluates the policy.
  3. The result is recorded, including whether a refund is pending.
  4. The screen presents the business outcome in understandable language.

A second interface should reach the same decision for the same facts. Presentation may reject an empty reference for usability, but authoritative eligibility cannot exist only in the website.

Costs and selection criteria

Layering helps locate technical responsibilities, but it does not automatically make business capabilities independent. A cancellation feature still spans presentation, policy, and storage. If this causes repeated handoffs, organize ownership around the feature while retaining useful internal separation.

Review: can the business operation be exercised without the website? Are storage concerns determining policy? Are extra layers performing meaningful work? A practical first step is to separate a duplicated rule from its screens, rather than introduce many new layers at once.

Reference: Microsoft's architecture guide.

Clean Architecture

Source dependencies: outer implementations depend on inner agreements and policies. Arrows mean “depends on”; they do not show the order of runtime calls.

flowchart TD
    UI[Website adapter] -->|Depends on| UseCase[Cancellation use case]
    UseCase -->|Depends on| Policy[Business rules]
    UseCase -->|Depends on| Port[Refund capability agreement]
    Payment[Payment provider adapter] -->|Implements| Port
    Database[Storage adapter] -->|Implements| Storage[Booking storage agreement]
    UseCase -->|Depends on| Storage

Main idea: keep business policies at the center and technology details outside. The defining dependency rule points inward: inner policies must not depend on outer implementation details such as a particular database or website framework.

Problem solved: important rules become difficult to understand and verify when tangled with external technology.

Example: refund policy determines eligibility. An application operation coordinates cancellation. A payment connection executes the refund. Replacing that connection should not require rewriting eligibility rules.

Use when: business rules are substantial, the application is long-lived, or rules need verification without external services.

Avoid a full structure when: little business behavior exists, a tool is short-lived, or simpler boundaries already provide sufficient protection.

Tradeoff: boundaries add translation and coordination work. Protecting rules does not make every technology change effortless.

Common mistake: treating a particular folder layout or number of layers as proof that dependencies are correct.

Policy, coordination, and delivery

Consider three decisions: the business policy defines the eligible refund amount; the application operation coordinates the cancellation; the outer connection translates the approved refund into a provider request. These responsibilities change for different reasons and should be understandable separately.

The dependency rule concerns what the inner policies know. It does not prohibit runtime communication with a database or payment service. A business-defined capability can be fulfilled by an outer implementation while keeping provider-specific assumptions outside policy.

Worked example: a new cancellation rule

Suppose corporate contracts allow a learner replacement instead of a refund. The domain decision evaluates replacement eligibility. The application operation coordinates the transfer and payment consequences. The website explains the available outcome. A new website should reuse that decision, and a new provider should not redefine it.

Boundaries worth protecting

Use business meanings at boundaries: a cancellation outcome and an eligible amount, rather than a provider response record. Include uncertainty and rejection where they genuinely exist. Translation is useful when meanings differ; copying identical information through many ceremonial layers adds maintenance without improving isolation.

Review: can eligibility scenarios be checked without a live provider? Does changing a database detail force a policy change? Start by protecting a high-value rule rather than restructuring the entire application. Infrastructure and integration checks remain necessary even when policy can be verified independently.

Reference: Robert C. Martin's original explanation.

Hexagonal Architecture: Ports & Adapters

Runtime interactions: different incoming adapters reach one application capability; outgoing adapters translate requests to outside systems.

flowchart LR
    Web[Website adapter] -->|Requests booking| In[Booking port]
    Import[Corporate import adapter] -->|Requests booking| In
    In -->|Invokes| Core[Booking application]
    Core -->|Requests payment| Out[Payment port]
    Out -->|Delegates to| Adapter[Payment adapter]
    Adapter -->|Calls| Provider[External provider]

Main idea: connect an application to the outside world through defined capabilities. A port expresses an interaction, such as collecting payment. An adapter connects it to a specific provider or technology. The hexagon does not imply six connections.

Problem solved: business behavior becomes tied to one interface, database, or external service.

Example: learners book through a website and employees through an internal tool. Both reach the same booking capability. A payment adapter translates requests for the current provider.

Use when: multiple channels share behavior, external integrations matter, or controlled substitutes are needed to check business scenarios.

Avoid extensive adapters when: there are few meaningful outside interactions and the extra boundaries add little value.

Tradeoff: adapters require maintenance. Providers with different refund rules or settlement behavior are not interchangeable merely because they use the same connection shape.

Common mistake: letting provider-specific meanings leak through a supposedly neutral port.

Two directions of interaction

An incoming interaction asks the application to do something: a learner submits a booking or an employee imports registrations. An outgoing interaction asks an external capability for help: take payment, store a reservation, or send a message. Each conversation needs an agreement suited to its business purpose.

Worked example: adding a corporate booking channel

A corporate buyer uploads a list of participants. The upload adapter interprets the file and requests bookings through the same application capability used by the website. Capacity and eligibility rules remain inside the application. The file adapter handles malformed columns; it does not invent a separate corporate capacity rule.

Where translation stops

A payment adapter translates the provider's responses into outcomes the application understands. If one provider supports delayed settlement and another does not, the agreement must represent the behavior the business needs. A port is a meaningful conversation, not just a renamed technical connection.

Review: are equivalent requests governed by the same rules across channels? Can a controlled substitute reproduce an uncertain payment? Verify the real adapter separately: a substitute demonstrates application behavior, but cannot prove provider compatibility.

Reference: Alistair Cockburn's original article.

Onion Architecture

Source dependencies: presentation and infrastructure point toward application agreements; application responsibilities point toward the central domain model.

flowchart TD
    Presentation[Presentation] -->|Depends on| Application[Application operations and agreements]
    Infrastructure[Infrastructure implementations] -->|Depends on| Application
    Application -->|Depends on| Domain[Domain model and business rules]

Main idea: place the domain model at the center, surround it with application responsibilities, and keep infrastructure outside. Dependencies point toward the center.

Problem solved: business behavior becomes shaped by database structures and technical frameworks rather than business meaning.

Example: a booking model expresses capacity and enrollment eligibility. The database stores its information without defining those rules.

Use when: a meaningful business model needs protection from technical changes.

Avoid elaborate rings when: there is little domain behavior to protect or an existing boundary approach already meets the need.

Tradeoff: the separation can improve clarity while adding translation work.

Common mistake: stacking Onion, Clean, and Hexagonal Architecture as three independent sets of mandatory layers. They overlap: Onion emphasizes the central domain model, Clean emphasizes policies and dependencies, and Hexagonal emphasizes external interactions.

What belongs near the center

Put business concepts and decisions near the center: bookings, eligibility, permitted transitions, and the relationships needed to explain them. Put orchestration around that model. Keep storage, external connections, and presentation at the edge. The precise number of rings is less important than preserving this direction.

Worked example: changing storage

The company changes how booking records are stored. Its model still recognizes a temporary reservation, a confirmed booking, and a cancelled booking. The outer storage implementation translates those concepts into the new records. If the central model must adopt database-specific fields to remain usable, the storage boundary is leaking.

Limits of the protection

Storage can influence correctness even when dependencies point inward. A new store must still support the required capacity guarantees. Likewise, keeping a model independent of a framework does not eliminate migrations, integration work, or performance concerns.

Review: does the central model explain the business, or merely mirror tables? Can a policy be discussed without naming technical tools? Use existing Clean or Hexagonal boundaries where they already achieve the desired protection; additional rings need a concrete purpose.

Reference: Jeffrey Palermo's original explanation.

Domain-Driven Design: DDD

Model relationships: a buyer can fund several bookings, each identifying a participant and a course offering. Relationships describe business meaning rather than database design or aggregate boundaries.

flowchart LR
    Buyer[Buyer] -->|Pays for| Booking[Booking]
    Booking -->|Reserves a place in| Course[Course offering]
    Booking -->|Identifies| Participant[Participant]
    Participant -->|Has recorded| Attendance[Attendance]
    Attendance -->|Contributes to decision about| Completion[Completion eligibility]

Main idea: develop a model of the business collaboratively with domain experts, then use that model and shared language to guide the system.

Problem solved: software misrepresents business meanings or cannot clearly express complicated rules.

Example: teaching calls someone a participant, while billing calls the buyer a customer. A company can buy places for several participants. Treating these as one concept causes billing and attendance mistakes.

Use when: business complexity and terminology matter, and experts can participate throughout development.

Avoid extensive tactical modeling when: work is mostly simple record maintenance or an external product already defines the behavior. Shared language can still help.

Tradeoff: discovering and refining a useful model takes sustained collaboration.

Common mistake: using DDD terminology without involving people who understand the business.

Strategic design: where models belong

First identify the important business capabilities and where meanings differ. Spend the most modeling effort on the capabilities that distinguish the company. A specialized enrollment policy may deserve deep modeling; a standard email delivery integration may be better purchased and connected through a clear agreement.

Tactical design: expressing decisions

Within a context, entities represent continuing identities, value objects represent descriptive values, and aggregates define groups whose rules are maintained together. A booking aggregate can protect its own valid transitions. Course-wide capacity still needs its own coordinated owner; separate valid bookings do not by themselves prevent overselling.

Worked discovery session

Ask sales, teaching, and billing to describe a learner transfer. Sales may call it a replacement, teaching may require prerequisites, and billing may distinguish a price adjustment from a refund. Write down the events, decisions, exceptions, and disputed terms. Resolve disagreements before embedding one interpretation in the system.

Example rule: replacing a participant keeps the purchased place, while transferring a booking to another course can change price and capacity. A model that calls both actions “edit participant” hides consequences that staff need to understand.

Adoption and review

Begin with one complex workflow and a shared vocabulary. Refine the model when new examples contradict it. Workshops produce hypotheses that must be checked against real operations. Review whether the model explains exceptions, whether expert vocabulary appears consistently, and whether a policy has one authoritative home.

Further reading: domain analysis and domain models and aggregates.

Reference: DDD overview.

ConceptMeaningTraining-company example
Ubiquitous languageVocabulary used consistently within a model's boundaryEveryone agrees what a confirmed booking means
EntitySomething with a continuing identityA particular booking remains the same booking after a transfer
Value objectSomething identified by its valuesAn amount together with its currency
AggregateA group managed as a consistency boundaryA booking and its lines enforce their rules together
Domain eventA meaningful business occurrenceBooking confirmed

Bounded contexts & ownership

Information flow between contexts: arrows label the facts exchanged. Each context interprets them within its own model.

flowchart LR
    Sales[Sales: offers and discounts] -->|Agreed offer| Bookings[Bookings: reservations and capacity]
    Bookings -->|Payment request| Billing[Billing: invoices and settlement]
    Billing -->|Settlement result| Bookings
    Bookings -->|Confirmed enrollment| Teaching[Teaching: attendance and completion]
    Teaching -->|Completion decision| Certificates[Certification: issued credentials]

A bounded context is an area where a particular model and vocabulary apply. Sales understands offers and discounts, bookings understands reservations, teaching understands attendance, and billing understands payment obligations. The same word can legitimately mean different things in different contexts.

Problem solved: one universal model forces different departments to compromise or silently use incompatible meanings.

Example: “course” in sales includes promotional descriptions; in teaching it includes a syllabus and completion criteria. Both refer to related offerings without needing identical records.

Use when: meanings or ownership differ across business areas. Define how those areas exchange information and translate concepts.

Avoid arbitrary contexts: separate models need a real difference in meaning or responsibility, rather than one boundary per screen or organizational chart box.

Tradeoff: separate models require explicit integration agreements and sometimes duplicated information. A bounded context does not automatically require a separate service or database.

Common mistake: sharing internal records across contexts so freely that neither owner can change its model.

Map relationships as well as boxes

A context map explains who supplies information, who consumes it, and where translation happens. Billing may supply invoice settlement to bookings; teaching may supply completion to certification. Document which side controls the agreement, how changes are coordinated, and what happens when information arrives late.

Worked example: protecting teaching from a vendor model

An external learning platform reports sessions viewed and quiz scores. Teaching translates those facts into the company's completion criteria. “Viewed every video” must not silently become “completed the course” unless the business explicitly defines it that way. This translation boundary is often called an anti-corruption layer.

Separate context from deployment

Contexts can live in one application. One context can also contain multiple technical components. The business boundary identifies coherent meaning; deployment is a separate decision about operations and independence. Forcing a service boundary too early makes uncertain business divisions expensive to change.

Review: which facts are copied, who can correct them, and how are corrections propagated? If two contexts must inspect each other's internals to make every decision, reconsider either the boundary or the agreement.

Reference: Bounded Context.

Modular Monolith

Deployment and runtime interactions: internal modules have explicit agreements while sharing one deployment. The payment provider remains outside that boundary.

flowchart LR
    subgraph App[One application deployment]
        Bookings[Bookings module] -->|Requests payment| Billing[Billing module]
        Bookings -->|Supplies enrollment| Teaching[Teaching module]
    end
    Billing -->|Uses external connection| Provider[Payment provider]

Main idea: deploy one application while maintaining clear internal modules with explicit responsibilities and interaction agreements.

Problem solved: a single application becomes hard to maintain when every part freely manipulates every other part.

Example: bookings owns seat allocation, billing owns invoices, and teaching owns attendance. They interact through agreed operations and are released together.

Use when: the team benefits from simple operations, boundaries are still evolving, or independent releases are unnecessary.

Avoid when: demonstrated requirements demand independent deployment, stronger process isolation, or scaling arrangements that one deployment cannot reasonably provide.

Tradeoff: releases and runtime resources remain shared. Internal boundaries need discipline and verification; a single process alone does not enforce them.

Common mistake: calling folders “modules” while allowing unrestricted access to each other's records. A monolith can be well structured, and a service-based system can be tangled.

What makes the modules real

Each module owns a coherent capability, exposes deliberate operations, and protects its internal information. Sharing a database does not justify unrestricted updates across owners. Architectural checks and focused integration scenarios help prevent shortcuts from becoming permanent dependencies.

Worked example: coordinated booking and billing

Bookings records a temporary reservation and asks billing to start payment. Billing reports a result through an agreed interaction. Bookings decides confirmation or expiry. The single deployment simplifies operation, but a payment provider remains external and can still fail independently.

Advantages and constraints

Local interactions can simplify debugging and avoid network overhead between modules. A shared transaction may coordinate selected local changes when supported, but external payment cannot simply be rolled back with local records. One deployment also shares release timing and can share resource failures.

Evolution: strengthen an internal boundary before extracting a module into a service. Check its data ownership, callers, and failure assumptions first. Extraction is justified when independence solves a demonstrated problem, not because the module has become large by an arbitrary measure.

Review: can billing's internal organization change without editing teaching? Are cross-module operations visible? Is a shared release actually causing harm, or is it keeping a manageable system simple?

Microservices

Deployment and runtime interactions: each service has its own deployment and authoritative data. Arrows between services cross a network boundary.

flowchart LR
    subgraph B[Booking deployment]
        Booking[Booking service] -->|Owns| Seats[(Reservation data)]
    end
    subgraph P[Billing deployment]
        Payment[Billing service] -->|Owns| Invoices[(Invoice data)]
    end
    subgraph T[Teaching deployment]
        Teaching[Teaching service] -->|Owns| Attendance[(Attendance data)]
    end
    Booking -->|Payment request over network| Payment
    Booking -->|Enrollment over network| Teaching

Main idea: organize business capabilities into independently deployable services with clear ownership.

Problem solved: shared deployments and operating arrangements can constrain teams with genuinely different release, scaling, or isolation needs.

Example: video delivery needs substantial bandwidth and frequent operational changes, while billing follows a different release schedule. Separate services may let each evolve appropriately.

Use when: deployment independence has clear value, boundaries are understood, and teams can operate distributed systems.

Avoid when: a small team must maintain many services, boundaries change frequently, or most operations require coordinated changes across them.

Tradeoff: network failures, compatibility, monitoring, and data consistency become major concerns. Automated deployment and operational readiness are prerequisites.

Common mistake: splitting into many services that still require coordinated releases, creating a distributed monolith.

Independence is a responsibility

A service needs an owner for its behavior, information, deployment, monitoring, and recovery. Other services use its supported agreements rather than update its records directly. Independent deployment requires compatibility across different versions, since callers and providers will not always upgrade together.

Worked example: payment and reservation

Booking and payment cannot rely on a single local transaction when they are separate services. The business needs a process with explicit intermediate states: reserve temporarily, attempt payment, confirm, or release the reservation. A charge that succeeds after a reservation expires may require a refund or staff intervention under a defined policy.

Understand the failure cost

Adding a network call adds latency and another way to fail. A long chain of required services can reduce end-to-end availability even if every service seems reliable individually. Isolation helps only when callers have a useful way to behave during an outage, such as postponing certificate generation while bookings remain available.

Selection and review

Look for measured differences in scaling, release cadence, or isolation needs. Establish automated deployment, operational ownership, and a way to trace one business process across services. Start with a capability whose boundary is already clear.

Review: can the service release without synchronized changes elsewhere? Can it recover its own failed work? If every request crosses many services or every feature changes all of them, reconsider the division before adding more infrastructure.

Reference: Microservice prerequisites.

Event-Driven Architecture

Runtime event delivery: confirmation is announced once as a business occurrence; independent consumers react at their own pace. Delivery can repeat, so each consumer needs safe handling.

flowchart LR
    Booking[Booking owner] -->|Publishes Booking confirmed| Channel[Event channel]
    Channel -->|Delivers event| Email[Joining instructions consumer]
    Channel -->|Delivers event| Instructor[Instructor planning consumer]
    Channel -->|Delivers event| Reports[Reporting consumer]

Main idea: components announce occurrences and interested consumers react. An event describes something that happened; a command requests an action.

Problem solved: one operation must trigger several independent activities without directly coordinating each one.

Example: “Booking confirmed” triggers joining instructions, instructor notifications, and reporting updates. “Confirm booking” is instead a command.

Use when: multiple consumers need an occurrence, work can happen asynchronously, or consumers require independent processing capacity.

Avoid when: a simple immediate interaction is sufficient or the business requires an immediate coordinated result that the proposed asynchronous design cannot provide.

Tradeoff: consumers may temporarily disagree about current state. Delivery, repeated messages, ordering, monitoring, and recovery need explicit design.

Common mistake: assuming publication proves downstream completion. A failed email consumer must be detectable and recoverable even though the booking succeeded.

Define the meaning of the event

“Booking confirmed” should have one agreed meaning. Consumers need enough context to act, plus an identity that connects processing to the original business occurrence. Avoid broadcasting unnecessary personal information; many consumers may receive and retain the message.

Worked failure: confirmed but never announced

Suppose a booking is saved and the application crashes before announcing it. A durable notification intention recorded with the local booking change can close this gap. A separate sender delivers that intention later. This is the transactional outbox approach; delivery can still repeat, so consumers must handle duplicates.

Ordering and repeated delivery

A cancellation may reach a consumer before an earlier confirmation. Decide which order matters, within what scope, and how consumers recognize stale information. Processing the same confirmation twice must not issue two vouchers. A broker's guarantees do not automatically cover an external side effect.

Coordination choices

Choreography lets consumers react independently; orchestration gives a workflow owner responsibility for progress and next steps. Independent notifications often suit choreography. A multi-step refund process may benefit from explicit orchestration so staff can see what is pending.

Review: can operators find delayed or failed events, retry safely, and identify unfinished business processes? Define acceptable lag and an escalation route. Further reading: transactional outbox.

Reference: Event-driven architecture guide.

CQRS: Separate models for changes and reads

Runtime flow for an asynchronous variant: changes use an authoritative model; dashboards use a projection that can lag. CQRS can also use one database without asynchronous projection.

flowchart LR
    User[Learner] -->|Reserve seat| Change[Change operation]
    Change -->|Enforces rules and writes| Write[(Authoritative booking state)]
    Write -->|Changes feed| Project[Projection updater]
    Project -->|Updates later| Read[(Dashboard read model)]
    Dashboard[Dashboard query] -->|Reads| Read

Main idea: use different models for changing information and retrieving it. CQRS stands for Command Query Responsibility Segregation. It does not inherently require separate databases, services, or events.

Problem solved: a model that enforces business rules can be awkward for searching, reporting, or presenting summaries.

Example: reserving a seat requires capacity checks; a dashboard needs course availability, attendance, and revenue summaries. Each receives a model suited to its purpose.

Use when: reads and changes have substantially different needs and separation provides measurable clarity or performance benefits.

Avoid when: ordinary record management already meets the requirements.

Tradeoff: separate models require maintenance. Asynchronously copied information can make dashboards temporarily outdated.

Common mistake: introducing multiple databases and messaging for every feature simply because operations are called commands and queries.

Separate purpose before infrastructure

A change model answers whether an action is allowed and protects its rules. A read model answers a particular information need. The separation can begin inside one application and one database. Separate storage and asynchronous updates are additional choices, each with its own cost.

Worked example: a stale availability dashboard

The dashboard says a course has one seat left, but another learner has just booked it. The authoritative reservation operation must recheck capacity. The dashboard helps discovery; it cannot guarantee a future booking. After success, the interface may show the confirmed result directly while its summary catches up.

Operating read models

A projection is a view assembled for a purpose, such as a course summary. If it is updated asynchronously, define its freshness target, detect when it falls behind, and decide how to rebuild it. Several tailored views can improve reading while multiplying maintenance and reconciliation work.

Review: does each separate model serve a real need? Are authorization and sensitive-information rules enforced for every view? A simpler report, index, or cache may solve the immediate problem without a broader CQRS design.

Reference: Martin Fowler on CQRS.

Event Sourcing

Information derivation: accepted changes extend the authoritative event history. Replaying that history reconstructs state and views, without repeating external side effects.

flowchart LR
    Request[Requested change] -->|Checked against current state| Decision[Business decision]
    Decision -->|Appends accepted event| History[(Ordered event history)]
    History -->|Replayed to reconstruct| State[Current booking state]
    History -->|Projected into| View[Reporting view]
    State -->|Informs next decision| Decision

Main idea: store an ordered history of changes as the authoritative record and derive current state from it.

Problem solved: latest-state records alone do not explain or reconstruct the sequence of business changes.

Example: a booking history records reservation, confirmation, transfer, and cancellation. Current status is derived from those events.

Use when: historical reconstruction and change history are central requirements.

Avoid when: current-state storage with a conventional audit trail already meets the need.

Tradeoff: historical event formats must remain understandable. Corrections, reconstruction speed, and sensitive-data retention need careful treatment.

Common mistake: treating ordinary application logs as an authoritative event history. Reliable history requires deliberate completeness and ordering guarantees.

Event sourcing, CQRS, and event-driven communication are independent choices. Using one does not require adopting the others.

History, current state, and projections

The authoritative history records accepted business changes. Current state is reconstructed from that history, and projections provide views for particular questions. A snapshot can speed reconstruction by saving a derived state at a known point; it does not replace the authoritative events.

Worked example: correcting a transfer

A booking is confirmed, transferred, then found to have been transferred to the wrong course. Record the correction as a new occurrence with its business meaning. The history must explain both the original decision and the correction. Quietly rewriting past events undermines the intended historical account.

Evolution and replay

Older events must remain interpretable as business definitions evolve. Rebuilding a view must not resend historical emails or recharge customers; reconstruction and live side effects need separate handling. Competing changes to one history also require a way to prevent both being accepted against the same outdated state.

Selection and review

Ask which historical questions truly require reconstruction. An audit trail may be simpler when the latest state remains authoritative. Plan recovery, format evolution, retention, and sensitive data before adoption. An append-only design creates practical challenges for correcting or removing information.

Review: can a clean environment rebuild trustworthy current state? Can historical formats still be read? Can staff distinguish a correction from the original event? Event history alone does not guarantee completeness or audit quality.

Reference: Event Sourcing pattern.

Vertical Slice Architecture

Responsibility map: each slice owns an end-to-end action. All slices rely on shared authoritative policy where the business rules are the same.

flowchart TD
    Reserve[Reserve seat slice] -->|Uses| Capacity[Shared capacity policy]
    Transfer[Transfer booking slice] -->|Uses| Capacity
    Transfer -->|Uses| Eligibility[Shared transfer eligibility]
    Cancel[Cancel booking slice] -->|Uses| Refund[Shared refund policy]

Main idea: organize work around complete business actions, such as booking a course, transferring a learner, or requesting a refund.

Problem solved: a feature scattered across technical layers requires coordination throughout the application.

Example: the refund slice brings together the responsibilities specifically needed to process a refund, while shared refund policy retains one owner.

Use when: features change independently and end-to-end ownership improves delivery.

Avoid rigid slicing when: it duplicates shared policies or hides important dependencies among workflows.

Tradeoff: slices can evolve inconsistently unless shared business rules and technical conventions remain explicit.

Common mistake: copying refund eligibility into several slices. Slices may share a domain model and coexist with Clean or Hexagonal boundaries.

Follow the business action

A slice gathers the work needed for one outcome rather than grouping all presentation, all coordination, and all storage work into separate ownership silos. Internal techniques can differ by need: a simple listing may stay straightforward, while cancellation uses richer policy modeling.

Worked example: transferring a participant

The transfer slice collects the request, invokes the shared rules for eligibility and capacity, coordinates changes, and presents the outcome. It should be easy to trace this action end to end. It must not create a private copy of the same capacity rule used by ordinary bookings.

Sharing without recreating a maze

Share stable business decisions and truly common capabilities. Similar-looking steps do not always mean identical policies: canceling a course and canceling one booking may have different obligations. Prematurely merging them can create a shared component filled with exceptions.

Review: does a routine feature change remain localized? Can reviewers see its full business effect? Are cross-slice dependencies explicit? Choose slice boundaries around meaningful actions rather than every screen widget or individual field.

Reference: Jimmy Bogard's explanation.

Pipes & Filters

Processing flow: each stage receives and produces a defined form of information. Preliminary validation does not replace the authoritative capacity check when reserving.

flowchart TD
    File[Registration file] -->|Rows| Parse[Read and normalize]
    Parse -->|Normalized rows| Validate[Validate required details]
    Validate -->|Valid rows| Deduplicate[Detect repeated requests]
    Validate -->|Invalid rows| Report[Import report]
    Deduplicate -->|New requests| Reserve[Authoritative reservation operation]
    Reserve -->|Accepted or rejected outcomes| Report

Main idea: process information through focused stages, with each stage receiving input and producing output for the next.

Problem solved: a large transformation becomes easier to understand, verify, and reuse when divided into meaningful steps.

Example: a bulk registration import reads records, checks required information, detects duplicates, validates course availability, and produces an import report.

Use when: work naturally forms a sequence of transformations and stages can be checked independently.

Avoid when: the workflow has extensive shared decisions, unpredictable branching, or tightly coordinated changes that do not fit a pipeline.

Tradeoff: intermediate formats, partial completion, and restarting failed work require agreements.

Common mistake: retrying an import repeats an irreversible action. Issuing certificates or charging customers needs protection against duplicate processing.

Stages and their agreements

A filter performs a focused transformation or validation. A pipe carries its output onward. Each stage needs a clear input, output, and failure meaning so it can be checked independently. Stages may run together or be separated operationally; a pipeline does not require a queue between every step.

Worked example: a partially invalid import

A company submits 500 registrations. Some rows lack participant details and several reference a full course. Decide whether to reject the entire batch or accept valid rows with a precise error report. This is a business choice, not a consequence to leave to the pipeline implementation.

Back pressure and recovery

If reading is much faster than booking, work accumulates. Back pressure means slowing upstream stages or bounding queued work so the system remains stable. Checkpoints can allow restart from a known position, but the action that creates a booking still needs protection against duplicates.

Review: can each rejected row be explained? Can a stopped batch resume safely? Does reordering stages change meaning? A capacity check early in the pipeline is only advisory if capacity can change before the authoritative reservation step.

Further reading: Pipes and Filters pattern.

Combining approaches

Choose approaches by the question they answer. DDD describes business understanding; microservices describes deployment boundaries. A business model can exist inside either a monolith or a service.

QuestionRelevant approaches
What does the business mean?DDD and shared language
Where do meanings or ownership differ?Bounded contexts
How is internal work organized?Layers or vertical slices
How are policies protected from technology?Clean, Hexagonal, Onion
What is deployed independently?Modular monolith or microservices
How do independent parts react?Event-driven architecture
Do reads and changes need different models?CQRS
Is change history authoritative?Event sourcing
Does processing follow transformation stages?Pipes and filters

Coherent combination: use DDD to clarify booking terms, a modular monolith for deployment, Hexagonal boundaries for payments, vertical slices for workflows, and events for independent notifications. Each choice should solve a concrete problem; adopting more names is not a quality goal.

Decision guide

Observed problemFirst direction to investigateEvidence to seek
Repeated misunderstandings about business termsDDD and bounded contextsWhich meanings differ, and who can clarify them?
A vendor change disrupts business rulesHexagonal or Clean boundariesWhich provider assumptions leaked into policy?
Every feature requires changes everywhereCohesion, modules, vertical slicesWhich responsibilities actually change together?
Teams block each other's releasesOwnership improvements; possibly microservicesWould deployment independence remove the bottleneck?
Several independent actions follow a bookingEvents or background workWhat delay, retry, and delivery guarantees are required?
Reporting conflicts with transaction needsDedicated read models; possibly CQRSAre simpler reporting changes sufficient?
Historical reconstruction is essentialAudit design; possibly event sourcingWhich history must be authoritative?
Imports are hard to understand and recoverPipes and filtersHow will partial completion and retries behave?

Decision method: describe the problem, state measurable constraints, compare the simplest viable alternatives, identify new failure modes, and record why the chosen tradeoff is acceptable. Revisit the decision when its assumptions change.

Worked example: evolving a training platform

Booking lifecycle: this illustrative policy distinguishes a temporary hold, a confirmed booking, and an unresolved payment outcome. An uncertain payment needs reconciliation rather than a guessed success or failure.

stateDiagram-v2
    [*] --> Held: Seat reserved temporarily
    Held --> Confirmed: Payment accepted before hold expires
    Held --> Released: Payment rejected or unpaid hold expires
    Held --> Investigating: Payment outcome uncertain
    Investigating --> Confirmed: Payment and valid reservation reconciled
    Investigating --> RefundPending: Charged but reservation cannot be honored
    Investigating --> Released: No charge confirmed and hold released
    Confirmed --> Cancelled: Cancellation accepted
    Cancelled --> RefundPending: Refund required by policy
    RefundPending --> Refunded: Refund confirmed
    Released --> [*]
    Refunded --> [*]

Stage 1: A small company

The company needs listings, bookings, payments, and email. One application with explicit modules is a reasonable starting point. Bookings owns seats, billing owns payment status, and provider connections have defined boundaries. There is no demonstrated need yet for separate services or event sourcing.

Stage 2: Business rules become complicated

Corporate customers buy seat bundles, cancellation rules differ by contract, and learners transfer between courses. DDD becomes useful because terminology and policy need refinement with experts. The deployment can remain unchanged.

Stage 3: Reporting becomes demanding

Operations needs dashboards that combine attendance, availability, and revenue. A dedicated read model may help. Apply separation to reporting where justified rather than introducing CQRS throughout the platform. Agree how stale a dashboard may be.

Stage 4: Operating requirements diverge

Video delivery grows rapidly and needs independent scaling and releases. Extracting that capability may now be justified. Plan network failures and compatibility before relying on the new service.

Stage 5: More activities follow bookings

Instructor planning, reporting, and external integrations all react to confirmations. Events may reduce direct coordination. Support staff also need visibility into failed consumers and a safe way to retry work.

Check the difficult cases

  • Two learners request the final seat: the booking owner must prevent both becoming confirmed.
  • Payment succeeds but the response is lost: a retry must recognize the existing attempt and reconcile the result.
  • Payment fails after a temporary reservation: define when and how the seat becomes available again.
  • A notification arrives twice: repeated delivery must not create duplicate business actions.
  • A course is cancelled: one clear owner initiates cancellation, while refunds and notifications expose progress and recoverable failures.
  • Attendance is corrected: teaching owns the correction and certificate eligibility is reconsidered under an explicit policy.

The useful architecture is the one that makes these outcomes reliable and understandable. Its structure can evolve as the business provides evidence.

Architecture review questions

  1. What specific problem does this design solve, and how will improvement be measured?
  2. Who owns each rule and authoritative fact?
  3. Which conditions must always remain true, including under simultaneous requests?
  4. Which information may temporarily be outdated, and for how long?
  5. What happens if a dependency fails halfway through?
  6. What happens if an operation or message is repeated?
  7. How will support staff identify and recover a failed business process?
  8. What changes together, and does the structure reflect that?
  9. What simpler alternative was considered?
  10. What evidence would justify revisiting the decision?

Warning signs: choosing services by a target count, drawing boundaries without owners, requiring coordinated releases everywhere, duplicating policies, or claiming that a technology eliminates failure. Ask for a concrete business scenario and its failure path.

Plain-language glossary

TermMeaning
DomainThe business area and its knowledge, activities, and rules
ModelA purposeful representation of relevant business concepts
Component / moduleA part with a defined responsibility and interaction boundary
ContractAn agreement about inputs, outcomes, errors, and meaning
DependencySomething a part relies on to be defined, changed, or operated
InfrastructureTechnical facilities such as storage, messaging, and external connections
DeploymentReleasing a runnable version into an operating environment
SynchronousThe initiating interaction waits for a result
AsynchronousWork can finish later, independently of the initiating interaction
Strong consistencyA defined guarantee that relevant reads reflect coordinated changes immediately
Eventual consistencyCopies can temporarily differ and converge as updates are processed
IdempotencyRepeating an operation has the same intended effect as performing it once
ObservabilityThe ability to understand system behavior from its operational evidence
CompensationA business action that counteracts an earlier step, such as refunding a charge

Sources & further reading

The original explanations are useful for understanding intent; the business scenarios in this handbook illustrate application rather than prescribing a universal design.

Diagram
100%