In Module 2 we separated the domain from the infrastructure inside the orders module. That separation is a particular case of an older and more general idea: organizing a system in layers, each with one kind of work and with clear rules about who may call whom. In this lesson you will study which layers exist, what each one should contain, how logical layers differ from physical tiers, and how layers coexist with hexagonal architecture. It is the first lesson of Module 3, in which Verdalia lifts its eyes from the code to put the components of the system in order.
What a Layer Is and Why Organize in Layers
A layer is a group of components that do the same kind of work and sit at the same distance from the user. The layer closest to the user receives its requests; the one farthest away stores the data. In between, the decisions are made.
In Module 2 we applied separation of concerns to a function: view_product was split into a part that fetches data, another that decides, and another that presents. A layered architecture applies that same division to the whole system and turns it into a rule.
Organizing in layers brings four benefits:
- Every change has a place. A change to the page design affects one layer; a change to a pricing rule affects another.
- Business rules can be tested on their own, with no browser and no database.
- A layer can be replaced without modifying the others, as long as it keeps the way it is used.
- The team shares a map. Faced with a new file, everyone knows where it should go and what it may contain.
It is worth clarifying from the start how layers combine with the modules of the monolith. There are two ways to divide the code:
| Division | First level of folders | Consequence |
|---|---|---|
| By layers | presentation/, business/, data/ |
A change in shipping means touching three folders shared by every area |
| By business modules, with layers inside | catalog/, orders/, shipping/ |
A change in shipping stays inside its module; the layers organize the interior |
Verdalia chose the second in ADR-001: the seven modules come first, and the layers organize each module on the inside. The two divisions complement each other: modules separate by business area and layers separate by kind of work.
The Usual Layers and Their Responsibility
The number of layers and their names vary from one author to another. The following five are the ones you will find most often:
| Layer | Responsibility | Should contain | Should not contain |
|---|---|---|---|
| Presentation | Receive the request and show the result | Web routes, input format checks, templates, response codes | Business rules, SQL |
| Business logic | Decide | Rules, calculations, and coordination of each operation | HTML, HTTP details, SQL |
| Data access | Store and retrieve | Queries, conversion between rows and objects | Business rules, presentation format |
| Database | Store with integrity | Tables, keys, integrity constraints | Business rules in triggers or stored procedures |
| Infrastructure | Support all the others | Server, operating system, network, web server, configuration, logging | Anything that depends on the business |
A few clarifications:
- Presentation is not always a page. An API that returns JSON is presentation too: it receives requests and shapes the responses.
- Business logic is sometimes split in two. The application layer coordinates a complete operation, such as
OrderService.confirm. The domain layer contains the rules, such asOrder.totalor the shipping cost calculation. In a system the size of Verdalia, treating them as a single layer is enough. - Data access and persistence are the same concept. It is the application code that talks to the database. The database is a different layer: a separate program, with its own rules.
- Infrastructure is cross-cutting. It does not receive chained calls like the others; it holds all of them up.
A simple test for placing a piece of code is to ask why it would change:
| If it changes because... | It belongs to... |
|---|---|
| The website design or the format of a response changes | Presentation |
| A business rule changes | Business logic |
| The name of a column or the way of querying changes | Data access |
| The engine or the storage structure changes | Database |
| The server, the network, or the operating system changes | Infrastructure |
Dependency Rules Between Layers
Layers are only useful if three rules are respected.
1. One direction. Calls go from top to bottom: presentation calls business, and business calls data access. A lower layer never calls a higher one, nor knows about it. Responses travel back up as return values.
2. Closed layers. A layer is closed when a request cannot skip it: to reach the layer below, you must go through it. It is the default option. With closed layers, a change in data access can only affect business, which is its only client.
3. Open layers, as a declared exception. A layer is open when it may be crossed without being used. It makes sense for layers of auxiliary services that not every operation needs. Every open layer should be documented, because it increases coupling: the layer above now knows two layers.
flowchart TB
presentation["Presentation - closed"] --> business["Business logic - closed"]
business --> common["Common services - open"]
common --> data["Data access - closed"]
business -->|"may skip it"| data
data --> db[("Database")]
presentation -.->|"forbidden"| data
In the diagram, business can go directly to data access because the intermediate layer is open. Presentation cannot: business logic is closed.
| Aspect | Closed layer | Open layer |
|---|---|---|
| Can it be skipped? | No | Yes |
| Isolation from changes | High | Lower |
| Steps per request | All | Only the necessary ones |
| When to use it | By default | Auxiliary layers, with the decision documented |
At Verdalia, every layer is closed. The rule is checked the same way as the dependency rule from Module 2, by looking at the imports: a presentation file may not contain import psycopg2, and a data access file may not contain import flask.
Logical Layers and Physical Tiers
There are two words that are often translated the same way and mean different things:
| Concept | Term | What it separates | Question it answers |
|---|---|---|---|
| Logical layer | Layer | The code, according to its responsibility | How is the program organized? |
| Physical tier | Tier | The execution, in different processes or machines | Where does each part run? |
A system can have three logical layers and run on a single machine. Depending on the number of physical tiers, we speak of:
| Architecture | Division | Example | Remarks |
|---|---|---|---|
| 1 tier | Everything on the same machine | A desktop application with its data in a local file | Simple, no network; not shared |
| 2 tiers | Client and server | A desktop program that queries a central database | The logic usually ends up split between the two |
| 3 tiers | Client, application server, and database server | Browser, web application, and database on separate machines | Each tier can be sized and protected separately |
| N tiers | More than three | Tiers such as a load balancer, a cache, or several services are added | More flexibility and more pieces to operate |
Where is Verdalia? Seen from outside there are two machines: the customer's browser and the verdalia-prod-01 server. Inside the server, Nginx, the application, and PostgreSQL are different processes sharing one machine. It is a three-tier architecture missing the physical separation: if the server runs out of memory, all three go down at once, as happened the day before Mother's Day.
Separating tiers has a price. Every hop between machines adds a network wait and a new point of failure. In exchange, it allows each tier to be expanded or protected on its own. Spreading the store across several machines is the work of Module 4. What matters now is the relationship between the two concepts: well-separated logical layers make it possible to separate the physical tiers later. With the tangled code of view_product, there was nothing to spread.
Layers and Hexagonal Architecture
In the last lesson of Module 2 we organized the orders module with ports and adapters. Is it an alternative to layers? It is really a variant. The pieces correspond:
| Layered architecture | Hexagonal architecture | At Verdalia |
|---|---|---|
| Presentation | Inbound adapter | Flask web routes |
| Business logic | Core | OrderService, CatalogService |
| Data access | Outbound adapter | PostgresOrderRepository, ProductRepository |
| Database and external services | The outside | PostgreSQL, PagoRaíz, email server |
The difference lies in one arrow. In classic layers, business depends on data access: it imports it and calls it. In hexagonal architecture, that dependency is inverted: business declares a port and data access implements it.
| Aspect | Classic layers | Hexagonal |
|---|---|---|
| Dependency between business and data | Business imports the concrete repository | The repository implements an interface of the business |
| Number of files | Lower | Higher: the ports must be added |
| Testing the business | By handing it a substitute repository | With in-memory adapters that fulfill the port |
| Changing technology | Affects the repository; the business is reviewed | Affects only the adapter |
| When it pays off | Modules with few rules and a single data store | Modules with valuable rules and several external systems |
The two forms coexist at Verdalia, as ADR-002 established:
| Module | Internal organization | Reason |
|---|---|---|
| Orders, payments, cart, inventory | Ports and adapters | They combine business rules with external systems |
| Catalog | Three classic layers | Few rules; almost everything is querying and displaying |
| Shipping | Business logic only | It does not talk to the outside |
In every case the essentials hold: presentation contains no rules, rules contain no SQL, and dependencies go in one direction.
The Journey of a Request Through Verdalia
The Starting Point
In the last week of November, Íker reorganized the catalog module. It is the most visited part of the store and the protagonist of scenario QS-1. Of its 14 web routes, 11 had SQL queries written inside the Flask function itself.
In Module 2, view_product was split into four functions, but they were still together in the same file and the route knew all of them. Now each function goes to its layer:
| File | Layer | Contents |
|---|---|---|
verdalia/catalog/web.py |
Presentation | The view_product route and product_page |
verdalia/catalog/service.py |
Business logic | CatalogService, price_with_vat, stock_notice |
verdalia/catalog/repository.py |
Data access | ProductRepository, heir of find_product |
The Code
So that you can run it without installing anything, the example gathers the three layers in a single file and uses sqlite3, the database bundled with Python. It also replaces Flask with an ordinary function. The print messages are there only to follow the journey.
import sqlite3
from dataclasses import dataclass
# ---------------------------------------------------------------
# DATA ACCESS LAYER: verdalia/catalog/repository.py
# ---------------------------------------------------------------
class ProductRepository:
def __init__(self, connection):
self._connection = connection
def find(self, product_id):
print(" [Data] SELECT on the products table")
cursor = self._connection.cursor()
cursor.execute(
"SELECT name, price, stock FROM products WHERE id = ?",
(product_id,),
)
row = cursor.fetchone()
if row is None:
return None
name, price, stock = row
return {"name": name, "price": float(price), "stock": stock}
# ---------------------------------------------------------------
# BUSINESS LOGIC LAYER: verdalia/catalog/service.py
# ---------------------------------------------------------------
VAT = 0.21
LAST_UNITS_THRESHOLD = 5
class ProductNotFound(Exception):
"""No product exists with that identifier."""
@dataclass
class ProductDetails:
name: str
final_price: float
notice: str
def price_with_vat(price):
return round(price * (1 + VAT), 2)
def stock_notice(stock):
return "Last units" if stock < LAST_UNITS_THRESHOLD else ""
class CatalogService:
def __init__(self, repository):
self._repository = repository
def product_details(self, product_id):
print(" [Business] Prepare the product details")
product = self._repository.find(product_id)
if product is None:
raise ProductNotFound(product_id)
return ProductDetails(
name=product["name"],
final_price=price_with_vat(product["price"]),
notice=stock_notice(product["stock"]),
)
# ---------------------------------------------------------------
# PRESENTATION LAYER: verdalia/catalog/web.py
# ---------------------------------------------------------------
def product_page(details):
return (
f"<h1>{details.name}</h1><p>€{details.final_price:.2f}</p>"
f"<p>{details.notice}</p>"
)
def view_product(service, product_id):
print(f"[Presentation] GET /product/{product_id}")
try:
details = service.product_details(product_id)
except ProductNotFound:
return "<h1>Product not found</h1>", 404
return product_page(details), 200
# ---------------------------------------------------------------
# ASSEMBLY: what app.py does in the store
# ---------------------------------------------------------------
connection = sqlite3.connect(":memory:")
connection.execute(
"CREATE TABLE products (id INTEGER PRIMARY KEY, name TEXT, "
"price REAL, stock INTEGER)"
)
connection.execute("INSERT INTO products VALUES (2087, 'Potted olive tree', 33.00, 3)")
service = CatalogService(ProductRepository(connection))
for product_id in (2087, 9999):
html, status = view_product(service, product_id)
print(f"[Response] {status}: {html}\n")Output:
[Presentation] GET /product/2087 [Business] Prepare the product details [Data] SELECT on the products table [Response] 200: <h1>Potted olive tree</h1><p>€39.93</p><p>Last units</p> [Presentation] GET /product/9999 [Business] Prepare the product details [Data] SELECT on the products table [Response] 404: <h1>Product not found</h1>
Explanation:
- Data access.
ProductRepositoryis the only class that knows theproductstable. It receives the connection in the constructor and returns a dictionary with simple data, orNoneif the product does not exist. It decides nothing. - Business logic.
CatalogServicereceives the repository, asks it for the product, and applies the rules you already knew. It returns aProductDetails, an object with what the page needs, already calculated. If the product does not exist, it raisesProductNotFound, an exception with business vocabulary. - Presentation.
view_productdoes three things: it receives the request, calls the service, and shapes the response. It translates the business exception into the 404 code, which is HTTP vocabulary. It does not know that a database exists. - Assembly. The last lines create the connection and chain the pieces together. In the store, that work is done by the composition root,
app.py. - The output shows the journey. The request goes down layer by layer, and the response comes back up the same path.
In the real store, the connection is a PostgreSQL one and the parameter placeholder is %s instead of ?. That difference affects a single layer, which is exactly what we wanted. The real presentation is a Flask route:
# verdalia/catalog/web.py (excerpt)
@catalog.route("/product/<int:product_id>")
def view_product(product_id):
try:
details = catalog_service.product_details(product_id)
except ProductNotFound:
return render_template("not_found.html"), 404
return render_template("product.html", details=details)The HTML has moved to templates, separate files that Flask fills in with the product details. catalog_service is the object assembled in app.py.
The complete journey, including the layers that are not store code:
sequenceDiagram
participant C as Browser
participant N as Nginx
participant P as Presentation
participant L as Business logic
participant D as Data access
participant B as PostgreSQL
C->>N: GET /product/2087
N->>P: Forwards the request
P->>L: product_details 2087
L->>D: find 2087
D->>B: SQL query
B-->>D: Product row
D-->>L: Product data
L-->>P: ProductDetails
P-->>N: HTML page
N-->>C: 200 response
A Nuance About Dependencies
CatalogService receives the repository through the constructor, but there is no abstract ProductRepository interface. It is the classic layered organization: business knows the layer below. Since Python does not force you to declare types, in the tests it is enough to hand it a substitute object with a find method:
class FakeRepository:
def find(self, product_id):
return {"name": "Lavender", "price": 6.50, "stock": 40}
details = CatalogService(FakeRepository()).product_details(310)
print(details)Output, without the trace messages:
With this technique, Íker added 6 tests to the catalog. The store's total went from 23 to 29.
Antipatterns of Layered Architecture
The Sinkhole Layer
A sinkhole layer is a layer that receives a request and passes it on to the next one without doing anything. An example would be a service whose only content was this:
Happening in some operations is normal: there are queries with no rules. The problem appears when it is the majority. As a guideline, if around 20% of operations are pass-through, the structure is reasonable. If they approach 80%, the layers are adding ceremony without providing isolation, and it is better to simplify the module or declare some layer open.
Business Logic in the Presentation
It happens when a template or a route makes decisions. A typical case is a template that calculates the price with tax, or a check that is only done with JavaScript in the browser. The rule ends up hidden, cannot be reused, and anyone calling the server by another path skips it.
Business Logic in the Database
It happens when the rules live in triggers or stored procedures. For example, a trigger that zeroed the shipping cost of orders over €60. Anyone reading the application code would not understand why the amount changes, the rule would have no tests, and it would sit outside the usual version control.
The database should protect integrity: keys, required values, or the fact that stock cannot be negative. The difference is that those constraints prevent impossible data, whereas business rules decide what the store does.
Skipping Layers
It is the route that queries the database directly “just this once,” because going through the service seemed like a lot of work for a simple query. Every skip is a dependency that does not appear on the blueprint. It was the state of the catalog before this lesson.
Summary
| Antipattern | Symptom | Remedy |
|---|---|---|
| Sinkhole layer | Most methods only delegate | Simplify the module or open the layer, and document it |
| Logic in the presentation | Business calculations or conditions in routes and templates | Move them to the service and hand over the result already calculated |
| Logic in the database | Triggers or stored procedures with business rules | Take the rule to the business logic; leave only integrity in the database |
| Skipping layers | SQL in the routes, forbidden imports | Code review and automated import checks |
Common Mistakes and Tips
- Confusing layers with folders. Creating three folders does not create three layers. What defines them is the dependency rule, and that is checked in the imports.
- Confusing layers with tiers. Having three layers does not mean having three servers, nor the other way around.
- Returning database objects to the presentation. If the route receives a cursor or a row, it depends on the column names again. The service should hand over its own objects, such as
ProductDetails. - Using the vocabulary of one layer in another. A service that returns the 404 code is speaking HTTP. It should raise
ProductNotFoundand let the presentation translate it. - Applying the same layers to every module. The shipping module has no data access, and forcing it to have one would create a sinkhole layer.
- Reorganizing everything at once. Íker moved the catalog routes one at a time, with the store running, and started with the most visited ones.
- Practical tip. When reviewing a change, look at the file's imports first. They tell you which layer it is in and whether it respects the rules, before you read a single line of logic.
Exercises
Exercise 1: Everything in Its Layer
Indicate which layer each element belongs to:
- The
product.htmltemplate. - The rule “a customer cannot add more units to the cart than there are in stock.”
- The query
SELECT * FROM cart_items WHERE cart_id = %s. - The constraint that prevents the
stockcolumn from taking negative values. - The Nginx configuration that serves the product images.
- The code that turns the
InsufficientStockexception into a message for the customer.
Exercise 2: A Business Change
Andrés asks that products with no stock show the notice “Sold out” instead of “Last units.” Indicate which catalog files need to be modified and write the change.
Exercise 3: Spotting Antipatterns
Point out the problems in this cart route and propose how to divide it:
@cart.route("/cart/add", methods=["POST"])
def add_to_cart():
product_id = int(request.form["product_id"])
quantity = int(request.form["quantity"])
cursor = connection.cursor()
cursor.execute("SELECT stock FROM products WHERE id = %s", (product_id,))
stock = cursor.fetchone()[0]
if quantity > stock:
return "<p>Not enough units left</p>", 409
cursor.execute(
"INSERT INTO cart_items (cart_id, product_id, quantity) "
"VALUES (%s, %s, %s)",
(session["cart_id"], product_id, quantity),
)
connection.commit()
return redirect("/cart")Solutions
Solution to Exercise 1
- Presentation. It shapes what the customer sees.
- Business logic. It is a decision of the store.
- Data access. It is application code that talks to the database.
- Database. It is an integrity constraint: it prevents impossible data.
- Infrastructure. It does not depend on the business.
- Presentation. It translates a business result into the user's language.
Solution to Exercise 2
Only the business logic changes, in verdalia/catalog/service.py:
def stock_notice(stock):
if stock == 0:
return "Sold out"
return "Last units" if stock < LAST_UNITS_THRESHOLD else ""The repository already hands over the stock, and the template already shows whatever notice it receives. It is worth adding a test for the zero-stock case.
Common mistake: solving it in the template with a condition on the stock. It would work, but the rule would stay in the presentation and the cart could not reuse it.
Solution to Exercise 3
Problems:
- It skips layers. The route runs SQL directly and uses the global variable
connection. - There is business logic in the presentation. The comparison between the quantity and the stock is a rule.
- It reads a table that belongs to other modules. The cart queries
productson its own. It is one of the pending issues from Module 2, which we will resolve in the last lesson of this module.
Proposed division:
| Layer | Piece | Contents |
|---|---|---|
| Presentation | The route | Reads the form, calls the service, and translates InsufficientStock into the 409 code |
| Business logic | CartService.add(cart_id, product_id, quantity) |
Asks for the stock, applies the rule, and orders the item to be saved |
| Data access | CartRepository.save_item(...) |
Runs the INSERT |
Since the cart is among the modules of ADR-002, the service will receive its collaborators through ports.
Conclusion
In this lesson you have seen that a layer groups the code that does one kind of work, and that the usual layers are presentation, business logic, data access, database, and infrastructure. You have learned the rules that give them value: calls in one direction and layers closed by default. You have also distinguished logical layers, which organize the code, from physical tiers, which indicate where each part runs. And you have verified that hexagonal architecture is a variant of layers that inverts the dependency between business and data.
At Verdalia, the catalog no longer has SQL in its routes: 11 of its 14 routes had it, and today none does. The request to view a product travels through three layers with clear responsibilities, and the store has 29 automated tests.
All those layers still run inside a single application. The next question is whether it should stay that way. In October, ADR-001 answered yes, with review conditions. In the next lesson, “Microservices vs. Monoliths,” we will compare the two options in depth and the team will decide, with explicit criteria, whether any piece of the store deserves to become an independent service.
