ArchitectureIntermediate

Hexagonal Architecture in Spring, Node, and Python

DeveloperHat Team
18 min read

TL;DR

Ports and adapters, done three ways: Hexagonal and Clean Architecture in Spring Boot, NestJS, and FastAPI — real code, honest trade-offs, and when to skip the ceremony.

Hexagonal Architecture and Clean Architecture are the same idea wearing two coats: put your business rules in the middle, and let everything else — the web framework, the database, the message broker — plug in from the outside through interfaces you own. Alistair Cockburn published the hexagonal pattern in 2005 as "ports and adapters"; Robert C. Martin restated it as Clean Architecture in 2012 with the dependency rule that nothing in the inner circles may know about anything in the outer circles. Twenty years on, the idea survives because the problem it solves never went away: frameworks change, databases get swapped, and the code that encodes what your business actually does should not have to change with them.

This article builds the same small slice of a system — placing an order — three times: in Spring Boot, in NestJS (Node), and in FastAPI (Python). Same ports, same shape, different idioms. The short version up front: the pattern is one decision, not three — the domain owns interfaces, adapters implement them — and the differences between stacks are just how each one wires an interface to its implementation. If your service has one way in and one way out, you probably do not need it at all.

The hexagon: the domain in the middle, everything else an adapter REST API driving adapter CLI / Jobs driving adapter Tests driving adapter PostgreSQL driven adapter Message broker driven adapter External HTTP API driven adapter DOMAIN use cases · entities ports are interfaces Driving adapters call in through ports; driven adapters are called out through ports.

What the hexagon actually is

The hexagon is a drawing of a dependency rule, not a folder structure. The domain — entities, value objects, use cases — sits in the middle and knows nothing about the outside world. Around it sit ports: interfaces the domain defines, in the language of the business. A port that the outside world calls is a primary (driving) port: "place an order". A port the domain calls out through is a secondary (driven) port: "save this order", "charge this card". Around the ports sit adapters: concrete implementations that translate between a port and a real technology. A REST controller is a primary adapter — it translates HTTP into a call on a primary port. A JPA repository is a secondary adapter — it translates a secondary port into SQL.

Two consequences follow from that drawing, and they are the whole payoff:

  • The domain is testable without infrastructure. A use case takes its secondary ports as constructor arguments. In a test you pass fakes. No database, no HTTP server, no Spring context, no test containers — the business rule runs in milliseconds.
  • Infrastructure is swappable at the boundary. Replacing PostgreSQL with another store means writing one new adapter that implements the same port. Nothing in the domain changes, because the domain never imported the old adapter in the first place. The dependency arrow points inward, always: adapters depend on the domain, never the reverse.
  • Clean Architecture adds concentric rings to the same drawing — entities at the centre, then use cases, then interface adapters, then frameworks and drivers at the edge — and one sentence that does the same work: source code dependencies must point inward. If you understand the hexagon, you understand Clean Architecture; the rings are a stricter way of drawing the same rule, with the extra discipline that use cases may not depend on the delivery mechanism either.

    The core: one use case, three stacks

    The domain code below is deliberately boring. An order is placed, the use case checks the rules, and it persists the result through a port. The port is the interesting line — everything else in this article is just adapters around it.

    In Spring Boot, the port is a Java interface and the use case is a plain class the container constructs:

    // The domain owns this interface. No Spring imports here.
    public interface OrderRepository {
        Order save(Order order);
        Optional<Order> findById(OrderId id);
    }
    
    public class PlaceOrderUseCase {
    
        private final OrderRepository orders;
        private final PaymentGateway payments;
    
        public PlaceOrderUseCase(OrderRepository orders, PaymentGateway payments) {
            this.orders = orders;
            this.payments = payments;
        }
    
        public Order place(Cart cart) {
            if (cart.isEmpty()) {
                throw new IllegalArgumentException("cannot place an empty order");
            }
            Order order = new Order(cart);
            payments.charge(order.total());
            return orders.save(order);
        }
    }

    Nothing in this class mentions HTTP, JPA, or Spring. PaymentGateway is another port — the domain says "charge this amount" and does not care whether the adapter behind it talks to Stripe, a test double, or a queue. That is the pattern in one class: constructor-injected ports, business rules in plain code, no framework imports. Our creational patterns guide covers the same constructor-injection habit from the other side — the container creates the object, the object never looks the container up.

    NestJS expresses the identical shape with TypeScript interfaces and injection tokens. NestJS's container cannot inject by interface (interfaces do not exist at runtime), so the port gets a token — a string or symbol — and the adapter registers against it:

    // order.repository.ts — the port, owned by the domain
    export interface OrderRepository {
      save(order: Order): Promise<Order>;
      findById(id: string): Promise<Order | null>;
    }
    export const ORDER_REPOSITORY = Symbol('ORDER_REPOSITORY');
    
    // place-order.use-case.ts — same rules, same shape as the Java version
    @Injectable()
    export class PlaceOrderUseCase {
      constructor(
        @Inject(ORDER_REPOSITORY) private readonly orders: OrderRepository,
        @Inject(PAYMENT_GATEWAY) private readonly payments: PaymentGateway,
      ) {}
    
      async place(cart: Cart): Promise<Order> {
        if (cart.items.length === 0) {
          throw new Error('cannot place an empty order');
        }
        const order = new Order(cart);
        await this.payments.charge(order.total);
        return this.orders.save(order);
      }
    }

    The token is the one piece of NestJS ceremony the pattern forces on you, and it is also the reason the pattern works so well there: the module system makes the boundary explicit. The use case is registered in a module, the adapter is registered against the token in the same module, and swapping the adapter is a one-line change in the module definition. NestJS's providers documentation covers custom providers and injection tokens — the mechanism the whole hexagonal wiring hangs on.

    FastAPI has no container of its own, so the port is a typing.Protocol and the wiring is Depends. The use case is a plain function that receives its ports as arguments:

    from typing import Protocol
    
    # The port, owned by the domain — a Protocol, not a base class.
    class OrderRepository(Protocol):
        def save(self, order: Order) -> Order: ...
        def find_by_id(self, order_id: str) -> Order | None: ...
    
    class PaymentGateway(Protocol):
        def charge(self, amount: Money) -> None: ...
    
    def place_order(
        cart: Cart,
        orders: OrderRepository,
        payments: PaymentGateway,
    ) -> Order:
        if not cart.items:
            raise ValueError("cannot place an empty order")
        order = Order(cart)
        payments.charge(order.total)
        return orders.save(order)

    The use case is a function, not a class, because Python does not need the class to hold the dependencies — they arrive as arguments. The test story is the same: pass fakes, no database. The wiring story is different, and it is the honest trade-off of the Python version: there is no container to catch a missing binding at startup, so the route handler has to assemble the dependencies itself, as the next section shows.

    Primary adapters: how the outside world calls in

    A primary adapter translates one delivery mechanism into a call on a primary port. The use case never sees HTTP; the adapter never contains a business rule.

    Spring Boot's adapter is a @RestController that depends on the use case — which the container built with its ports already wired:

    @RestController
    @RequestMapping("/orders")
    public class OrderController {
    
        private final PlaceOrderUseCase placeOrder;
    
        public OrderController(PlaceOrderUseCase placeOrder) {
            this.placeOrder = placeOrder;
        }
    
        @PostMapping
        public ResponseEntity<OrderResponse> place(@RequestBody CartDto cart) {
            Order order = placeOrder.place(cart.toDomain());
            return ResponseEntity.status(HttpStatus.CREATED)
                    .body(OrderResponse.from(order));
        }
    }

    The controller does two translations and nothing else: the DTO becomes a domain Cart, and the domain Order becomes a response DTO. If the team later adds a CLI command or a message listener that places orders, it calls the same use case — the second primary adapter costs almost nothing, because the port already exists. That is the first moment the hexagon starts paying rent: the second way in is nearly free.

    NestJS's controller is the same shape with decorators instead of annotations, and the module is where the port gets bound to its adapter:

    @Controller('orders')
    export class OrderController {
      constructor(private readonly placeOrder: PlaceOrderUseCase) {}
    
      @Post()
      async place(@Body() cart: CartDto): Promise<OrderResponse> {
        const order = await this.placeOrder.place(cart.toDomain());
        return OrderResponse.from(order);
      }
    }
    
    // orders.module.ts — the one place the wiring lives
    @Module({
      controllers: [OrderController],
      providers: [
        PlaceOrderUseCase,
        { provide: ORDER_REPOSITORY, useClass: PostgresOrderRepository },
        { provide: PAYMENT_GATEWAY, useClass: StripePaymentGateway },
      ],
    })
    export class OrdersModule {}

    FastAPI's adapter is a route function, and the dependency assembly happens in Depends — each dependency is a small factory that builds one adapter:

    from fastapi import APIRouter, Depends
    
    router = APIRouter()
    
    def get_orders() -> OrderRepository:
        return SqlAlchemyOrderRepository(session_factory())
    
    def get_payments() -> PaymentGateway:
        return StripePaymentGateway()
    
    @router.post("/orders", status_code=201)
    def place(
        cart: CartDto,
        orders: OrderRepository = Depends(get_orders),
        payments: PaymentGateway = Depends(get_payments),
    ) -> OrderResponse:
        order = place_order(cart.to_domain(), orders, payments)
        return OrderResponse.from_domain(order)

    FastAPI's dependencies documentation is the reference for this wiring. Note what Depends gives you and what it does not: it gives you per-request construction and easy overrides in tests (app.dependency_overrides), but there is no startup-time check that every port has an adapter — a missing Depends factory fails at the first request, not at boot. Spring Boot and NestJS both fail at startup when a bean is missing. That is a real operational difference between the stacks, and it is the kind of thing that only shows up in production if nobody tests the route.

    Five layers, one dependency rule — everything points inward Primary adapters — REST controllers, CLI commands, event listeners Application — use cases orchestrate, one transaction per use case Domain — entities, value objects, domain services, pure rules Ports — interfaces the domain owns; the only way in or out Secondary adapters — JPA repos, HTTP clients, message publishers Dependencies point inward: adapters depend on the domain — the domain never imports an adapter.

    Secondary adapters: how the domain reaches out

    A secondary adapter implements a port against a real technology. This is where the database, the payment provider, and the message broker live — and the only place they are allowed to live.

    Spring Boot's repository adapter wraps a Spring Data interface. The domain port is OrderRepository; the Spring Data interface is a separate, infrastructure-owned interface, and the adapter translates between them:

    // Infrastructure-owned: Spring Data speaks in entities, not domain objects.
    interface OrderJpaRepository extends JpaRepository<OrderEntity, UUID> {}
    
    @Repository
    class JpaOrderRepository implements OrderRepository {
    
        private final OrderJpaRepository jpa;
    
        JpaOrderRepository(OrderJpaRepository jpa) {
            this.jpa = jpa;
        }
    
        @Override
        public Order save(Order order) {
            return jpa.save(OrderEntity.fromDomain(order)).toDomain();
        }
    
        @Override
        public Optional<Order> findById(OrderId id) {
            return jpa.findById(id.value()).map(OrderEntity::toDomain);
        }
    }

    The translation in fromDomain / toDomain is the adapter's whole job, and it is also the cost of the pattern in Spring: every entity that crosses the boundary gets mapped twice. Teams that skip the mapping and let JPA entities leak into the domain have not adopted hexagonal architecture — they have adopted hexagonal folder names, and the first database migration that renames a column will prove it. The mapping is the boundary; without it there is no boundary.

    NestJS's adapter is the same idea behind an @Injectable class, and Python's is a class that takes a SQLAlchemy session:

    @Injectable()
    export class PostgresOrderRepository implements OrderRepository {
      constructor(@InjectRepository(OrderEntity) private readonly repo: Repository<OrderEntity>) {}
    
      async save(order: Order): Promise<Order> {
        return (await this.repo.save(OrderEntity.fromDomain(order))).toDomain();
      }
    
      async findById(id: string): Promise<Order | null> {
        const entity = await this.repo.findOneBy({ id });
        return entity ? entity.toDomain() : null;
      }
    }

    class SqlAlchemyOrderRepository:
        def __init__(self, session: Session):
            self.session = session
    
        def save(self, order: Order) -> Order:
            entity = OrderRow.from_domain(order)
            self.session.add(entity)
            self.session.commit()
            return entity.to_domain()
    
        def find_by_id(self, order_id: str) -> Order | None:
            row = self.session.get(OrderRow, order_id)
            return row.to_domain() if row else None

    Three stacks, one shape: the adapter owns the translation, the port owns the contract, and the domain never imports either adapter. If you swap PostgreSQL for another store, you write one new class per stack and change one wiring line — the controller, the module binding, or the Depends factory.

    Head-to-head: Spring Boot vs NestJS vs FastAPI

    Spring BootNestJS (Node)FastAPI (Python)
    Port mechanismJava interfaceTypeScript interface + injection tokentyping.Protocol
    WiringContainer, constructor injection, fails at startup on a missing beanModule providers, token binding, fails at startup on a missing providerDepends factories, fails at first request if a factory is missing
    Primary adapter@RestController@ControllerRoute function
    Secondary adapter@Repository wrapping Spring Data@Injectable wrapping TypeORM / PrismaClass taking a SQLAlchemy session
    CeremonyAnnotations; the most framework magic, the least hand-written wiringTokens + modules; explicit, and the module is a readable map of the boundaryLeast ceremony; most hand assembly in Depends factories
    Testing the domainPlain JUnit, no contextPlain Jest, no Nest applicationPlain pytest, no app fixture
    Where it bitesJPA entities leaking into the domain; the double mapping feels like boilerplate until the first migrationToken indirection confuses newcomers; two names for every portNo startup binding check; a forgotten Depends factory is a runtime surprise
    Best fitTeams already on the JVM; long-lived services with several adaptersTeams that want explicit module boundaries and TypeScript end to endSmall teams, fast iteration, services where the domain is small and the adapters are few

    The table hides the decision that matters most, which is not about the framework at all. Hexagonal architecture is a bet that the infrastructure will change more often than the business rules. For a service that talks to one database and one payment provider and will do so for years, that bet loses: the ports, the adapters, and the double mapping are pure overhead. For a service that already has two ways in (a REST API and a message consumer) or two ways out (a database and an external API), the bet wins on the second adapter, because the second adapter reuses a port that already exists. Count the boundaries you have today, and the boundaries you can see coming in the next year. That count is the decision.

    Architecture decision: hexagonal architecture, three stacks

  • Decision: Adopt ports-and-adapters (hexagonal / Clean Architecture) for services with more than one inbound or outbound boundary, in all three stacks, with the domain owning the port interfaces and adapters owning every translation. Single-boundary services stay layered (controller → service → repository) with no ports.
  • Context: The team ships services in Spring Boot 4.2, NestJS, and FastAPI. The recurring pain is infrastructure leaking into business logic — JPA entities in service methods, Stripe calls inside controllers, SQL in route handlers — which makes the domain untestable without a database and makes every infrastructure swap a rewrite. The pattern's originators describe it the same way: Cockburn's hexagonal architecture puts the application inside with ports as its interface to the outside, and Martin's Clean Architecture states the dependency rule that inner circles must not know about outer ones.
  • Options considered: (a) The approach above — ports owned by the domain, one adapter per technology, in all three stacks. (b) Layered architecture everywhere (controller → service → repository), no ports. (c) Full Clean Architecture with separate use-case, entity, and interface-adapter layers as distinct modules in every service, enforced by build rules.
  • Why this one: Option (a) buys the two things the team actually needs — domain tests without infrastructure, and infrastructure swaps at a single class — at the smallest ceremony that delivers them. Option (b) is cheaper today and the right call for single-boundary services, which is why this decision explicitly keeps it for those; applied everywhere, it is how the leakage started. Option (c) adds module-boundary enforcement the team has no tooling for — ArchUnit in Java, dependency-cruiser in Node, import-linter in Python — and three different enforcement mechanisms for one rule is a maintenance cost the team would stop paying within a quarter.
  • What it costs you: Every entity crossing a boundary is mapped twice (domain object ↔ persistence row); every port is an interface plus an adapter plus a wiring line, so a service with three boundaries has roughly three times the files of the layered version; and each stack has its own wiring idiom to learn — Spring's container, NestJS's tokens, FastAPI's Depends factories — with FastAPI's missing startup-time binding check as a known sharp edge.
  • When to reverse it: If a hexagonal service still has exactly one inbound and one outbound boundary after a year, collapse it back to layered — the ports are not earning their keep. If the double mapping becomes the dominant complaint in review, revisit a shared mapping layer or accept entity leakage as a documented, deliberate trade-off for that one service. If the team adopts a stack without a container (plain Node, plain Python scripts), re-evaluate: the pattern still works, but the wiring is hand-rolled and the cost-benefit line moves.
  • Does this service earn the hexagon, or is a layer enough? How many ways in and out? ports, stores, clients One in, one out single API + one DB Several, or they change swap infra over time A script or prototype throwaway by design Layered service controller → service → repo Hexagonal ports earn their keep Skip the ceremony no ports, no adapters One port is not a hexagon — the pattern pays off at the second boundary, not the first.

    Recommendation

    For a new service, count the boundaries before you choose the shape. One REST API in, one database out: build it layered, keep the service class honest, and move on — the hexagon would be architecture for its own sake. Two or more ways in or out, or one you can see coming in the next year (a second client, a message consumer, a database migration, a payment-provider switch): build it hexagonal from the first commit, because retrofitting ports onto a service that already leaks infrastructure is a rewrite, not a refactor.

    When you do build it, enforce the one rule that makes the rest true: the domain module imports nothing from the framework. No jakarta.persistence in a Java domain class, no NestJS decorator on a use case, no FastAPI or SQLAlchemy import in a Python domain module. That single import rule is checkable in review without any tooling, and every leak the team has hit in the past violated it. The adapters can be as framework-heavy as they like — that is their job.

    For an existing service, do not rewrite it hexagonal in one pass. Pick the leakiest boundary — usually the repository or the payment client — extract a port for it, move the implementation behind an adapter, and wire the use case to the port. One boundary per change, each one shippable on its own. After two boundaries the shape is visible, the tests run without the database, and the team can decide whether the third boundary is worth the same treatment. If it is not, stop: a half-hexagonal service with its two worst leaks fixed is a better outcome than a half-finished rewrite.

    The companion decision for how these services fit into the system around them is our modular monolith vs microservices guide — the hexagon decides the inside of one service, that guide decides how many services there should be. And the pattern that decides how the objects inside the hexagon get created is our creational patterns guide, where the container takes over from the hand-written factory. For the structural patterns that wrap those objects once they exist — the proxies, decorators, and adapters the frameworks already run for you — see Proxy, Decorator, and Adapter in Spring Boot.

    When NOT to use hexagonal architecture

  • Don't build ports for a single-boundary service. A CRUD API over one database with one client is a layered service. Ports, adapters, and double mapping add files and indirection that no future change will repay.
  • Don't use it for scripts, prototypes, and throwaway tools. A migration script, a one-off data job, and a weekend prototype have no second boundary coming. The pattern's payoff is measured in years; the prototype's lifetime is measured in days.
  • Don't let the domain import the framework. The moment a domain class imports a persistence annotation, an HTTP decorator, or an ORM base class, the hexagon is a drawing, not an architecture. The import rule is the pattern; everything else is decoration.
  • Don't map twice and then skip the mapping. An adapter that returns the JPA entity directly to the use case has saved the mapping cost and lost the boundary. If the mapping feels too expensive, the honest answer is to stay layered, not to build a hexagon with a hole in it.
  • Don't enforce it with tooling you won't maintain. ArchUnit rules, import-linter configs, and dependency-cruiser rules all rot the first month nobody owns them. A code-review checklist — "does the domain import the framework?" — outlives every enforcement tool the team has tried.
  • Don't confuse hexagonal with microservices. One service can be hexagonal; a hundred services can all be layered. The hexagon is about the inside of a service, and it says nothing about how many services you should have.
  • Hexagonal and Clean Architecture survive because they are one rule with an obvious test: can you run the business logic with no framework, no database, and no network? In Spring Boot the rule is enforced by the container, in NestJS by the module system, in FastAPI by the discipline of passing ports as arguments — but in all three the test is the same, and the answer is the same. If the use case runs in a plain unit test with fakes for its ports, the architecture is working. If it needs the application context, the test containers, or the running server, the boundary has a hole in it, and the hole is where the next infrastructure change will hurt.

    Why This Matters

    Understanding the business and technical context helps you make informed decisions rather than blindly following patterns.

    Trade-offs to Consider

    Every architectural decision involves trade-offs. Consider your specific requirements, team expertise, and scale when evaluating options.

    When NOT to Use This

    Knowing when a solution doesn't apply is as valuable as knowing when it does. Consider alternatives for your specific situation.

    Decision Framework

    Use this framework to evaluate whether this approach is right for your use case based on your specific constraints and requirements.

    Share this articleShare on XShare on LinkedIn

    Keep the decision frameworks coming

    One practical architecture guide a week — patterns, trade-offs, and when not to use them. No spam, unsubscribe anytime.