Software architecture reference

Every architecture pattern is a rule about dependencies.

Layers, ports, modules, services, and events each decide which code is allowed to know about which other code, and what it costs to change that later. This reference covers eight patterns, the problem each one solves, and the trap each one hides. For the route-level view of a React application, see the Next.js App Router architecture checklist.

presentation → application → data

Layered architecture

The application is split into horizontal layers — usually presentation, business logic, and data access — and each layer calls only the one below it. It is the default shape of most web frameworks and the easiest to explain: a request enters at the top, and dependencies point down toward the database.

Each layer calls only the layer below it.

Use it for

  • Applications whose main job is moving data between a UI and a database: back offices, internal tools, CRUD-heavy products.
  • A starting point while the domain is not yet understood well enough to draw better boundaries.

Watch for

  • Rules leak upward into controllers or downward into SQL, and the middle layer becomes a pass-through that only forwards calls.
  • The business layer depends on the data layer, so the rules cannot be tested without a database and change whenever the schema does. Hexagonal architecture exists to reverse that arrow.
  • Layers cut across every feature. One feature change touches every layer, and teams split by layer hand work to each other on every ticket.
app/
  routes/        // presentation: parse input, render output
  services/      // rules: orderService.place()
  repositories/  // data access: orderRepository.insert()
// routes → services → repositories → database, never upward

ports · adapters

Hexagonal architecture (ports and adapters)

The application core declares ports: interfaces for what it needs (store an order, send an email) and for what it offers (place an order). Adapters implement those ports for one technology each — a Postgres repository, an HTTP controller, a payment client. Every dependency points at the core, so it never imports a framework, and any adapter can be replaced by a fake in a test.

Adapters on both sides depend on ports the core defines. Nothing in the core imports an adapter.

Use it for

  • Domains with real rules that must be tested without a database, a network, or a clock.
  • Code that has to survive a change of vendor: a payment provider, a queue, an email service.
  • Running one core from several entry points — an HTTP API, a CLI, a background worker.

Watch for

  • A port that mirrors one vendor’s API method for method leaves the core coupled to that vendor in everything but the import line. Name ports for what the core needs.
  • An interface for every class, including ones with one implementation and no I/O, adds indirection without adding a boundary.
  • Mapping between domain objects and database or transport shapes at each adapter is real work. Budget for it rather than letting ORM entities leak into the core.
// Port: owned by the core, named for what the core needs
export interface OrderStore {
  save(order: Order): Promise<void>
}

// Core: depends on the port, not on Postgres
export async function placeOrder(store: OrderStore, input: NewOrder) {
  const order = Order.create(input) // the rules live here
  await store.save(order)
  return order
}

// Adapters: one per technology, plus one for tests
export const pgOrderStore = (sql: Sql): OrderStore => ({ /* … */ })
export const memoryOrderStore = (): OrderStore => ({ /* … */ })

the dependency rule

Clean and onion architecture

Clean architecture (Robert C. Martin) and onion architecture (Jeffrey Palermo) draw the same idea as concentric rings: entities at the centre, use cases around them, interface adapters around those, and frameworks and drivers on the outside. The one rule is that source-code dependencies only point inward. It is hexagonal architecture with the inside given more structure.

Source-code dependencies only point inward. The inner rings never name the outer ones.

Use it for

  • Large, long-lived codebases whose business rules will outlive several UI frameworks and databases.
  • Separating use cases — workflows specific to this application — from entities, the rules that would hold in any application of the business.

Watch for

  • Applied to a CRUD app, four rings means four copies of the same shape and mapping code between each. The pattern costs most where there is the least domain to protect.
  • Folder names do not enforce the rule. Without an import-boundary check such as dependency-cruiser or eslint-plugin-boundaries, an inner ring importing an outer one goes unnoticed.
  • Use cases that only call a repository and return the result are the layered pass-through again, with more files.
src/
  domain/          // entities, value objects: imports nothing outside
  application/     // use cases: imports domain only
  adapters/        // controllers, presenters, repositories
  infrastructure/  // framework, ORM, HTTP server, config
// allowed: infrastructure → adapters → application → domain

one deployable · many modules

Modular monolith

One deployable application, divided into modules along business capabilities — billing, catalogue, accounts — rather than technical layers. Each module owns its data and exposes a small public interface; other modules call that interface and never reach into its internals or its tables. It gets most of the organisational benefit of services without putting the network between them.

One deploy. Modules call each other only through their public index; each owns its tables.

Use it for

  • The default for a new product with one team or a few. Boundaries can be drawn, tested, and moved while moving one is still a refactor.
  • A step toward services: a module with a clean interface and its own tables can be extracted later without untangling it first.

Watch for

  • Tables shared between modules quietly reintroduce coupling. A join across two modules’ tables is a dependency nobody declared.
  • Without enforcement, “public interface” is a convention, and convenient deep imports accumulate. Allow imports from a module’s index only, and check it in CI.
  • One deploy and one runtime is still one failure domain and one scaling unit: a memory leak in reporting takes checkout down with it.
src/modules/
  billing/
    index.ts      // public: createInvoice, getBalance
    internal/     // everything else, never imported from outside
  catalogue/
    index.ts
    internal/

import { createInvoice } from "@/modules/billing"               // ✓
import { taxTable } from "@/modules/billing/internal/tax"     // ✗

independent deploys

Microservices

The system is split into services that are deployed, scaled, and owned independently, each with its own data store, communicating over the network through APIs or messages. The benefit is organisational: teams ship on their own schedule. The cost is that every call between services can now be slow, fail, or arrive twice.

Each service deploys on its own and owns its data. Every arrow is a network call.

Use it for

  • Several teams that block each other on one release, where independent deploys are worth the operational cost.
  • Parts of a system with very different scaling, availability, or compliance needs, such as a video transcoder beside an accounts service.

Watch for

  • The distributed monolith: services that must deploy together, share a database, or call each other synchronously in long chains have the costs of both styles and the benefits of neither.
  • Network calls need timeouts, retries, idempotency, and tracing that an in-process call never did. Plan for them before the first split, not after the first outage.
  • Splitting early freezes boundaries before the domain is understood. Moving a capability between services is a data migration, not a rename.
orders-service    → orders_db     // owns orders
payments-service  → payments_db   // owns payments

// orders never queries payments_db. It calls
//   POST /payments
// or reacts to the payment.succeeded event.

publish · subscribe

Event-driven architecture

Components announce facts — OrderPlaced, PaymentFailed — to a broker, and any number of consumers react in their own time. The producer does not know who is listening, so new behaviour is added by adding a consumer, not by editing the producer. Work happens asynchronously, so the system as a whole is eventually consistent.

The producer publishes a fact. Consumers subscribe without the producer knowing they exist.

Use it for

  • Side effects that fan out from one business event: send a receipt, update search, record revenue.
  • Letting a new team subscribe to an event without the producing team changing anything.
  • Absorbing load spikes: the queue buffers while consumers catch up.

Watch for

  • The flow becomes invisible. No single place in the code says what happens after an order is placed, so document the event flows and trace them with correlation ids.
  • Most brokers deliver at least once, and ordering is usually guaranteed only per partition or key. Consumers must tolerate duplicates and reordering.
  • Events that are commands in disguise (SendWelcomeEmail) couple the producer to one consumer again. Name events as past-tense facts.
  • Publishing after the database commit loses the event if the process dies in between. The transactional outbox closes that gap.
// Producer: states a fact, knows no consumers
await bus.publish("order.placed", { orderId, total, placedAt })

// Consumers: each subscribes on its own
bus.subscribe("order.placed", sendReceipt)
bus.subscribe("order.placed", reserveStock)
bus.subscribe("order.placed", recordRevenue)

commands ≠ queries

CQRS

Command Query Responsibility Segregation uses one model to change state and another to read it. Commands go through the domain rules and write to the write store; queries read from projections shaped for each screen, which are updated from the writes — sometimes in the same transaction, often asynchronously. Event sourcing, which stores the events themselves as the source of truth, is a common partner but a separate decision.

Writes go through the rules. Reads come from a model shaped for the screen.

Use it for

  • Read and write shapes that differ sharply: a dashboard aggregating thousands of rows beside a form that edits one.
  • Read traffic far above write traffic, where read models can be denormalised, cached, or scaled on their own.

Watch for

  • With asynchronous projections, a user can save and then not see their change. Decide how the UI handles that — return the new state from the command, or read your own writes — before it ships.
  • Two models are twice the code. For most CRUD screens, one model plus a few dedicated query functions is the proportionate version.
  • Event sourcing adopted by default alongside CQRS brings event schema versioning, replays, and snapshots as permanent work.
// Command side: enforces the rules, writes the source of truth
async function renameProject(cmd: { id: string; name: string }) {
  const project = await projects.load(cmd.id)
  project.rename(cmd.name) // throws if the name breaks a rule
  await projects.save(project)
}

// Query side: reads a projection built for one screen
const rows = await readDb.query(
  "select * from project_list_view where owner_id = $1",
  [ownerId]
)

one backend per client

Backend for frontend (BFF)

Each client — web app, mobile app, partner API — gets its own thin server-side layer that calls the underlying services and returns exactly the shape that client needs. It keeps aggregation, token handling, and response shaping out of the browser and out of the shared services. In a Next.js application, route handlers and server components already play this role.

Each client gets a thin server-side layer that shapes responses for it.

Use it for

  • A web client and a mobile client that need different shapes or granularity from the same services.
  • Keeping secrets server-side: the browser holds a session cookie for its BFF, and only the BFF holds API keys and service tokens.
  • Collapsing several service calls into one round trip for a slow mobile connection.

Watch for

  • Business rules creep into the BFF and get duplicated across BFFs. It should shape and aggregate, not decide.
  • One BFF shared by every client turns back into a general-purpose gateway, with each client’s special cases in the same file.
  • A BFF is one more hop. For a single client calling a single service, it can be a layer with nothing to do.
// app/api/dashboard/route.ts: one round trip for one screen
export async function GET() {
  const session = await getSession()
  const [projects, usage] = await Promise.all([
    projectsApi.list(session.uid),
    billingApi.usage(session.uid),
  ])
  return Response.json({
    projects: projects.map(toCard),
    creditsLeft: usage.remaining,
  })
}

Start from the problem

A data-in, data-out app with few real rules
Layered architecture
The business rules cannot be tested without a database
Hexagonal architecture (ports and adapters)
The rules have to outlive the framework and the database
Clean and onion architecture
One team, a new product, boundaries still moving
Modular monolith
Several teams block each other on every release
Microservices
One action triggers a growing list of side effects
Event-driven architecture
Reads and writes need very different shapes or scale
CQRS
Web and mobile need different shapes from the same services
Backend for frontend (BFF)

Keep going

Splitting a system across the network changes how it fails.

The distributed systems reference covers timeouts, retries with backoff, idempotency keys, circuit breakers, the transactional outbox, and sagas.

Open the distributed systems reference

With your permission, Affonso uses a 30-day cookie to remember which affiliate referred you. Google Analytics measures site usage. Google Ads measures our advertising. Microsoft Clarity records masked session replays. You can use Nodlume with or without these cookies.