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.
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:
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.
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 NoneThree 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 Boot | NestJS (Node) | FastAPI (Python) | |
|---|---|---|---|
| Port mechanism | Java interface | TypeScript interface + injection token | typing.Protocol |
| Wiring | Container, constructor injection, fails at startup on a missing bean | Module providers, token binding, fails at startup on a missing provider | Depends factories, fails at first request if a factory is missing |
| Primary adapter | @RestController | @Controller | Route function |
| Secondary adapter | @Repository wrapping Spring Data | @Injectable wrapping TypeORM / Prisma | Class taking a SQLAlchemy session |
| Ceremony | Annotations; the most framework magic, the least hand-written wiring | Tokens + modules; explicit, and the module is a readable map of the boundary | Least ceremony; most hand assembly in Depends factories |
| Testing the domain | Plain JUnit, no context | Plain Jest, no Nest application | Plain pytest, no app fixture |
| Where it bites | JPA entities leaking into the domain; the double mapping feels like boilerplate until the first migration | Token indirection confuses newcomers; two names for every port | No startup binding check; a forgotten Depends factory is a runtime surprise |
| Best fit | Teams already on the JVM; long-lived services with several adapters | Teams that want explicit module boundaries and TypeScript end to end | Small 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
Depends factories — with FastAPI's missing startup-time binding check as a known sharp edge.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
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.