Clean Architecture / Hexagonal Architecture

Keep business logic independent of frameworks, databases, and UI, so you can swap any of them without touching the core.

What is it?

Layered architecture stacks presentation, business logic, and data access so each talks to its neighbor. Clean Architecture (and its close cousin, Hexagonal Architecture, also called "ports and adapters") keeps the same idea but adds one strict rule: business logic sits at the center, and nothing about frameworks, databases, or UI may leak into it. Every dependency points inward, toward the business logic.

Your core logic defines abstractions for what it needs, called ports ("I need something that can save an order", "I need something that can look up a user"). Outside the core, adapters implement those ports with real technology: a Postgres adapter, a REST API adapter, a command-line adapter.

The web framework, database driver, and UI toolkit all live in adapters. Swap the web framework, or move from REST to a CLI, and the core doesn't change, because it never depended on them.

This is dependency inversion applied to a whole application, not just one class.

Explain like I'm 10

A board game's rules don't care whether you play on a physical board, in an app, or by reading moves aloud over a video call. Each is just a different 'adapter' for the same game.

Examples

Business logic entangled with a framework

// Express-specific request/response objects leak into the core logic
app.post("/orders", async (req, res) => {
  if (!req.body.items || req.body.items.length === 0) {
    return res.status(400).json({ error: "Order must have items" }); // business rule, tangled with HTTP
  }
  const total = req.body.items.reduce((s, i) => s + i.price, 0);
  await pgPool.query("INSERT INTO orders (total) VALUES ($1)", [total]); // tangled with Postgres
  res.json({ total });
});

The rule 'an order must have items' and the pricing calculation are stuck in an Express route handler, wired to one database client. None of it can run without a live HTTP + Postgres setup.

Business logic isolated behind ports

// core/placeOrder.js — no Express, no Postgres, no imports from either
export function placeOrder(items, orderRepository) {
  if (!items || items.length === 0) {
    throw new Error("Order must have items");
  }
  const total = items.reduce((s, i) => s + i.price, 0);
  orderRepository.save({ items, total });
  return { total };
}

// adapters/expressOrderController.js — the HTTP adapter
app.post("/orders", async (req, res) => {
  try {
    const result = placeOrder(req.body.items, pgOrderRepository);
    res.json(result);
  } catch (e) {
    res.status(400).json({ error: e.message });
  }
});

placeOrder is plain JavaScript that knows nothing of HTTP or Postgres. It runs just as easily behind a CLI, a message queue, or a test. The Express handler is now a thin adapter that turns HTTP into a call to the core.

How it works

Picture concentric circles:

- Business rules (entities) at the center. - Application-specific logic (use cases) around them. - Everything volatile (web frameworks, databases, external APIs, UI) on the outside, in adapters.

The Dependency Rule: source code dependencies only point inward. Outer layers know about inner ones; inner layers know nothing of outer ones. The core defines the interfaces (ports) it needs, and the adapters implement them.

┌─────────────────────────────────────┐
   │        Adapters (web, DB, CLI)       │
   │   ┌───────────────────────────────┐ │
   │   │   Use Cases (application logic)│ │
   │   │   ┌─────────────────────────┐  │ │
   │   │   │  Entities (core rules)  │  │ │
   │   │   └─────────────────────────┘  │ │
   │   └───────────────────────────────┘ │
   └─────────────────────────────────────┘
        Dependencies always point inward →

Why does it exist?

Business logic is usually the most valuable, longest-lived, and most-tested part of a system. Frameworks, databases, and UI technology churn constantly. A web framework may be replaced in three years, but "an order needs at least one item" probably won't change.

Tangling the durable part with the disposable parts means every framework upgrade or database migration risks the part you can least afford to break. It also makes the core nearly impossible to test without running the whole stack.

When to use it

It earns its cost in systems with real, evolving business logic that outlives any framework or database: systems maintained for years, ported across technologies, or tested heavily at the logic level without a full stack.

When not to use it

In a small CRUD app or internal tool that mostly moves data in and out of a database, a full ports-and-adapters setup adds a lot of ceremony (interfaces, adapters, wiring) while protecting almost nothing, since there's barely any core logic.

Common mistakes

  • Adding ports and adapters but still importing a framework type (like an Express Request) into the core, quietly breaking the Dependency Rule.

  • Treating it as plain layered architecture and missing the key difference: the strict inward-only dependency direction and a framework-free center.

  • Over-applying it to simple apps, producing many interfaces and adapters that wrap almost no real logic.

Practice exercises

  1. Easy:

    An Express route handler validates a request body and contains a business rule. Extract the business rule into a plain function with no Express dependency.

  2. Medium:

    Design the ports (interfaces) a 'library book checkout' use case needs, e.g., looking up a book, checking a member's borrowing limit, recording the checkout, without referencing any database or framework.

  3. Hard:

    Take a small project (or an imagined to-do app with a REST API and a database). Describe how you'd restructure it into entities, use cases, and adapters, and what would change if you replaced the database.

Interview questions

What is the core idea behind Clean Architecture / Hexagonal Architecture?

Business logic sits at the center with zero dependency on frameworks, databases, or UI. Those volatile pieces live in outer 'adapters' that depend inward on the core, never the reverse.

What is a 'port' and what is an 'adapter' in this style of architecture?

A port is an abstraction the core defines for what it needs (e.g., 'something that can save an order'). An adapter implements a port with real technology (e.g., a Postgres-backed order repository, or an HTTP controller).

Why keep business logic independent of the web framework?

So you can test and evolve the business logic without a running framework or server, and upgrade or replace the framework without risking the app's core rules.