Skip to content

Lesson 12 of 28Architecture

Layered Architecture

Split a backend into presentation, service, domain and data layers, with clear transaction, error and cross-cutting boundaries.

27 min read0/8 questions

So far you have shaped functions, classes and modules. This unit zooms out to the shape of a whole service. Open a codebase where a route handler parses JSON, runs SQL, applies discount rules and sends email in one 120-line function. Now change the discount rule. You cannot test it without a database and an HTTP request, and you are scared to touch it. Layered architecture is the fix almost every backend team reaches for, and "how would you structure this service?" is a standard interview question.

Four layers, one direction

Each layer has one job and talks only to the layer below it.

A request through the layers
  1. PresentationHTTP routes, CLI, React pages: parse input, return output
  2. Application / serviceuse cases: orchestrate one business action
  3. Domainentities and rules: Order, Money, can this order be refunded?
  4. Data access / repositoryload and save domain objects
  5. DatabasePostgres, SQLite, an external API

POST /orders/42/pay arrives. The route parses the path and body into plain values, then calls the service. No business rules here.

1/6

The word "below" matters. Presentation may call services. Services may call the domain and repositories. The domain calls nothing: it has no imports of FastAPI, SQLAlchemy, React or fetch. That makes it the most stable, most tested, easiest to read part of the system.

Match the pairs0/4 matched

Which layer should own each piece of code?

Choose an item, then its match on the other side.

Dependencies point inward

There is a catch. The service needs to save orders, so does it import the Postgres repository? If it does, the business code depends on the database, and you are back to needing Postgres to test a rule.

The trick is dependency inversion from the SOLID lesson. The inner layer declares an interface describing what it needs (OrderRepository with get and save). The outer layer implements it (SqlOrderRepository). Now the arrow of dependency points inward, toward the business rules, even though calls flow outward to the database.

Here is a whole slice of a layered app in one runnable file. In a real project each section would be its own module.

Python
from dataclasses import dataclassfrom typing import Protocol # ---- domain: pure rules, no imports from other layersclass DomainError(Exception): ... @dataclassclass Order: id: int total_cents: int status: str = "pending" def pay(self) -> None: if self.status != "pending": raise DomainError(f"order {self.id} is {self.status}, cannot pay") self.status = "paid" # ---- application: the port it needs, and the use caseclass OrderRepository(Protocol): def get(self, order_id: int) -> Order | None: ... def save(self, order: Order) -> None: ... class OrderService: def __init__(self, repo: OrderRepository): self.repo = repo def pay(self, order_id: int) -> Order: order = self.repo.get(order_id) if order is None: raise LookupError(order_id) order.pay() self.repo.save(order) return order # ---- data access: one implementation of the portclass InMemoryOrderRepository: def __init__(self): self.rows: dict[int, Order] = {} def get(self, order_id: int) -> Order | None: return self.rows.get(order_id) def save(self, order: Order) -> None: self.rows[order.id] = order # ---- presentation: map HTTP-ish input/output, nothing elsedef pay_route(service: OrderService, order_id: str) -> tuple[int, dict]: try: order = service.pay(int(order_id)) except LookupError: return 404, {"error": "not found"} except DomainError as e: return 409, {"error": str(e)} return 200, {"id": order.id, "status": order.status} repo = InMemoryOrderRepository()repo.save(Order(id=42, total_cents=4999))service = OrderService(repo)print(pay_route(service, "42"))print(pay_route(service, "42"))print(pay_route(service, "7"))
Output
Press Run (⌘ Enter) to see what happens.

Paying twice gives a 409 Conflict because the domain refused, and the route only translated that refusal into HTTP. Swap InMemoryOrderRepository for a SQL one and not a single line of Order or OrderService changes.

Quick check
In a clean layered design, which import is a red flag?
Need a nudge? A hint rules out a wrong answer.

Smell: the fat controller

Here is the code we started with, and where each piece moves.

smell: routes/orders.py
@router.post("/orders/{order_id}/pay")
def pay(order_id: int, db: Session = Depends(get_db)):
    row = db.execute(text("SELECT * FROM orders WHERE id = :id"), {"id": order_id}).one()  # data access
    if row.status != "pending":                                                         # domain rule
        raise HTTPException(409)
    db.execute(text("UPDATE orders SET status = 'paid' WHERE id = :id"), {"id": order_id})
    db.commit()
    send_email(row.email, "Paid!")                                                      # use case step
    return {"id": row.id, "status": "paid", "email": row.email, "card_hash": row.card_hash}  # leaks fields
LineMoves to
SELECT / UPDATE / commitSqlOrderRepository
if status != "pending"Order.pay() in the domain
load, pay, save, emailOrderService.pay()
returning the rowa response DTO with only public fields

After the refactor the route is three lines: parse, call the service, map the result.

DTOs vs domain models

A domain model (like Order) holds state and rules. A DTO (data transfer object) is a dumb shape for crossing a boundary: an API request, an API response, a message on a queue. In FastAPI your DTOs are Pydantic models; in TypeScript they are types, often validated with Zod.

Domain modelDTO
Lives inDomain layerEdges (API, queue, DB row)
Has behaviourYes (pay(), refund())No, just fields
Shape driven byBusiness rulesWhat the client needs
Example fieldstatus, total: Money"total": "49.99"

Keeping them separate means you can rename a database column, or add an internal field like fraud_score, without breaking the public API. Returning ORM rows straight from routes is how password_hash ends up in a JSON response.

Quick check
A route returns the SQLAlchemy User object directly. What is the most serious risk?
Need a nudge? A hint rules out a wrong answer.

Why testing gets easy

Because the domain is pure and the service takes its repository as a parameter, tests need no server and no database:

tests/test_order_service.py
def test_paying_twice_is_rejected():
    repo = InMemoryOrderRepository()
    repo.save(Order(id=1, total_cents=500))
    service = OrderService(repo)
    service.pay(1)
    with pytest.raises(DomainError):
        service.pay(1)

That test runs in about a millisecond. You keep a few slower tests that use the real SqlOrderRepository against a real database, but the bulk of your rules are covered by fast ones. The testing strategy lesson at the end of this track builds on exactly this seam.

Put it in order6 steps

Order what happens for POST /orders/42/refund in a layered app.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Where a transaction begins and ends

Layers answer "who does what". They also have to answer "who commits". Get this wrong and you get half-saved data that no test catches.

Picture a transfer use case: debit one account, credit another. If the repository commits inside every save(), the debit is permanent before the credit even starts. A crash in between, and money vanishes. The repository cannot know that two saves belong together. Only the use case knows that.

So the rule is: the application (service) layer owns the transaction. One use case, one transaction. The service opens it, calls the domain and the repositories, and commits once at the end. If anything raises, everything rolls back. Repositories only add and flush. They never commit.

  • Not the route. If the route commits, a second entry point (a CLI command, a queue consumer) has to remember to do the same, and one day it will not.
  • Not the repository. It sees one aggregate, not the whole business action.
  • Not the domain. It has no idea a database exists.

Fowler's name for the object that tracks changes during a use case and writes them in one go is the unit of work. SQLAlchemy's Session is one: with session.begin(): commits on success and rolls back on an exception. In Django the equivalent is transaction.atomic() wrapped around the service call.

You can see the all-or-nothing behaviour with the standard library. A sqlite3 connection used as a context manager commits on success and rolls back on an exception:

Predict the outputPython

What does this print?

import sqlite3
conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE users (email TEXT UNIQUE)")
try:
  with conn:
      conn.execute("INSERT INTO users VALUES ('a@x.io')")
      conn.execute("INSERT INTO users VALUES ('b@x.io')")
      conn.execute("INSERT INTO users VALUES ('a@x.io')")
except sqlite3.IntegrityError:
  pass
print(conn.execute("SELECT count(*) FROM users").fetchone()[0])
Need a nudge? Hints walk you through it.

Two traps seniors watch for:

  1. Slow calls inside an open transaction. Calling a payment API or sending an email while the transaction is open holds row locks for the whole network round trip. Under load that becomes lock waits and timeouts. Do the I/O before the transaction, or after the commit.
  2. Side effects that cannot roll back. If you send the "order paid" email and then the commit fails, the customer got an email for an order that does not exist. Either send after commit, or write the message into an outbox table inside the transaction and let a relay send it. The Event-Driven Architecture lesson shows the outbox in detail.
Quick check
A transfer(from_id, to_id, cents) use case debits one account and credits another. Where should the commit happen?
Need a nudge? A hint rules out a wrong answer.

Translating errors at each boundary

Each layer speaks its own error language, and errors get translated as they cross a boundary. They are never passed through raw.

LayerRaisesExample
Data accessCatches driver errors, raises application errorsIntegrityError on users.email becomes EmailTaken
DomainBusiness rule violationsOrderAlreadyPaid, InsufficientFunds
ServiceUse-case failuresNotFound(order 42), PermissionDenied
PresentationHTTP responses404, 409, 422, with a problem details body

Why bother? If sqlalchemy.exc.IntegrityError reaches the route, the route has to know about SQL constraint names to decide between 409 and 500. Swap the database and every route breaks. Worse, a lazy handler returns str(e), and your table names and SQL end up in a public response.

The mapping to HTTP should live in one place: an exception handler registered on the app, not a try/except in every route. Give each application error a status, and let the handler build the body. RFC 9457 "Problem Details for HTTP APIs" (which replaced RFC 7807) is the standard shape: type, title, status, detail, instance, served as application/problem+json.

Python
import sqlite3 # ---- application errors: the vocabulary the service speaksclass AppError(Exception): status, title = 500, "Internal error" class NotFound(AppError): status, title = 404, "Not found" class Conflict(AppError): status, title = 409, "Conflict" class EmailTaken(Conflict): title = "Email already registered" # ---- data access: translate driver errors, never leak themclass SqlUserRepository: def __init__(self, conn): self.conn = conn def add(self, email): try: self.conn.execute("INSERT INTO users (email) VALUES (?)", (email,)) except sqlite3.IntegrityError as e: raise EmailTaken(email) from e def get(self, user_id): row = self.conn.execute("SELECT id, email FROM users WHERE id = ?", (user_id,)).fetchone() if row is None: raise NotFound(f"user {user_id}") return row # ---- service: owns the transactionclass UserService: def __init__(self, conn): self.conn = conn self.users = SqlUserRepository(conn) def register(self, email): with self.conn: # commit on success, roll back on any exception self.users.add(email) def find(self, user_id): return self.users.get(user_id) # ---- presentation: ONE place that maps errors to HTTPdef handle(fn, *args): try: return 200, fn(*args) except AppError as e: return e.status, {"title": e.title, "status": e.status, "detail": str(e)} # Anything else is a bug. Let it crash into a generic 500 and log it. conn = sqlite3.connect(":memory:")conn.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT UNIQUE NOT NULL)")svc = UserService(conn) print(handle(svc.register, "ada@example.com"))print(handle(svc.register, "ada@example.com"))print(handle(svc.find, 1))print(handle(svc.find, 99))
Output
Press Run (⌘ Enter) to see what happens.

The route never imported sqlite3. The repository raised EmailTaken ... from e, which keeps the original error attached as __cause__, so your logs still show the real constraint failure while the client sees a clean 409.

A duplicate email crosses the layers
ClientRouteServiceRepositoryDatabasePOST /usersregister(email)add(email)INSERT INTO usersIntegrityErrorEmailTakenEmailTaken (rolled back)409 problem+json

The route parses and validates the body into a DTO. Bad JSON fails here with a 422, before any business code runs.

1/8

One more rule: unexpected errors stay unexpected. Do not catch Exception in a service and wrap it in a friendly message. A bug should reach the top, get logged with a stack trace and a request id, and return a generic 500. Translating only the errors you understand is what keeps real bugs visible.

Cross-cutting concerns live at the edges

Some concerns touch every request: logging, authentication, metrics, tracing, rate limiting, caching. They are called cross-cutting concerns because they cut across all the layers. If you write them inside each service method, every method starts with the same eight lines, and someone eventually forgets them.

Instead, apply them around the layers, using the tools your framework gives you:

app/main.py
@app.middleware("http")
async def request_context(request: Request, call_next):
    request_id = request.headers.get("x-request-id") or uuid4().hex
    with log_context(request_id=request_id):          # every log line gets the id
        response = await call_next(request)
    response.headers["x-request-id"] = request_id
    return response
 
@app.exception_handler(AppError)
async def app_error(request: Request, exc: AppError):
    return JSONResponse(
        {"title": exc.title, "status": exc.status, "detail": str(exc)},
        status_code=exc.status,
        media_type="application/problem+json",
    )
ConcernWhere it usually goes
Request ids, access logs, timingHTTP middleware
Who is calling (authentication)Middleware or a dependency like FastAPI Depends(current_user)
Error to HTTP mappingOne registered exception handler
Caching a slow readA decorator or caching wrapper around the repository
Retries and timeouts on outbound callsThe adapter or HTTP client for that service

There is one important exception. Authentication (who are you?) is cross-cutting and belongs at the edge. Authorization that depends on business data (can this user refund this order?) is a business rule. It belongs in the service or the domain, where it is tested with the rest of the rules. A middleware that checks "is logged in" is fine. A middleware that checks "owns order 42" has pulled a business rule out to the edge, where nobody looks for it.

Match the pairs0/4 matched

Where should each concern live?

Choose an item, then its match on the other side.

Strict vs relaxed layering, and the sinkhole

In strict (closed) layering, each layer may only call the one directly below it. A route must go through a service, which must go through the domain, which goes through a repository. In relaxed (open) layering, a layer may skip layers below it, for example a route calling a read-only query directly.

Strict layering is easy to reason about. It also produces the architecture sinkhole anti-pattern, a name from Mark Richards' "Software Architecture Patterns": requests that pass through every layer with no logic at all.

smell: three layers that do nothing
@router.get("/products/{id}")
def get_product(id: int, svc: ProductService = Depends()):
    return svc.get_product(id)            # route: pass through
 
class ProductService:
    def get_product(self, id):
        return self.repo.get_product(id)  # service: pass through
 
class ProductRepository:
    def get_product(self, id):
        return self.db.get(Product, id)   # the only real work

A few of these are normal. Every app has simple reads. The usual rule of thumb is about 80/20: if roughly 20% of requests are pure pass-through, that is fine. If most of them are, your layers are ceremony, and every new field means editing four files.

Common fixes, from least to most change:

  • Open the layer for reads. Let simple queries skip the service and go to a query object that returns a DTO directly. Keep writes, where the rules live, strictly layered. This is CQRS in its lightest form, and it fits the Event-Driven Architecture lesson.
  • Let services hold real use cases only. A service method that just forwards a call is a sign the method should not exist yet.
  • Slice vertically. If most of the app is simple CRUD, organise by feature (one folder per use case with its own handler, query and DTO) instead of horizontal layers. This is often called vertical slice architecture. The Modular Monolith lesson shows how to keep the boundaries between such modules clean.
Quick check
A team finds that 85% of their endpoints are a route calling a service calling a repository, with no logic added at any step. What is the best response?
Need a nudge? A hint rules out a wrong answer.
ChallengeEasy

Order lifecycle rules

This is pure domain code: no database, no HTTP, just the rule. Write transition(state, event) that returns the next order state, or None (TypeScript: null) if the move is not allowed.

FromEventTo
pendingpaypaid
pendingcancelcancelled
paidshipshipped
paidcancelrefunded
shippeddeliverdelivered
deliveredreturnreturned
returnedrefundrefunded

Anything not in the table (including unknown states or events) is rejected.

transition("pending", "pay")     ->  "paid"
transition("shipped", "cancel")  ->  None   (too late to cancel)
def transition(state: str, event: str) -> str | None: # Look the move up in one table of allowed transitions. pass
Key terms
layered architecture
Splitting code into presentation, application, domain and data access layers, each calling only the one below.
domain model
An object holding business state and the rules that change it, with no I/O or framework imports.
repository
An object with collection-like methods (get, save, list) that hides how domain objects are stored.
DTO
Data transfer object: a plain shape used to cross a boundary like an API request or response.
fat controller
A route handler that mixes HTTP, SQL and business rules, making each hard to change or test.
unit of work
An object that tracks the changes made during one use case and commits them together in one transaction.
error translation
Catching an error from a lower layer and raising one in the current layer's vocabulary, keeping the original as the cause.
cross-cutting concern
Something every request needs, like logging, authentication or metrics, applied around the layers instead of inside each one.
architecture sinkhole
An anti-pattern where requests pass through layers that add no logic, so layering becomes pure ceremony.