Domain-Driven Hexagon
Check out my other repositories:
- Backend best practices - Best practices, tools and guidelines for backend development.
- System Design Patterns - list of topics and resources related to distributed systems, system design, microservices, scalability and performance, etc.
- Full Stack starter template - template for full stack applications based on TypeScript, React, Vite, ChakraUI, tRPC, Fastify, Prisma, zod, etc.
The main emphasis of this project is to provide recommendations on how to design software applications. This readme includes techniques, tools, best practices, architectural patterns and guidelines gathered from different sources.
Code examples are written using NodeJS, TypeScript, NestJS framework and Slonik for the database access.
Patterns and principles presented here are framework/language agnostic. Therefore, the above technologies can be easily replaced with any alternative. No matter what language or framework is used, any application can benefit from principles described below.
Note: code examples are adapted to TypeScript and frameworks mentioned above.
(Implementations in other languages will look differently)
Everything below is provided as a recommendation, not a rule. Different projects have different requirements, so any pattern mentioned in this readme should be adjusted to project needs or even skipped entirely if it doesn't fit. In real world production applications, you will most likely only need a fraction of those patterns depending on your use cases. More info in this section.
- Domain-Driven Hexagon
- Architecture - Pros - Cons
- Diagram
- Modules
- Application Core
- Application layer
- Domain Layer
- Interface Adapters
- Infrastructure layer
- Other recommendations
- Additional resources
Architecture
This is an attempt to combine multiple architectural patterns and styles together, such as:
- Domain-Driven Design (DDD)
- Hexagonal (Ports and Adapters) Architecture
- Secure by Design
- Clean Architecture
- Onion Architecture
- SOLID Principles
- Software Design Patterns
And many others (more links below in every chapter).
Before we begin, here are the PROS and CONS of using a complete architecture like this:
Pros
- Independent of external frameworks, technologies, databases, etc. Frameworks and external resources can be plugged/unplugged with much less effort.
- Easily testable and scalable.
- More secure. Some security principles are baked in design itself.
- The solution can be worked on and maintained by different teams, without stepping on each other's toes.
- Easier to add new features. As the system grows over time, the difficulty in adding new features remains constant and relatively small.
- If the solution is properly broken apart along bounded context lines, it becomes easy to convert pieces of it into microservices if needed.
Cons
-
This is a sophisticated architecture which requires a firm understanding of quality software principles, such as SOLID, Clean/Hexagonal Architecture, Domain-Driven Design, etc. Any team implementing such a solution will almost certainly require an expert to drive the solution and keep it from evolving the wrong way and accumulating technical debt.
-
Some practices presented here are not recommended for small-medium sized applications with not a lot of business logic. There is added up-front complexity to support all those building blocks and layers, boilerplate code, abstractions, data mapping etc. Thus, implementing a complete architecture like this is generally ill-suited to simple CRUD applications and could over-complicate such solutions. Some principles which are described below can be used in smaller sized applications, but must be implemented only after analyzing and understanding all pros and cons.
Diagram
Diagram is mostly based on this one + others found online
In short, data flow looks like this (from left to right):
- Request/CLI command/event is sent to the controller using plain DTO;
- Controller parses this DTO, maps it to a Command/Query object format and passes it to an Application service;
- Application service handles this Command/Query; it executes business logic using domain services and entities/aggregates and uses the infrastructure layer through ports(interfaces);
- Infrastructure layer maps data to a format that it needs, retrieves/persists data from/to a database, uses adapters for other I/O communications (like sending an event to an external broker or calling external APIs), maps data back to domain format and returns it back to Application service;
- After the Application service finishes doing its job, it returns data/confirmation back to Controllers;
- Controllers return data back to the user (if application has presenters/views, those are returned instead).
Each layer is in charge of its own logic and has building blocks that usually should follow a Single-responsibility principle when possible and when it makes sense (for example, using Repositories
only for database access, using Entities
for business logic, etc.).
Keep in mind that different projects can have more or less steps/layers/building blocks than described here. Add more if the application requires it, and skip some if the application is not that complex and doesn't need all that abstraction.
General recommendation for any project: analyze how big/complex the application will be, find a compromise and use as many layers/building blocks as needed for the project and skip ones that may over-complicate things.
More in details on each step below.
Modules
This project's code examples use separation by modules (also called components). Each module's name should reflect an important concept from the Domain and have its own folder with a dedicated codebase. Each business use case inside that module gets its own folder to store most of the things it needs (this is also called Vertical Slicing). It's easier to work on things that change together if those things are gathered relatively close to each other. Think of a module as a "box" that groups together related business logic.
Using modules is a great way to encapsulate parts of highly cohesive business domain rules.
Try to make every module independent and keep interactions between modules minimal. Think of each module as a mini application bounded by a single context. Consider module internals private and try to avoid direct imports between modules (like importing a class import SomeClass from '../SomeOtherModule'
) since this creates tight coupling and can turn your code into a spaghetti and application into a big ball of mud.
Few advices to avoid coupling:
- Try not to create dependencies between modules or use cases. Instead, move shared logic into a separate files and make both depend on that instead of depending on each other.
- Modules can cooperate through a mediator or a public facade, hiding all private internals of the module to avoid its misuse, and giving public access only to certain pieces of functionality that meant to be public.
- Alternatively modules can communicate with each other by using messages. For example, you can send commands using a commands bus or subscribe to events that other modules emit (more info on events and commands bus below).
This ensures loose coupling, refactoring of a module internals can be done easier because outside world only depends on module's public interface, and if bounded contexts are defined and designed properly each module can be easily separated into a microservice if needed without touching any domain logic or major refactoring.
Keep your modules small. You should be able to rewrite a module in a relatively short period of time. This applies not only to modules pattern, but to software development in general: objects, functions, microservices, processes, etc. Keep them small and composable. This is incredibly powerful in a constantly changing environments of software development, since when your requirements change, changing small modules is much easier than changing a big program. You can just delete a module and rewrite it from scratch in a matter of days. This idea is further described in this talk: Greg Young - The art of destroying software.
Code Examples:
- Check src/modules directory structure.
- src/modules/user/commands - "commands" directory in a user module includes business use cases (commands) that a module can execute, each with its own Vertical Slice.
Read more:
- Modular programming: Beyond the spaghetti mess.
- What are Modules in Domain Driven Design?
- How to Implement Vertical Slice Architecture
Each module consists of layers described below.
Application Core
This is the core of the system which is built using DDD building blocks:
Domain layer:
- Entities
- Aggregates
- Domain Services
- Value Objects
- Domain Errors
Application layer:
- Application Services
- Commands and Queries
- Ports
Note: different implementations may have slightly different layer structures depending on applications needs. Also, more layers and building blocks may be added if needed.
Application layer
Application Services
Application Services (also called "Workflow Services", "Use Cases", "Interactors", etc.) are used to orchestrate the steps required to fulfill the commands imposed by the client.
Application services:
- Typically used to orchestrate how the outside world interacts with your application and performs tasks required by the end users;
- Contain no domain-specific business logic;
- Operate on scalar types, transforming them into Domain types. A scalar type can be considered any type that's unknown to the Domain Model. This includes primitive types and types that don't belong to the Domain;
- Uses ports to declare dependencies on infrastructural services/adapters required to execute domain logic (ports are just interfaces, we will discuss this topic in details below);
- Fetch domain
Entities
/Aggregates
(or anything else) from database/external APIs (through ports/interfaces, with concrete implementations injected by the DI library); - Execute domain logic on those
Entities
/Aggregates
(by invoking their methods); - In case of working with multiple
Entities
/Aggregates
, use aDomain Service
to orchestrate them; - Execute other out-of-process communications through Ports (like event emits, sending emails, etc.);
- Services can be used as a
Command
/Query
handlers; - Should not depend on other application services since it may cause problems (like cyclic dependencies);
One service per use case is considered a good practice.
What are "Use Cases"?
wiki:
In software and systems engineering, a use case is a list of actions or event steps typically defining the interactions between a role (known in the Unified Modeling Language as an actor) and a system to achieve a goal.
Use cases are, simply said, list of actions required from an application.
Example file: create-user.service.ts
More about services:
Commands and Queries
This principle is called Command–Query Separation(CQS). When possible, methods should be separated into Commands
(state-changing operations) and Queries
(data-retrieval operations). To make a clear distinction between those two types of operations, input objects can be represented as Commands
and Queries
. Before DTO reaches the domain, it's converted into a Command
/Query
object.
Commands
Command
is an object that signals user intent, for example CreateUserCommand
. It describes a single action (but does not perform it).
Commands
are used for state-changing actions, like creating new user and saving it to the database. Create, Update and Delete operations are considered as state-changing.
Data retrieval is responsibility of Queries
, so Command
methods should not return business data.
Some CQS purists may say that a Command
shouldn't return anything at all. But you will need at least an ID of a created item to access it later. To achieve that you can let clients generate a UUID (more info here: CQS versus server generated IDs).
Though, violating this rule and returning some metadata, like ID
of a created item, redirect link, confirmation message, status, or other metadata is a more practical approach than following dogmas.
Note: Command
is similar but not the same as described here: Command Pattern. There are multiple definitions across the internet with similar but slightly different implementations.
To execute a command you can use a Command Bus
instead of importing a service directly. This will decouple a command Invoker from a Receiver, so you can send your commands from anywhere without creating coupling.
Avoid command handlers executing other commands in this fashion: Command → Command. Instead, use events for that purpose, and execute next commands in a chain in an Event handler: Command → Event → Command.
Example files:
- create-user.command.ts - a command Object
- create-user.message.controller.ts - controller executes a command using a command bus. This decouples it from a command handler.
- create-user.service.ts - a command handler.
Read more:
- [What is a command bus and why should you use