Driving ports, driven ports and the composition root
Differentiate driving primary ports from driven secondary ports and orchestrate dependency injection at the application composition root.
Contentsand lesson path
On this page
- The Two Sides of the Hexagon: Driving vs. Driven Ports
- Driving Ports (Primary / Inbound Boundary)
- Driven Ports (Secondary / Outbound Boundary)
- The Composition Root: Assembling the Hexagon
Lessons of Clean & Hexagonal Architecture
- Which way dependencies point: layers, the MVC family, ports and adapters Concept · 25 min
- Driving ports, driven ports and the composition root Concept · 20 min
- Moving a layered service to hexagonal Lab · 30 min
- Testing the core with in-memory adapters Lab · 20 min
- When a plain layered design is the better choice Concept · 10 min
- Dependency rule check Knowledge check · 6 questions
What you will learn
- Restructure a service into domain core, application ports and infrastructure adapters with all dependencies pointing inward.
Prerequisites: Software Design Principles
01. The Two Sides of the Hexagon: Driving vs. Driven Ports
In Hexagonal Architecture, a Port is an application-defined boundary interface that defines a conversational protocol between the application core and the outside world. Ports are completely agnostic of technology, protocol, and transport mechanics. A port never mentions HTTP, SQL, JSON, gRPC, or AMQP; it speaks strictly in terms of domain entities, value objects, and application commands.
Alistair Cockburn divided ports into two fundamental categories based on the direction of interaction initiation: Driving (Primary) ports and Driven (Secondary) ports.
Understanding this distinction is the cornerstone of designing clean, testable application boundaries.
02. Driving Ports (Primary / Inbound Boundary)
A Driving Port (also known as an Inbound or Primary Port) represents an entry point into the application. It defines an interface through which external actors trigger workflows and use cases inside the core.
- Who calls it? External drivers invoke driving ports. Drivers include HTTP REST controllers, GraphQL resolvers, CLI commands, cron job schedulers, and asynchronous message queue consumers.
- Who defines it? The application layer defines the driving port interface (e.g.,
SubmitOrderUseCasePortorRegisterUserCommandPort). - Who implements it? An application service or use case interactor within the core implements the interface, executing business logic and coordinating domain entities.
Because driving ports are owned by the application layer, the core dictates exactly how external actors are allowed to trigger its operations. An HTTP controller does not decide how an order is created; it merely translates an incoming JSON request into a command object and delegates it to the driving port.
03. Driven Ports (Secondary / Outbound Boundary)
A Driven Port (also known as an Outbound or Secondary Port) represents an interface through which the application core communicates with external infrastructure to fulfill a use case.
- Who calls it? The application use case inside the core calls the driven port to perform persistence, emit notifications, or query external services.
- Who defines it? The application core defines the driven port interface in terms of domain needs (e.g.,
OrderRepositoryPort,PaymentGatewayPort,SmsNotificationPort). - Who implements it? An infrastructure adapter located in the outer ring implements the interface (e.g.,
PostgresOrderRepository,StripePaymentAdapter,TwilioSmsAdapter).
The Architectural Miracle of Dependency Inversion Driven ports are the mechanism by which the Dependency Inversion Principle is realized in system architecture. While control flow travels outward from the application service to the database adapter during execution, source code dependencies point in the opposite direction. The application core owns the interface; the infrastructure adapter depends on that interface. The database adapter cannot compile without the core, but the core compiles with zero dependencies on database libraries, ORMs, or network drivers.
Port Granularity: Role Interfaces vs. Header Interfaces
A common anti-pattern in early hexagonal designs is the "Header Interface"—creating an interface that blindly mirrors all methods of an infrastructure database class. If an ORM repository exposes thirty CRUD and query methods, copying all thirty into a generic GenericRepositoryPort couples use cases to unnecessary capabilities.
Architects should instead design Role Interfaces according to the Interface Segregation Principle. A role interface is tailored strictly to the specific consumer use case. If the SettleInvoiceService only needs to find an invoice by ID and save it, the port should declare only those two operations. A separate reporting use case can declare its own query-focused port. Multiple role ports can even be implemented by the same concrete database adapter class behind the scenes without polluting individual use case boundaries.
04. The Composition Root: Assembling the Hexagon
If the application core knows nothing about concrete adapters, and adapters only implement abstract ports, how does the application actually run? Where do adapters get instantiated, and who injects them into use cases?
The answer is the Composition Root. As defined by Mark Seemann, the Composition Root is the unique, centralized location in an application where the entire dependency graph is composed and wired together. It is situated at the absolute entry point of the executable process (e.g., main.py, index.ts, or the application bootstrap module).
The Composition Root Lifecycle During application startup, the Composition Root executes a disciplined sequence:
-
- Reads environment variables and configuration files.
-
- Instantiates infrastructure adapters: database connection pools, HTTP clients, and message broker publishers.
-
- Instantiates application services, injecting the driven adapters into use case constructors.
-
- Instantiates driving adapters (controllers, routers, event listeners), injecting the use cases into controller constructors.
-
- Starts the HTTP server or begins polling message queues.
Graceful Shutdown and Resource Lifecycle Management
In addition to assembling the object graph at startup, the Composition Root is responsible for orchestrating graceful process termination when receiving operating system signals (SIGTERM or SIGINT). In containerized environments like Kubernetes, rolling updates terminate pods routinely.
When a termination signal arrives, the Composition Root intercepts the event, instructs driving adapters (HTTP listeners) to stop accepting new inbound connections, allows in-flight use cases to complete within a bounded grace window, and systematically drains and closes driven infrastructure adapters (closing database connection pools, flushing batch telemetry buffers, and disconnecting message broker channels). Centralizing shutdown inside the Composition Root guarantees that domain use cases never harbor custom thread cleanup or connection management logic.
By isolating all dependency injection, framework annotations, and adapter instantiation to the Composition Root, the rest of the application remains pristine and modular.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.