Chapter 9: Building WriteFlow: The complete implementation
The introduction explains how WriteFlow’s previously built parts will form a runnable application and why two consumers of one domain event run in different transaction phases.
After this chapter you will be able to
- A Complete WriteFlow Assembly. Explain why this chapter connects existing WriteFlow components rather than introducing new patterns, and identify the limited wiring needed to make them a runnable whole.
- Two Event Consumption Guarantees. Distinguish why the published-article event has a before-commit outbox consumer and an after-commit notification consumer.
- Two paths through the hexagon. Describe how publishing an article and reading it back provide the chapter’s command and query paths through a complete hexagon, rather than isolated examples or stubs.
- Publish event transaction phases. Distinguish when the outbox writer and subscriber notification run in relation to the publish transaction.
- Domain Core Responsibility. Explain what belongs in WriteFlow’s domain core and why the surrounding application carries data to and from it rather than defining article rules itself.
- Always-valid article value objects. Explain how WriteFlow replaces raw article strings with value objects that cannot be created without validation, and describe what their factories return on success or failure.
- Single and multiple rule validation. Distinguish the single-rule chain from the error-list approach, using ArticleId and Title to explain when WriteFlow uses each and how Title reports failures.
- Article lifecycle and rule ownership. Explain that an article is either a draft or published, and that the ArticleStatus enum names those states while the aggregate owns the rules for transitioning between them.
- Article aggregate responsibility. Explain why Article is an aggregate root rather than a record: it owns data that must remain consistent together, has identity by id, and controls status changes through behavior.
- Creation and reconstitution factories. Distinguish validateThenCreate from reconstitute, including why loading a persisted article does not repeat creation validation or decide how to handle older data that fails today's rules.
- Publishing and event ownership. Describe what the Article aggregate does when publishing succeeds and distinguish its decision to record an ArticlePublished event from delivery by the application layer.
- Cross-boundary event contract. Explain why ArticlePublished lives in the shared kernel and uses primitives, even though the Article aggregate may decide to raise it.
- Article Aggregate Guarantees. Describe how Article creation, publication, event handling, and reconstitution preserve the stated domain guarantees.
- Inside Out Domain Boundary. Explain what building the domain inside-out keeps within the core and what it deliberately leaves outside.
- Input and output port contracts. Distinguish the contracts that bring requests into WriteFlow from those the application uses to reach outward, and describe where those contracts live.
- Primitive-only message boundary. Explain why commands and queries carry primitives rather than domain value objects, using PublishArticleCommand as an example.
- Validated message construction. Describe how a command or query rejects malformed primitive input before a handler runs, and why domain value objects still validate when constructed.
- Thin input port contracts. Explain how a WriteFlow input port names a capability and specifies its message and result without implementing behavior. Describe why this lets an adapter depend on a use-case interface rather than a handler.
- Read-side DTO contract. Describe how the query handler reads an Article and returns an ArticleDTO with flat data, including a String status rather than an ArticleStatus.
- Aggregate boundary protection. Explain why query handlers and output ports must not return Article, and distinguish the read-side ArticleDTO result from the write-side Void result.
- Output port boundary contract. Explain what output ports represent in WriteFlow and how the application core and adapters relate to them.
- In-process domain event dispatch. Trace how raised domain events reach in-process listeners through DomainEventPublisherOutputPort without exposing dispatch technology to the core.
- Durable relay and publisher failures. Distinguish the integration-event relay from in-process dispatch and explain what a failure returned by either publisher port means.
- Behavior-free application contracts. Explain what the completed WriteFlow contracts specify and why they contain no behavior.
- Port dependency direction. Distinguish input ports from output ports and explain why commands and queries carry primitives rather than domain types.
- Thin handler orchestration. Explain how a handler implements a use-case input port by turning a primitive command into domain input, driving the aggregate, coordinating output ports, and returning Either. Distinguish that orchestration from domain decisions and adapter mechanics.
- Either-aware transaction rollback. Explain why handlers use the project's @Transactional annotation and why configured Either.left results require rollbackForClassNameWithEither rather than relying on Spring's standard rollback behavior.
- Create Handler Flow. Trace how the create handler turns a primitive command into value objects, assembles a draft Article, and persists it. Explain why a failed step stops the chain.
- Publish handler pipeline. Trace the publish handler’s five steps and explain why publication rules remain in the Article aggregate rather than the handler.
- Save-before-dispatch ordering. Explain how the handler retains the article after saving so it can drain its events, and why it dispatches them only after a successful save.
- Publisher port and dispatch result. Describe how the publisher output port hides Spring event dispatch from the handler, and distinguish a successful dispatch call from a listener’s later outcome.
- Atomic before-commit outbox recording. Explain why the outbox intention is recorded before commit and how an outbox failure can roll back the publication.
- Post-commit notification trade-off. Distinguish the durability and failure behavior of after-commit subscriber notification from before-commit outbox recording, and justify the phase chosen for each.
- Article query read path. Trace how GetArticleByIdHandler parses an id, requests a DTO from the repository, and returns it to the caller. Explain why this path does not mutate state, raise events, or require a second transaction phase.
- Publish event transaction timing. Explain why a publish event has consumers at different transaction phases: the outbox write must share the business transaction, while the subscriber notification is attempted only after commit.
- Handlers versus domain decisions. Distinguish a handler’s orchestration from business decisions that belong on the aggregate, such as guards, calculations, and state checks.
- Driving and driven adapters. Distinguish adapters the core calls through output ports from adapters that send requests into the core through input ports. Explain why WriteFlow needs both before its completed core can interact with a database, external services, or HTTP requests.
- Inward adapter dependencies. Explain how WriteFlow keeps adapter implementations outside the core: adapters depend inward on ports, output-port implementations need not be public, and assembly-time wiring connects them. Distinguish adapters from the mappers that merely collaborate inside them.
- Separate persistence model. Explain why JpaArticle is separate from the Article aggregate and why the Spring Data repository is not the ArticleRepository port.
- Guarded creation and reconstitution. Distinguish guarded creation from database reconstitution, and explain how WriteFlow restricts access to the validation-free path.
- Adapter boundary translations. Describe the three translations performed by the adapter that implements ArticleRepository.
- Atomic outbox recording. Explain the dual-write problem and how WriteFlow avoids it by saving an outbox row in the same transaction that publishes the article, rather than sending the event immediately.
- Three event representations. Distinguish the in-process domain event, the external integration-event contract, and the outbox storage row, and explain why they remain separate.
- Transactional domain event bridge. Trace how SpringDomainEventPublisher dispatches drained domain events and explain why it lives in the persistence module.
- Interchangeable notification adapters. Explain why WriteFlow can use a fake notification adapter instead of a production email adapter without changing the core.
- Prototype adapter selection. Justify which adapters WriteFlow implements fully and which it stubs when demonstrating the publish path.
- REST controller translation pipeline. Trace how a REST endpoint turns an HTTP request into a core invocation and then an HTTP response.
- Generated identity and command results. Explain how the controller can return a new article ID while CreateArticleCommand still returns no success value, and why WriteFlow generates the ID server-side.
- Expected and unexpected error channels. Distinguish how the REST adapter handles expected core failures from failures that never enter its Either pipeline.
- The assembly gap. Explain why WriteFlow cannot run even though its adapters exist, and state what the composition root must connect.
- Adapter boundary translation. Describe how adapters translate between the domain and external technology, using the persistence adapter’s three boundaries as examples.
- Composition root boundary role. Explain why assembly belongs in a composition root and why that module may depend on all the others.
- Bootstrap scanning and JPA discovery. Explain how WriteFlow's Spring Boot entry point makes beans across modules visible and lets Boot discover its JPA entities and repositories without explicit JPA setup.
- Stereotype-Based Bean Discovery. Explain how WriteFlow discovers handlers and adapters as Spring beans without listing each class in the composition root, and why Spring’s default component filters remain enabled.
- Scanning Versus Boundary Enforcement. Distinguish the component scan’s bean-discovery job from the ArchUnit rules’ job of guarding the inner layers.
- Automatic bus handler routing. Trace how the command and query buses find handlers and route messages without explicitly registering each use case. Explain how stereotype-scanned handler beans and their generic message types make this possible.
- Conditional database replacement. Explain when replacing H2 can leave the core unchanged and why the switch may still require work outside the core.
- Assembled request path. Trace how the bootstrap, component scan, auto-configuration, bus registries, and YAML connect WriteFlow so an HTTP request can reach a handler and persist an aggregate.
- Publish transaction atomicity. Explain what changes in the database when a draft is published and why the article update and outbox insertion succeed or fail together.
- Composition root boundaries. Justify keeping concrete-adapter knowledge and framework configuration in the composition root, and distinguish a running assembly from proof that architectural rules hold.
- Two complementary verification gates. Explain why wiring WriteFlow together does not prove it is correct, and distinguish what architectural tests check from what behavioral tests check. State why both must pass.
- Reusable checker test setup. Describe how WriteFlow applies the existing checker rules: each architectural role has a small test class that targets its packages with @AnalyzeClasses, imports the matching checker’s rules with ArchTests.in(...), and supplies the checker’s configuration.
- Reconstitution access guard. Explain why only the persistence adapter may call Article.reconstitute and why an architecture rule, rather than a visibility modifier, enforces that restriction.
- Two complementary test gates. Distinguish what architecture tests and behavioral tests establish, and explain why both must pass. Describe when a design rule needs a custom architecture check.
- Handler orchestration and nonpublication. Explain how handler tests mock ports to verify orchestration, especially that a failed publishing path never dispatches an event.
- The two verification gates. Explain how `mvn clean verify` checks both hexagonal structure and application behavior, and why either kind of failure makes the build fail.
- Change at architectural boundaries. Describe where a new delivery channel, replacement technology, or new business capability lands in the assembled hexagon.
What it builds on
- Assembly time: Wiring the hexagon (chapter 6) · Earlier assembly work introduced wiring the hexagon.
- When listeners execute: The transactional question (chapter 6) · Earlier material addressed when event listeners execute relative to a transaction.
- The outbox pattern: A brief introduction (chapter 6) · Earlier material introduced the outbox pattern.
- CQS in practice (chapter 4) · The distinction between command and query paths.
- What lives inside the domain layer (chapter 3) · The distinction between domain code and outer application layers.
- The recommended approach: validateThenCreate (chapter 3) · The validateThenCreate approach to constructing always-valid domain objects.
- What Either says that the void did not (chapter 4) · Either as a return type that makes failure explicit.
- The Error hierarchy (chapter 4) · The Error hierarchy used to represent failures.
Section by section
Introduction
The introduction explains how WriteFlow’s previously built parts will form a runnable application and why two consumers of one domain event run in different transaction phases.
- A Complete WriteFlow Assembly: Explain why this chapter connects existing WriteFlow components rather than introducing new patterns, and identify the limited wiring needed to make them a runnable whole.
Why it matters: It frames the finished application as an assembly of established components, not a new architectural pattern. - Two Event Consumption Guarantees: Distinguish why the published-article event has a before-commit outbox consumer and an after-commit notification consumer.
Why it matters: The transaction phase determines whether a side effect commits with publication or remains separate from it.
Key terms: vertical slice, composition root, listeners, controller wiring, ArticlePublished, domain event, integration event, outbox, before commit, after commit
9.1 What we are building
This section frames article publishing and reading as two small operations that exercise WriteFlow’s complete hexagon, and identifies when the publish event’s two consumers run.
- Two paths through the hexagon: Describe how publishing an article and reading it back provide the chapter’s command and query paths through a complete hexagon, rather than isolated examples or stubs.
Why it matters: The small feature makes it possible to see how the complete architecture fits together. - Publish event transaction phases: Distinguish when the outbox writer and subscriber notification run in relation to the publish transaction.
Why it matters: The timing difference is essential to reading the event branch in the chapter’s architecture map.
Key terms: command path, query path, full hexagon, outbox writer, subscriber notification, publish transaction, before commit, after commit
9.2 The domain core
This section places WriteFlow’s article rules in a framework-independent domain core that the rest of the application serves.
- Domain Core Responsibility: Explain what belongs in WriteFlow’s domain core and why the surrounding application carries data to and from it rather than defining article rules itself.
Why it matters: Keeping article rules in the domain lets the rest of WriteFlow connect to them without making those rules depend on infrastructure.
Key terms: domain core, Article aggregate, business invariants, innermost ring
9.2.1 Value objects: The smallest always-valid things
This section shows how WriteFlow makes article fields always-valid value objects using private constructors, Either-returning factories, and shared validation helpers.
- Always-valid article value objects: Explain how WriteFlow replaces raw article strings with value objects that cannot be created without validation, and describe what their factories return on success or failure.
Why it matters: Domain code can use these fields without repeatedly checking whether their basic values are valid. - Single and multiple rule validation: Distinguish the single-rule chain from the error-list approach, using ArticleId and Title to explain when WriteFlow uses each and how Title reports failures.
Why it matters: Reporting all of a title’s failures at once lets the caller correct them together. - Shared validation helpers: Explain why WriteFlow places its field-validation helpers in the shared kernel rather than the domain module, and describe the error data they return.
Why it matters: Shared helpers let outer-layer inputs and domain values apply field checks without reversing the dependency boundary.
Key terms: value object, private constructor, validateThenCreate, Either<Error, VO>, Error.ValidationErrors, ArticleId, Title, chain, List, shared-kernel
9.2.2 The status: A two-state lifecycle
This section defines WriteFlow’s two article states and separates naming those states from governing transitions between them.
- Article lifecycle and rule ownership: Explain that an article is either a draft or published, and that the ArticleStatus enum names those states while the aggregate owns the rules for transitioning between them.
Why it matters: It keeps the state names separate from the business rules that govern a change of state.
Key terms: ArticleStatus, draft, published, aggregate, enum
9.2.3 The Article aggregate: Creation, reconstitution, and behaviour
This section explains how the Article aggregate controls creation, restoration from persistence, publishing, and the domain events publishing produces.
- Article aggregate responsibility: Explain why Article is an aggregate root rather than a record: it owns data that must remain consistent together, has identity by id, and controls status changes through behavior.
Why it matters: This explains why changes to an article go through its behavior rather than direct field updates. - Creation and reconstitution factories: Distinguish validateThenCreate from reconstitute, including why loading a persisted article does not repeat creation validation or decide how to handle older data that fails today's rules.
Why it matters: Keeping loading separate from creation prevents today's rules from unexpectedly blocking access to articles that were valid when saved. - Restricted reconstitution access: Justify why reconstitute is public despite bypassing validation, and describe how WriteFlow restricts who may call it without coupling the domain to persistence technology.
Why it matters: The rule allows persistence to restore articles without opening an unchecked construction path to the rest of the application. - Publishing and event ownership: Describe what the Article aggregate does when publishing succeeds and distinguish its decision to record an ArticlePublished event from delivery by the application layer.
Why it matters: The decision that publication occurred stays beside the state change, while event delivery remains outside the domain. - Pending event drain: Trace what popDomainEvents returns and changes, and explain why a second call finds no pending events.
Why it matters: Draining prevents the same pending event from being handed to the bus again if the aggregate remains in memory.
Key terms: aggregate root, identity, state transition, validateThenCreate, reconstitute, creation-time invariant, DRAFT, ArticleStatus, persistence mapper, persistence adapter
9.2.4 The domain event: A primitive-typed, cross-boundary contract
This section explains why ArticlePublished is a primitive-typed event in WriteFlow’s shared kernel rather than a domain-module type.
- Cross-boundary event contract: Explain why ArticlePublished lives in the shared kernel and uses primitives, even though the Article aggregate may decide to raise it.
Why it matters: The event can cross application boundaries without pulling domain dependencies into its consumers.
Key terms: ArticlePublished, shared kernel, domain event, primitives, domain value objects
9.2.5 What the domain guarantees
This section summarizes WriteFlow’s domain guarantees and draws out design principles for keeping domain models valid and independent of infrastructure.
- Article Aggregate Guarantees: Describe how Article creation, publication, event handling, and reconstitution preserve the stated domain guarantees.
Why it matters: These guarantees define what the rest of WriteFlow can rely on when it uses the domain core. - Inside Out Domain Boundary: Explain what building the domain inside-out keeps within the core and what it deliberately leaves outside.
Why it matters: This boundary lets application and infrastructure code use the domain without defining its rules. - Value And Lifecycle Modeling: Explain when to use value objects and where an aggregate’s lifecycle transitions belong.
Why it matters: These choices keep domain meaning and state-changing behavior in the model. - Events And Aggregate Consistency: Justify which changes merit domain events and how an aggregate root protects invariants across child entities.
Why it matters: Selective events avoid needless coupling, while root-controlled changes protect the entire aggregate.
Key terms: Article, ArticlePublished, popDomainEvents, reconstitute, inside-out, domain core, aggregate, value object, guarded public factory, raw primitive
9.3 The ports
This section defines WriteFlow’s input and output ports as implementation-free contracts around the handlers and sealed domain core.
- Input and output port contracts: Distinguish the contracts that bring requests into WriteFlow from those the application uses to reach outward, and describe where those contracts live.
Why it matters: This distinction makes clear which contracts handlers offer and which dependencies adapters fulfill.
Key terms: input ports, output ports, use-case interface, command, query, adapter
9.3.1 Commands and queries carry primitives, not domain types
This section defines commands and queries as self-validating, primitive-carrying messages that keep the input-ports module independent of the domain.
- Primitive-only message boundary: Explain why commands and queries carry primitives rather than domain value objects, using PublishArticleCommand as an example.
Why it matters: This boundary lets adapters use the application’s messages without importing domain types. - Validated message construction: Describe how a command or query rejects malformed primitive input before a handler runs, and why domain value objects still validate when constructed.
Why it matters: Each boundary can enforce its own contract without trusting validation performed by another caller or type. - Command and query roles: Distinguish commands from queries and describe how the section’s example messages fit those roles.
Why it matters: The message’s role makes clear whether a use case changes state or reads it while preserving the same boundary rules.
Key terms: primitives, input-ports module, domain (value) objects, dependency arrow, validated message, validateThenCreate, Either, value-object factory, invariants, command
9.3.2 Input ports: The use cases the application offers
This section defines WriteFlow’s input ports as thin use-case contracts that separate messages and callers from handler implementations.
- Thin input port contracts: Explain how a WriteFlow input port names a capability and specifies its message and result without implementing behavior. Describe why this lets an adapter depend on a use-case interface rather than a handler.
Why it matters: The use-case interface gives callers a stable contract without tying them to the code that performs the work. - Event-triggered operation contracts: Explain why notifying subscribers and recording an integration event use ordinary commanded-operation contracts even though an event triggers them.
Why it matters: It keeps the application’s capability contracts consistent regardless of what triggers an operation.
Key terms: input ports, use-case interface, Architecture Kernel’s handler types, handler, dependency-inversion seam, notify subscribers, record an integration event, commanded operations, assembly detail
9.3.3 The read-side DTO
This section explains why query results use a flat ArticleDTO instead of exposing the Article aggregate.
- Read-side DTO contract: Describe how the query handler reads an Article and returns an ArticleDTO with flat data, including a String status rather than an ArticleStatus.
Why it matters: It lets the read side return useful data without making a boundary record behave like a domain aggregate. - Aggregate boundary protection: Explain why query handlers and output ports must not return Article, and distinguish the read-side ArticleDTO result from the write-side Void result.
Why it matters: Keeping Article inside prevents outside callers from driving its lifecycle through a returned object.
Key terms: ArticleDTO, Article, always-valid rule, String, ArticleStatus, domain entity, application boundary, publish(...), popDomainEvents(), Void
9.3.4 Output ports: What the application needs from the world
Defines the output-port contracts WriteFlow uses for event dispatch, durable integration-event relay, notifications, and persistence while keeping the application independent of adapter technology.
- Output port boundary contract: Explain what output ports represent in WriteFlow and how the application core and adapters relate to them.
Why it matters: This boundary lets the application state its needs without choosing the technology that fulfills them. - In-process domain event dispatch: Trace how raised domain events reach in-process listeners through DomainEventPublisherOutputPort without exposing dispatch technology to the core.
Why it matters: The handler can request event dispatch without becoming coupled to Spring or another dispatcher. - Durable relay and publisher failures: Distinguish the integration-event relay from in-process dispatch and explain what a failure returned by either publisher port means.
Why it matters: These results identify which immediate boundary failed without pretending to report what later listeners did. - Channel-independent notification contract: Explain how NotificationOutputPort specifies notification delivery without binding the application to email, push, or another channel.
Why it matters: A notification channel can change without changing the application's delivery request. - Repository port exception: Explain why ArticleRepository is an output port but sits in the domain module instead of alongside the three @OutputPort interfaces.
Why it matters: The repository's different placement and stereotype still preserve a clear persistence contract for handlers.
Key terms: output ports, OutputPort suffix, @OutputPort, adapter, DomainEventPublisherOutputPort, List<DomainEvent>, Article.popDomainEvents(), shared-kernel DomainEvent, IntegrationEventPublisherOutputPort, ArticlePublished
9.3.5 The contracts are complete
This section completes WriteFlow’s behavior-free contracts and explains how their dependency direction keeps the application boundary clean.
- Behavior-free application contracts: Explain what the completed WriteFlow contracts specify and why they contain no behavior.
Why it matters: Behavior-free interfaces let handlers be developed and tested without running infrastructure. - Port dependency direction: Distinguish input ports from output ports and explain why commands and queries carry primitives rather than domain types.
Why it matters: Choosing ports by dependency direction protects the domain boundary as callers and adapters change. - Focused output port contracts: Explain how an output port’s purpose shapes its return type and why each port should name a single capability.
Why it matters: A focused port makes important failures visible without bundling unrelated adapter responsibilities together.
Key terms: contracts, input ports, output ports, read-side DTO, handlers, dependency direction, input port, output port, commands, queries
9.4 The handlers
This section establishes how WriteFlow handlers connect use-case ports to the domain and adapters, and explains the conventions that keep them encapsulated and transactional.
- Thin handler orchestration: Explain how a handler implements a use-case input port by turning a primitive command into domain input, driving the aggregate, coordinating output ports, and returning Either. Distinguish that orchestration from domain decisions and adapter mechanics.
Why it matters: This boundary keeps business decisions in the domain and technical mechanics in adapters. - Handler visibility and stereotype: Explain why handlers carry @ApplicationService but remain package-private: callers depend on the use-case interface, while the framework wires its implementation.
Why it matters: Callers can rely on the use-case contract without coupling to a particular handler class. - Either-aware transaction rollback: Explain why handlers use the project's @Transactional annotation and why configured Either.left results require rollbackForClassNameWithEither rather than relying on Spring's standard rollback behavior.
Why it matters: An error returned as a value must not accidentally commit work that should be rolled back.
Key terms: handler, application service, use-case input port, output ports, Either, @ApplicationService, package-private, use-case interface, @Transactional, Either.left
9.4.1 Creating a draft: The simplest handler
The create-article handler illustrates parse-then-drive: turn a primitive command into value objects, assemble a draft Article, and persist it, returning the first failure if a step fails.
- Create Handler Flow: Trace how the create handler turns a primitive command into value objects, assembles a draft Article, and persists it. Explain why a failed step stops the chain.
Why it matters: This is the basic handler shape that the following use cases build on. - Creation Event Choice: Explain why the absence of events in WriteFlow's create handler is not a general rule for creation handlers.
Why it matters: It keeps this example's event choice from becoming an unintended rule for other applications.
Key terms: parse-then-drive, primitive command, value objects, Article.validateThenCreate, DRAFT, left, events, creation operations, use cases
9.4.2 Publishing: The handler at the heart of the chapter
This section traces how the publish handler delegates publication to the Article aggregate, saves it, and dispatches its domain events through an output port.
- Publish handler pipeline: Trace the publish handler’s five steps and explain why publication rules remain in the Article aggregate rather than the handler.
Why it matters: This division of work keeps business rules in the domain while the handler coordinates the use case. - Save-before-dispatch ordering: Explain how the handler retains the article after saving so it can drain its events, and why it dispatches them only after a successful save.
Why it matters: The order prevents consumers from receiving an event for a publication that did not succeed. - Publisher port and dispatch result: Describe how the publisher output port hides Spring event dispatch from the handler, and distinguish a successful dispatch call from a listener’s later outcome.
Why it matters: The port keeps listener timing and Spring-specific dispatch outside the handler’s responsibilities.
Key terms: publish handler, Article aggregate, ArticlePublished, Either<Error, Void>, flatMap, popDomainEvents(), save, DomainEventPublisherOutputPort, ApplicationEventPublisher, Right
9.4.3 One event, two phases: The listeners
This section shows how two listeners react to an article publication at different transaction phases, making the outbox write atomic while treating subscriber notification as a best-effort post-commit effect.
- Listener and handler responsibilities: Describe how both listeners react to ArticlePublished by building commands from its primitive values and dispatching them through the CommandBus, while application handlers delegate the resulting work to output ports.
Why it matters: It keeps event reception, application coordination, and external effects in their respective architectural roles. - Atomic before-commit outbox recording: Explain why the outbox intention is recorded before commit and how an outbox failure can roll back the publication.
Why it matters: The system must not commit a published article without atomically recording the intention to publish its integration event. - Post-commit notification trade-off: Distinguish the durability and failure behavior of after-commit subscriber notification from before-commit outbox recording, and justify the phase chosen for each.
Why it matters: Choosing the wrong phase can either lose atomic outbox recording or send a notification about a publication that later rolls back.
Key terms: ArticlePublished, event-listener adapters, CommandBus, RecordIntegrationEventHandler, NotifySubscribersHandler, output ports, BEFORE_COMMIT, outbox, Either.left, peekLeft
9.4.4 Reading: The query handler
This section shows how WriteFlow reads an article through a simple query handler without exposing the aggregate or triggering write-side work.
- Article query read path: Trace how GetArticleByIdHandler parses an id, requests a DTO from the repository, and returns it to the caller. Explain why this path does not mutate state, raise events, or require a second transaction phase.
Why it matters: It keeps a read request straightforward and separate from the work needed when state changes.
Key terms: GetArticleByIdHandler, DTO, aggregate, popDomainEvents
9.4.5 The two paths at runtime
This section traces WriteFlow’s read and publish paths, explains the transaction timing of publish-event consumers, and identifies what the completed application core still cannot do without adapters.
- Straight line query path: Trace how an article-read request becomes a query, reaches its handler through the query bus, and returns an ArticleDTO without firing an event.
Why it matters: It gives you a simple baseline against which to compare the publish path. - Publish event transaction timing: Explain why a publish event has consumers at different transaction phases: the outbox write must share the business transaction, while the subscriber notification is attempted only after commit.
Why it matters: The transaction phase determines which event work is atomic with publishing and which is only attempted afterward. - Save before event dispatch: Justify persisting the article before dispatching its event, rather than dispatching first.
Why it matters: The order keeps event release tied to a successfully saved business change. - Handlers versus domain decisions: Distinguish a handler’s orchestration from business decisions that belong on the aggregate, such as guards, calculations, and state checks.
Why it matters: Keeping decisions in the aggregate preserves domain rules independently of a particular handler. - Completed core and missing edges: Describe what the completed application core can express through ports and why it cannot yet store articles, deliver notifications, or accept HTTP requests.
Why it matters: It separates a complete application core from an application connected to the outside world.
Key terms: GetArticleByIdQuery, query bus, GetArticleByIdHandler, findById, ArticleDTO, domain event, outbox write, AFTER_COMMIT, subscriber notification, save and dispatch order
9.5 Adapters: Wiring the core to the outside world
This section explains how WriteFlow’s adapters connect the completed core to external technology while keeping dependencies pointed inward.
- Driving and driven adapters: Distinguish adapters the core calls through output ports from adapters that send requests into the core through input ports. Explain why WriteFlow needs both before its completed core can interact with a database, external services, or HTTP requests.
Why it matters: The direction of the call tells you which kind of adapter a piece of infrastructure should be. - Inward adapter dependencies: Explain how WriteFlow keeps adapter implementations outside the core: adapters depend inward on ports, output-port implementations need not be public, and assembly-time wiring connects them. Distinguish adapters from the mappers that merely collaborate inside them.
Why it matters: Keeping concrete adapters out of the core preserves the port boundary when real infrastructure is added.
Key terms: driven adapter, driving adapter, output port, input port, @Adapter, ArchUnit, package-private, ArticlePersistenceMapper, ApiMapper
9.5.1 The persistence adapter
This section shows how WriteFlow’s persistence adapter translates between domain contracts and JPA while protecting aggregate invariants and accounting for transaction behavior.
- Separate persistence model: Explain why JpaArticle is separate from the Article aggregate and why the Spring Data repository is not the ArticleRepository port.
Why it matters: Keeping JPA’s requirements out of Article preserves the domain’s guarded behavior. - Guarded creation and reconstitution: Distinguish guarded creation from database reconstitution, and explain how WriteFlow restricts access to the validation-free path.
Why it matters: Rehydrating stored data must not give ordinary application code an unchecked way to create articles. - Adapter boundary translations: Describe the three translations performed by the adapter that implements ArticleRepository.
Why it matters: The adapter lets handlers use the domain-facing port without handling JPA types or persistence-specific outcomes. - Deferred failures and real transactions: Explain why the adapter may not convert every database constraint failure into Either.Left, and state what the example’s real transaction provides.
Why it matters: A successful adapter call does not guarantee that a later commit will succeed or return a typed persistence error.
Key terms: ArticleRepository, JpaArticle, Article aggregate, Spring Data, validateThenCreate, reconstitute, toDomainEntity, ReconstitutionAccessArchitectureTest, DataAccessException, Either left
9.5.2 The transactional outbox
Explains how WriteFlow records a pending integration event atomically with article publication, while keeping domain, external, and storage representations separate.
- Atomic outbox recording: Explain the dual-write problem and how WriteFlow avoids it by saving an outbox row in the same transaction that publishes the article, rather than sending the event immediately.
Why it matters: Recording intent in the same transaction prevents a crash between publication and event recording from leaving one without the other. - Three event representations: Distinguish the in-process domain event, the external integration-event contract, and the outbox storage row, and explain why they remain separate.
Why it matters: Keeping these forms separate lets business meaning, the public contract, and relay storage evolve independently. - Outbox failure and rollback: Trace how failures during the outbox adapter call affect the publish transaction, and distinguish them from failures detected only at commit.
Why it matters: Both immediate adapter failures and deferred commit failures must prevent a partial publication.
Key terms: dual-write problem, transactional outbox, BEFORE_COMMIT, outbox row, ArticlePublished, ArticlePublishedIntegrationEvent, OutboxMessage, domain event, integration event, Left
9.5.3 The event bridge and the notification fake
This section contrasts a real transactional event bridge with a fake notification adapter to show how ports support substitution and how prototypes can focus implementation effort.
- Transactional domain event bridge: Trace how SpringDomainEventPublisher dispatches drained domain events and explain why it lives in the persistence module.
Why it matters: The bridge makes event dispatch part of the transactional publish path rather than an unrelated notification step. - Interchangeable notification adapters: Explain why WriteFlow can use a fake notification adapter instead of a production email adapter without changing the core.
Why it matters: A shared port lets the application keep the same contract while its external implementation changes. - Prototype adapter selection: Justify which adapters WriteFlow implements fully and which it stubs when demonstrating the publish path.
Why it matters: This choice preserves the behavior the example is meant to demonstrate without burying it under unrelated infrastructure.
Key terms: DomainEventPublisherOutputPort, SpringDomainEventPublisher, Spring application event, BEFORE_COMMIT/AFTER_COMMIT, NotificationOutputPort, EmailNotificationAdapter, Liskov-substitutability, assembly-time decision, outbox, publish path
9.5.4 The REST driving adapter
The section shows how WriteFlow’s REST adapter translates HTTP requests into core invocations and maps their outcomes back to HTTP without putting business logic in the controller.
- HTTP boundary validation: Explain why HTTP request records need not be always-valid and where this example validates command inputs.
Why it matters: It keeps untrusted HTTP data and domain validity in their proper layers. - REST controller translation pipeline: Trace how a REST endpoint turns an HTTP request into a core invocation and then an HTTP response.
Why it matters: This is the boundary that lets HTTP drive the application without owning its business logic. - Generated identity and command results: Explain how the controller can return a new article ID while CreateArticleCommand still returns no success value, and why WriteFlow generates the ID server-side.
Why it matters: It resolves an apparent conflict between returning a useful HTTP response and keeping commands result-free. - Exhaustive business error mapping: Explain how ApiErrorHandler keeps the mapping from business errors to HTTP statuses complete as errors are added.
Why it matters: A new business failure cannot silently go without an HTTP mapping. - Expected and unexpected error channels: Distinguish how the REST adapter handles expected core failures from failures that never enter its Either pipeline.
Why it matters: Keeping the two channels separate makes deliberate use-case failures explicit without confusing them with broken requests or configuration.
Key terms: request records, always-valid, validateThenCreate, driving adapter, input port, command bus, query bus, mapLeft, fold, server-generated id
9.5.5 The edges are built, nothing is connected
This section explains why WriteFlow’s completed adapters do not yet make a running application, and how translation and port design keep the core separate from infrastructure.
- The assembly gap: Explain why WriteFlow cannot run even though its adapters exist, and state what the composition root must connect.
Why it matters: Having all the pieces in code is different from having an application that runs. - Adapter boundary translation: Describe how adapters translate between the domain and external technology, using the persistence adapter’s three boundaries as examples.
Why it matters: Recognizing each translation helps keep technology-specific concerns at the edge rather than in handlers. - Infrastructure substitution through ports: Explain why keeping the persistence model separate and binding implementations at assembly protects the core from infrastructure changes.
Why it matters: These boundaries leave room to replace infrastructure without rewriting the application’s center.
Key terms: composition root, ports, adapters, command and query buses, adapter layer, types, errors, optionality, Either left, NotFound
9.6 Assembly: The composition root
This section explains why WriteFlow needs a composition root to connect its independent modules without breaking hexagonal boundaries.
- Composition root boundary role: Explain why assembly belongs in a composition root and why that module may depend on all the others.
Why it matters: It explains how WriteFlow can become a running application without making its inner layers depend on outer ones.
Key terms: composition root, spring-boot-assembly module, hexagonal architecture
9.6.1 The bootstrap class
WriteFlow's minimal Spring Boot entry point lets base-package scanning and auto-configuration assemble the application's beans and JPA infrastructure without manual setup.
- Bootstrap scanning and JPA discovery: Explain how WriteFlow's Spring Boot entry point makes beans across modules visible and lets Boot discover its JPA entities and repositories without explicit JPA setup.
Why it matters: It explains why the entry point stays small even though WriteFlow includes persistence and several other modules.
Key terms: @SpringBootApplication, base-package scan, JPA auto-configuration, composition root
9.6.2 Wiring beans by stereotype, not by name
WriteFlow’s composition root discovers beans by architectural role while ArchUnit, not component scanning, enforces the boundaries around those roles.
- Stereotype-Based Bean Discovery: Explain how WriteFlow discovers handlers and adapters as Spring beans without listing each class in the composition root, and why Spring’s default component filters remain enabled.
Why it matters: Role-based discovery avoids maintaining a list of individual beans as the application grows. - Scanning Versus Boundary Enforcement: Distinguish the component scan’s bean-discovery job from the ArchUnit rules’ job of guarding the inner layers.
Why it matters: A class being discoverable as a bean does not prove that it respects the architecture’s dependency boundaries. - Package-Private Adapter Classes: Justify why stereotype-based discovery lets WriteFlow keep its adapters package-private.
Why it matters: Discovery through the container preserves the adapter’s limited visibility without preventing its instantiation.
Key terms: component scan, Architecture Kernel stereotypes, @ApplicationService, @Adapter, @DomainService, Spring’s default component filters, ArchUnit rules, inner layers, framework coupling, architectural stereotypes
9.6.3 Standing up the buses and registering handlers
This section shows how the composition root creates command and query buses that discover typed handlers automatically, and why their configuration is kept separate from component scanning.
- Automatic bus handler routing: Trace how the command and query buses find handlers and route messages without explicitly registering each use case. Explain how stereotype-scanned handler beans and their generic message types make this possible.
Why it matters: You can add a use case without maintaining a separate list of bus registrations. - Separate assembler responsibilities: Explain why the bus assembler is separate from the application assembler and whether the split changes behavior.
Why it matters: Keeping each configuration class focused makes a growing composition root easier to read.
Key terms: CommandBus, QueryBus, Registry, ApplicationContext, CommandHandler, QueryHandler, CommandQueryBusAssembler, ApplicationAssembler, composition root, component-scan policy
9.6.4 Profile and runtime configuration
This section places runtime settings outside Java code and explains the conditions and limits of replacing WriteFlow’s H2 database.
- Runtime settings outside Java: Describe where WriteFlow keeps the database, transaction manager, and HTTP settings needed to run the assembled application.
Why it matters: Assembly includes runtime configuration, not just connecting Java components. - Conditional database replacement: Explain when replacing H2 can leave the core unchanged and why the switch may still require work outside the core.
Why it matters: The boundary can protect the core without making a production database migration effortless.
Key terms: application.yaml, transaction manager, HTTP settings, H2, persistence adapter, repository port’s contract
9.6.5 The application is whole
The section shows the assembled WriteFlow application running, uses its API and database consoles to observe the publish path, and explains the boundaries that the composition root must preserve.
- Assembled request path: Trace how the bootstrap, component scan, auto-configuration, bus registries, and YAML connect WriteFlow so an HTTP request can reach a handler and persist an aggregate.
Why it matters: This is the point where the separate architectural pieces become a running application. - Manual publish walkthrough: Describe how Swagger UI and the H2 console let a reader drive and inspect the create-and-publish path without client code or a separate database tool.
Why it matters: The two conveniences make the request and its persisted effects visible without adding code to the core. - Publish transaction atomicity: Explain what changes in the database when a draft is published and why the article update and outbox insertion succeed or fail together.
Why it matters: The database observations make the publish operation's all-or-nothing behavior concrete. - Composition root boundaries: Justify keeping concrete-adapter knowledge and framework configuration in the composition root, and distinguish a running assembly from proof that architectural rules hold.
Why it matters: A working demo shows that components connect, while protected boundaries and verification show that they connect in the intended way.
Key terms: bootstrap class, stereotype-filtered scan, bus assemblers, output ports, H2, Swagger UI, Springdoc, H2 web console, 201 Created, DRAFT
9.7 Verification: Proving the hexagon holds
This section explains why WriteFlow needs both architectural and behavioral tests to verify that its assembled hexagon has the right structure and works correctly.
- Two complementary verification gates: Explain why wiring WriteFlow together does not prove it is correct, and distinguish what architectural tests check from what behavioral tests check. State why both must pass.
Why it matters: A working application can still violate its architecture, and a well-structured one can still behave incorrectly.
Key terms: architectural tests, behavioral tests, composition root, dependency rule
9.7.1 Reusing the chapter 7 checker library
This section shows how WriteFlow reuses the chapter 7 ArchUnit checker library to verify its architectural roles without rewriting the rules.
- Reusable checker test setup: Describe how WriteFlow applies the existing checker rules: each architectural role has a small test class that targets its packages with @AnalyzeClasses, imports the matching checker’s rules with ArchTests.in(...), and supplies the checker’s configuration.
Why it matters: The same architecture rules can be applied to WriteFlow without maintaining another copy of them. - Adapter checker package coverage: Explain why AdaptersArchitectureTest targets four packages and how one AdapterChecker covers them.
Why it matters: The adapter test must include all adapter packages for its checker to cover both sides of the hexagon.
Key terms: ArchUnit, archunit-hexagonal, @AnalyzeClasses, ArchTests.in(...), HexagonalArchitectureConfig, AdaptersArchitectureTest, AdapterChecker, driven and driving adapter
9.7.2 Extending the library with a project-specific rule
The section shows how WriteFlow adds a project-specific ArchUnit rule to its reusable architecture checks to restrict access to Article.reconstitute.
- Reconstitution access guard: Explain why only the persistence adapter may call Article.reconstitute and why an architecture rule, rather than a visibility modifier, enforces that restriction.
Why it matters: The rule makes an important boundary enforceable even though Java visibility cannot express it across these modules. - Project-specific rule implementation: Distinguish the reusable checker classes from WriteFlow’s bespoke reconstitution rule, and describe how that rule handles production and test callers.
Why it matters: Teams can extend shared architecture checks with enforceable rules for decisions specific to their application.
Key terms: Article.reconstitute, persistence-adapter package, architecture rule, validateThenCreate, publish state machine, ArchUnit, ClassFileImporter, ArchRuleDefinition, ArchTests.in(...), DO_NOT_INCLUDE_TESTS
9.7.3 Behavioral tests: Applying the chapter 8 recipes
This section applies behavioral test recipes to each WriteFlow component and explains why behavioral and architecture tests are both needed.
- Two complementary test gates: Distinguish what architecture tests and behavioral tests establish, and explain why both must pass. Describe when a design rule needs a custom architecture check.
Why it matters: Passing one kind of test does not establish what the other kind checks. - Pure aggregate behavior tests: Describe how ArticleTest tests the domain aggregate without mocks and which invariants it makes executable.
Why it matters: Direct tests turn the aggregate’s domain guarantees into observable assertions. - Handler orchestration and nonpublication: Explain how handler tests mock ports to verify orchestration, especially that a failed publishing path never dispatches an event.
Why it matters: A negative interaction assertion catches an event dispatched despite a failed save or missing article. - Adapter boundary behavior tests: Describe what the persistence adapter and REST controller tests assert at their respective boundaries.
Why it matters: These assertions show that errors and invalid requests are handled at the boundary rather than leaking into the core.
Key terms: architecture tests, behavioral tests, ArchUnit, ArticleTest, no-mocks recipe, ArticlePublished, reconstitute, Mockito-with-BDD recipe, PublishArticleHandlerTest, never()
9.7.4 The whole gate
The section shows how one build verifies both WriteFlow’s architecture and behavior, then explains how its boundaries help a larger system absorb change.
- The two verification gates: Explain how `mvn clean verify` checks both hexagonal structure and application behavior, and why either kind of failure makes the build fail.
Why it matters: A passing build gives the team evidence that both the design boundaries and the behavior still hold. - Change at architectural boundaries: Describe where a new delivery channel, replacement technology, or new business capability lands in the assembled hexagon.
Why it matters: Putting changes at the intended seams helps the domain retain its shape as the system grows. - Homes for consequential decisions: Explain where the section places transaction-phase, entity-identity, and event decisions, and why giving each a home matters.
Why it matters: A clear home for each decision makes its ownership easier to find as the codebase grows. - The single-hexagon boundary: State what WriteFlow’s completed example does and does not cover across service boundaries, including the limit of its transactional outbox.
Why it matters: This boundary prevents a reader from mistaking a recorded outbox event for delivered inter-service communication.
Key terms: mvn clean verify, architecture tests, unit tests, executable specification, ArchUnit rules, driving adapter, driven adapter, output port, composition root, use-case port
9.8 Summary
Where this is used later
- Event-driven integration (chapter 10) · Provides the distinction between recording an event for later dispatch and delivering it to consumers.
- What crosses the boundary: Requests and facts (chapter 10) · Distinguishing facts that cross a service boundary from what the single-hexagon example has implemented.
Concepts explained in this chapter
- composition rootA composition root is the application’s designated location for constructing components and wiring their dependencies.
- outbox patternA pattern that stores a message in the same transaction as a business change so it can be published reliably afterward.
- aggregate rootThe entity at the head of an aggregate that owns its consistency boundary and controls state changes within it.
- adapterAn adapter that connects an application to an external service through an API.
- handlerA handler is an application component that processes a request and coordinates the interactions needed to fulfill it.
- persistence modelA persistence model is a representation of data shaped for storage and retrieval by a persistence mechanism.
- value objectA value object is an immutable domain object defined by its attributes rather than identity and responsible for enforcing the constraints of the concept it represents.
- hexagonal architectureAn application design pattern that isolates the application core behind ports and connects external technologies through adapters.
- reconstitutionThe reconstruction of a previously persisted domain object from its stored state.
- REST controllerAn adapter that accepts REST requests and translates them into calls to application input ports.
- mapperA mapper is a component or procedure that converts data between distinct representations.
- persistence adapterAn adapter that implements persistence contracts and translates between domain objects and storage technology.
- architectural testingArchitectural testing automatically checks whether a codebase conforms to specified structural and dependency rules.
- commandA command object encapsulates data representing a requested application operation.
- queryA query is a request that retrieves information without changing application or domain state.
- outbound portAn application-facing boundary that declares a service the application requires from an external system.
- domain eventAn immutable representation of a significant occurrence expressed in the language of the business domain.
- component scanningA Spring mechanism that scans specified packages for eligible classes and registers them as application-context beans.
- driven adapterAn adapter that implements an output port and translates application requests into interactions with an external system.
- driving adapterA primary adapter translates an external trigger into a call to an application input port.
- architectural ruleAn architectural rule is a constraint that specifies an allowed or required structural property of a software system.
- primary portAn interface exposing an application operation that an external caller can invoke.
- handler registryA mapping from operation types or other keys to the handlers responsible for processing them.
- application coreThe central part of an application containing its domain and application logic while remaining independent of external technologies.
- integration eventA published event contract representing an occurrence in a stable form suitable for consumers across system boundaries.
- dual-write problemThe dual-write problem is the consistency failure that occurs when one operation must atomically update a database and publish a message through separate systems.
- validatethencreateA construction pattern that validates all required constraints before creating an object and returns validation errors instead of an invalid object.
- invariantA condition that must remain true for a domain object or business state to be valid.
- application serviceA service that coordinates an application use case and its domain operations without containing infrastructure concerns.
- event handlerA component that reacts to a published event by invoking additional behavior.
- dependency inversionA design principle stating that high-level and low-level components should depend on abstractions rather than concrete implementation details.
- use caseA use case is an application operation that coordinates domain rules to accomplish a specific user or system goal.
These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.
