Course contentsShow
← Software Engineering
Lesson 1266 of 1,93338. Layered and Modular ArchitectureFree lesson

Primary and Secondary Ports

Distinguish between driving ports (UI, API) and driven ports (database, messaging) in your architecture.

Primary and Secondary Ports

You'll learn how to categorize your application's ports into those that drive your system (primary) and those your system drives (secondary).

The Two Directions of Communication

In the Ports and Adapters pattern, not all ports are created equal. They flow in different directions based on who initiates the interaction:

Primary Ports (driving ports) are entry points where external actors initiate requests into your application. Someone or something calls your code. Examples include:

  • REST API endpoints
  • GraphQL resolvers
  • Command-line interfaces
  • Web UI controllers
  • Message queue consumers

Secondary Ports (driven ports) are exit points where your application initiates calls out to external systems. Your code calls something else. Examples include:

  • Database repositories
  • External API clients
  • File system access
  • Email services
  • Message publishers

The Control Flow Distinction

Think of your application as the center of a wheel. Primary ports are where control enters (spokes coming in), and secondary ports are where control leaves (spokes going out).

A web request hitting your API? That's primary—the HTTP server drives your app. Your app querying a database? That's secondary—your app drives the database.

This distinction matters for testing: primary ports are where you simulate user actions, secondary ports are what you mock or stub.

Why This Matters

Understanding this difference helps you:

  • Design clean interfaces with clear responsibilities
  • Know which side to mock in tests (secondary)
  • Identify proper dependency directions
  • Keep your core logic independent of both UI and infrastructure

Key Takeaway: Primary ports handle incoming requests that drive your application; secondary ports handle outgoing calls your application makes to external services—the distinction is about control flow direction, not technical complexity.