{
  "id": "hexagonal-architecture",
  "title": "Hexagonal Architecture",
  "lang": "en",
  "source_lang": "en",
  "summary": "Hexagonal architecture organizes software around an application core whose ports and adapters isolate business behavior from external technologies and support independent testing.",
  "category": "computer-science",
  "subcategory": "software",
  "type": "concept",
  "aliases": [
    "Ports and adapters architecture",
    "Ports-and-adapters architecture"
  ],
  "generated_at": "2026-11-04",
  "model": "pro/gpt-6.1-sol",
  "url": "https://aiwiki.page/en/hexagonal-architecture/",
  "translations": {
    "zh-Hans": {
      "url": "https://aiwiki.page/zh/hexagonal-architecture/",
      "json": "https://aiwiki.page/zh/hexagonal-architecture.json"
    }
  },
  "sections": [
    {
      "heading": "",
      "text": "Hexagonal architecture is a software architecture pattern that separates an application's essential behavior from the technologies through which users, external systems, and infrastructure interact with it. The application communicates across its boundary through ports, which describe purposeful interactions, and adapters, which translate those interactions into particular technologies or external interfaces. Its central aim is to let application behavior be developed and tested without requiring a particular user interface, database, or deployment environment."
    },
    {
      "heading": "Origin and terminology",
      "text": "Alistair Cockburn described hexagonal architecture in 2005 under the alternative name ports and adapters. The proposal addressed a recurring problem: business logic becoming entangled with user-interface code or persistence mechanisms, making an application difficult to test independently of those mechanisms.\n\nThe hexagon is a diagrammatic convention, not a requirement for six components, six layers, or six interfaces. Its shape provides room to draw multiple kinds of external interaction without suggesting that an application has only a top, a middle, and a bottom. The significant distinction is between the inside, where application behavior resides, and the outside, where technology-specific interactions occur.\n\nThe architecture is not tied to a particular programming language, framework, or deployment model. It can organize a single executable, a modular application, or an individual service."
    },
    {
      "heading": "Core structure",
      "text": "Application core\n\nThe application core contains behavior that should remain meaningful when external technologies change. Depending on the system, this includes business rules, domain objects, validation of business invariants, and orchestration of application use cases.\n\nFor example, an order-processing core might determine whether an order can be submitted, calculate its total, and coordinate stock reservation. It should not need to understand HTTP routing, database connection configuration, or a payment provider's proprietary message format.\n\nThe pattern does not prescribe a single internal organization. The core may contain distinct domain and application layers, but that separation is an additional design choice rather than a requirement of the hexagonal diagram.\n\nPorts\n\nA port defines a coherent interaction across the application boundary. It describes what the application offers to an external actor or what it needs from an external capability.\n\nPorts are often divided into two categories:\n\n- Driving, primary, or inbound ports expose operations through which an external actor initiates application behavior, such as submitting an order or requesting an account balance.\n- Driven, secondary, or outbound ports describe capabilities the application uses, such as retrieving stored orders, sending a notification, or obtaining the current time.\n\nThe terminology varies between implementations. “Inbound” and “outbound” describe responsibility for initiating an interaction, not the direction of every message or return value.\n\nA port is an architectural contract, not a network port. It may be expressed as a programming-language interface, a function signature, a set of operations, or a messaging contract. It need not correspond one-to-one with a class, endpoint, or external system.\n\nAdapters\n\nAn adapter connects a port to a concrete external mechanism. It translates representations and interaction styles while keeping technology-specific details outside the core.\n\nA driving adapter might be:\n\n- A web controller that translates an HTTP request into an application operation.\n- A command-line interface that invokes the same operation.\n- A message consumer that turns an incoming message into an application command.\n- A test harness that directly exercises a use case.\n\nA driven adapter might implement persistence using a relational database, call an external payment service, or provide an in-memory substitute for testing.\n\nSeveral adapters can serve the same port. For example, a notification port may have email and text-message implementations, provided both satisfy the behavior the port requires."
    },
    {
      "heading": "Dependency direction and execution flow",
      "text": "A central implementation principle is that the core should not depend on concrete external adapters. External mechanisms depend on contracts defined by, or aligned with, the application’s needs.\n\nThis commonly uses the dependency inversion principle. Instead of an application service importing a specific database client, it depends on an abstraction such as an order repository. A database adapter implements that abstraction.\n\nExecution flow and source-code dependency are therefore different:\n\n- A web adapter calls an application operation.\n- The application calls an outbound repository port.\n- A concrete repository adapter executes a database operation.\n- Results return through the same boundaries.\n\nAlthough execution passes from the core into the database adapter, the core's source code need not reference the adapter's implementation.\n\nDependency injection is a common way to supply concrete adapters at startup, but no dependency-injection framework is required. Ordinary constructor arguments, function parameters, or explicit assembly code can establish the same relationships. The assembly location is often called the composition root."
    },
    {
      "heading": "Example: placing an order",
      "text": "An order application might define the following boundary:\n\nElement | Responsibility\nInbound port: PlaceOrder | Accept an order request and return an application-level result\nApplication service | Coordinate validation, stock reservation, and order persistence\nDomain objects | Enforce order rules and permitted state changes\nOutbound port: OrderRepository | Retrieve and store orders\nOutbound port: Inventory | Request stock reservation\nHTTP adapter | Convert requests and responses into application inputs and outputs\nDatabase adapter | Implement order persistence\nInventory-service adapter | Translate reservation requests into the external service's protocol\n\nThe HTTP adapter handles transport details such as request parsing and status codes. The core decides whether an order is valid. The database adapter handles queries, storage mappings, and database-specific failures.\n\nA test can invoke PlaceOrder with in-memory adapters. Another driving adapter, such as a batch-import process, can invoke the same operation without duplicating the ordering rules.\n\nThis separation does not make external systems interchangeable automatically. A replacement must satisfy the port's behavioral contract, including relevant consistency, failure, and performance expectations."
    },
    {
      "heading": "Testing",
      "text": "Independent testing is a central motivation for hexagonal architecture. Business behavior can be exercised without starting a web server, connecting to a production database, or contacting an external service.\n\nDifferent tests establish different properties:\n\n- Unit tests check small pieces of domain or application behavior.\n- Application-level tests drive inbound ports while substituting controlled implementations of outbound ports.\n- Integration tests check concrete adapters against real infrastructure or representative external environments.\n- Contract tests check whether adapters satisfy agreed interaction and behavioral expectations.\n- End-to-end tests check selected complete paths through the assembled application.\n\nTest doubles are useful but can give false confidence when their behavior differs from real infrastructure. An in-memory repository, for example, may not reproduce uniqueness constraints, concurrent updates, or transaction behavior. Hexagonal architecture makes isolation easier; it does not eliminate the need to test external integrations."
    },
    {
      "heading": "Relationship to other architectural approaches",
      "text": "Layered architecture\n\nTraditional layered designs often depict presentation, business logic, and persistence in a vertical stack. Hexagonal architecture emphasizes the inside–outside boundary instead: both presentation mechanisms and persistence mechanisms are external to application behavior.\n\nThe approaches are not mutually exclusive. A layered implementation can follow hexagonal principles if its business code remains independent of concrete infrastructure.\n\nDomain-driven design\n\nDomain-driven design concerns modeling software around a business domain and defining appropriate model boundaries. Hexagonal architecture concerns how an application interacts with its environment. They are complementary, but neither requires the other. An application does not need a rich domain-object model to use ports and adapters.\n\nOnion and clean architecture\n\nOnion architecture and clean architecture share the goal of keeping central policy independent of external mechanisms. They provide more explicit concentric organizations and dependency rules. They are closely related approaches, rather than exact synonyms for hexagonal architecture.\n\nMicroservices\n\nHexagonal architecture is not a synonym for microservices. A service can use ports and adapters internally, and a monolithic application can do the same. The pattern does not determine deployment boundaries, service discovery, or interservice communication."
    },
    {
      "heading": "Applications and limitations",
      "text": "The pattern is particularly relevant when business behavior must be accessible through multiple interfaces, external integrations change over time, or substantial application testing should run independently of infrastructure.\n\nIts main costs are additional contracts, translation code, and architectural discipline. In a small application with little business behavior, introducing an interface and adapter for every operation can add indirection without a corresponding benefit. Effective ports represent meaningful application conversations rather than mechanically wrapping every library call.\n\nBoundary design also involves trade-offs:\n\n- Leaking external representations: exposing database-specific objects or transport-specific response types through ports can couple the core to infrastructure despite an apparently separated directory structure.\n- Overgeneralized contracts: attempting to support every possible database or provider can produce abstractions that are either too weak or unnecessarily complex.\n- Transaction boundaries: separating persistence behind ports does not determine how atomic changes should be coordinated. Transaction ownership and consistency guarantees still require explicit design.\n- Distributed failures: adapters cannot hide all effects of latency, partial failure, retries, and duplicate delivery. Where relevant, application behavior must account for idempotence and recovery.\n- Semantic differences between adapters: two implementations with identical method signatures may differ in ordering, durability, or consistency. Those differences can matter to correctness.\n- Framework coupling: persistence annotations, framework base classes, and infrastructure exception types can introduce dependencies into the core even when code is organized into separate packages.\n\nHexagonal architecture is therefore principally a way to manage dependency and change. It does not itself establish security, scalability, fault tolerance, or correctness; each of those properties requires additional design and verification."
    }
  ],
  "links": [
    "software-architecture",
    "programming-language",
    "hypertext-transfer-protocol",
    "relational-database",
    "source-code",
    "database-transaction",
    "idempotence"
  ],
  "sources": [],
  "license": "https://creativecommons.org/licenses/by/4.0/"
}