Skip to lesson

Layered architecture at system level

ShopLite's product search shows a product that the product page hides. The same rule lives in two places, and one copy was missed. Where should each rule live, and which machines run which part?

Your turn: where does each piece go?

ShopLite got popular and traffic is 100 times higher. Before you read the design, think it through on paper:

  • Draw the path of one "show product 1" request from the phone to the database. Which hops stay inside one program, and which cross the network?
  • The rule "inactive products are hidden" is needed by the product page and by search. Where would you write it so it exists only once?
  • Every request must be logged, and every /me/ request needs a token. Would you repeat that in each endpoint?
Write your answers down first. The sections below show one good design to compare with yours.

One good design: controller, service, repository

A layer is a group of classes with one job that calls only the layer directly below it: the controller handles HTTP, the service holds business rules and the repository talks to the database.

A request enters the controller, which calls the service, which calls the repository. Run the example and watch the answer travel back up.

Example 1 · One request through controller, service and repository

LayerTraceDemo.javaJava
import java.util.HashMap;import java.util.Map;import java.util.Optional;
// Prices are whole rupees to keep the simulation short; ShopLite itself uses BigDecimal.record Product(int id, String name, int price, int stock) {}
class ProductRepository {    private final Map<Integer, Product> table = new HashMap<>();
    ProductRepository() {        table.put(1, new Product(1, "Redmi Note 13 5G", 17999, 40));        table.put(6, new Product(6, "boAt Airdopes 141", 1299, 0));    }
    Optional<Product> findById(int id) {        System.out.println("    [repository] SELECT * FROM products WHERE id = " + id);        return Optional.ofNullable(table.get(id));    }}
class ProductService {    private final ProductRepository repository;
    ProductService(ProductRepository repository) {        this.repository = repository;    }
    Product getProduct(int id) {        System.out.println("  [service] getProduct(" + id + ")");        return repository.findById(id)                .orElseThrow(() -> new IllegalArgumentException("product " + id + " not found"));    }}
class ProductController {    private final ProductService service;
    ProductController(ProductService service) {        this.service = service;    }
    String get(String path) {        System.out.println("[controller] GET " + path);        int id = Integer.parseInt(path.substring(path.lastIndexOf('/') + 1));        try {            Product p = service.getProduct(id);            return "200 {\"id\":" + p.id() + ",\"name\":\"" + p.name() + "\",\"price\":" + p.price() + ".00}";        } catch (IllegalArgumentException e) {            return "404 " + e.getMessage();        }    }}
public class LayerTraceDemo {    public static void main(String[] args) {        ProductController controller = new ProductController(new ProductService(new ProductRepository()));
        System.out.println("-> " + controller.get("/api/v1/products/1"));        System.out.println("-> " + controller.get("/api/v1/products/99"));    }}
Output
[controller] GET /api/v1/products/1
  [service] getProduct(1)
    [repository] SELECT * FROM products WHERE id = 1
-> 200 {"id":1,"name":"Redmi Note 13 5G","price":17999.00}
[controller] GET /api/v1/products/99
  [service] getProduct(99)
    [repository] SELECT * FROM products WHERE id = 99
-> 404 product 99 not found

What this code does

  • Each layer prints a line, so you can see the call go down from the controller to the repository and the answer come back. The controller is the only class that knows the path and the status codes.
  • A missing product becomes an exception in the service and a 404 in the controller. Prices are whole rupees to keep the code short; the real ShopLite uses BigDecimal.

The controller turns an HTTP request into a method call and the result into a status code and JSON. The service holds rules such as "inactive products are hidden". The repository talks to the database and nothing else.

Sections 15 and 16 built ShopLite this way with Spring; here the same three roles are plain Java classes. Common mistake: a controller that reaches the repository "just this once", which the smells section shows.

Order of execution

Put one request in order

Tap the steps in the order they happen for GET /api/v1/products/1.

Layers inside the app tier, tiers across the network

A tier is a part of the system that runs on its own machines: the client tier (phone, browser), the app tier (the servers running ShopLite) or the data tier (MySQL).

ShopLite runs in three places: the phone, the app servers and MySQL. The three code layers all sit inside the app tier. The diagram marks where the network is crossed.

Text
Client tier         App tier (copied on N servers)                 Data tier[Phone app] --HTTPS--> [Controller -> Service -> Repository] --SQL--> [MySQL]               network        method calls inside one JVM      network

Example 2 · Layer calls cost microseconds, tier hops cost milliseconds

TierCostDemo.javaJava
import java.util.List;
record Hop(String from, String to, String tier, boolean network, double ms) {}
public class TierCostDemo {    public static void main(String[] args) {        // Typical figures for one product read (a simplified model, not a measurement)        List<Hop> hops = List.of(                new Hop("phone", "load balancer", "client -> app tier", true, 35),                new Hop("load balancer", "controller", "LB -> app tier", true, 0.5),                new Hop("controller", "service", "app tier", false, 0.001),                new Hop("service", "repository", "app tier", false, 0.001),                new Hop("repository", "MySQL", "app -> data tier", true, 1.0),                new Hop("MySQL", "query + result", "data tier", false, 4.0),                new Hop("app tier", "phone", "app -> client", true, 35));
        double network = 0;        double total = 0;        for (Hop h : hops) {            total += h.ms();            if (h.network()) {                network += h.ms();            }            System.out.printf("%-14s -> %-15s %-18s %-8s %7.3f ms%n",                    h.from(), h.to(), h.tier(), h.network() ? "network" : "local", h.ms());        }        System.out.printf("Total %.3f ms, of which %.1f ms is network between tiers%n", total, network);    }}
Output
phone          -> load balancer   client -> app tier network   35.000 ms
load balancer  -> controller      LB -> app tier     network    0.500 ms
controller     -> service         app tier           local      0.001 ms
service        -> repository      app tier           local      0.001 ms
repository     -> MySQL           app -> data tier   network    1.000 ms
MySQL          -> query + result  data tier          local      4.000 ms
app tier       -> phone           app -> client      network   35.000 ms
Total 75.502 ms, of which 71.5 ms is network between tiers

What this code does

  • The figures are a simplified model of one product read. Controller to service to repository are method calls inside one JVM and cost about 0.001 ms each.
  • Almost all of the 75 ms is network between tiers. Adding layers does not slow a request; adding network hops does, which matters in the microservices lesson.

Layers are about code organisation inside one program; tiers are about deployment across the network.

Calls between layers are plain method calls that take microseconds. Calls between tiers cross the network and take milliseconds. That is why the app tier can be copied onto many servers, while the data tier is the shared place everyone reads and writes.

Predict the output

What does one more layer cost?

Pick the best estimate for a new class between the service and the repository.

A new class sits between the service and the repository. How much time does it add?

phone -> load balancer 35 ms (network)
controller -> service 0.001 ms (method call)
repository -> MySQL 1 ms (network)

Where cross-cutting concerns live

A cross-cutting concern is work that every request needs, whatever the endpoint, such as logging, authentication, validation or caching. It is handled once, in one place, not copied into every controller.

Logging and authentication wrap every request, so they sit in front of the controller. The example chains a logging filter and an auth filter before one controller.

Example 3 · Logging and auth in filters, validation at the edge

CrossCuttingDemo.javaJava
record Request(String method, String path, String token, String body) {}
interface Handler {    String handle(Request r);}
// Cross-cutting: runs for every request, before and after the controllerclass LoggingFilter implements Handler {    private final Handler next;
    LoggingFilter(Handler next) {        this.next = next;    }
    public String handle(Request r) {        System.out.println("[log] " + r.method() + " " + r.path());        String response = next.handle(r);        System.out.println("[log] -> " + response.substring(0, 3));        return response;    }}
// Cross-cutting: one place decides who may call /me/... endpointsclass AuthFilter implements Handler {    private final Handler next;
    AuthFilter(Handler next) {        this.next = next;    }
    public String handle(Request r) {        if (r.path().startsWith("/api/v1/me/") && r.token() == null) {            return "401 unauthorized";        }        return next.handle(r);    }}
class OrderController implements Handler {    public String handle(Request r) {        if (r.method().equals("GET")) {            return "200 page of products";        }        if (r.body() == null || r.body().isBlank()) {     // request-shape validation at the edge            return "400 validation-failed: items is required";        }        return "201 order created";    }}
public class CrossCuttingDemo {    public static void main(String[] args) {        Handler app = new LoggingFilter(new AuthFilter(new OrderController()));
        System.out.println(app.handle(new Request("GET", "/api/v1/products", null, null)));        System.out.println(app.handle(new Request("POST", "/api/v1/me/orders", null, "{...}")));        System.out.println(app.handle(new Request("POST", "/api/v1/me/orders", "jwt-abc", "")));        System.out.println(app.handle(new Request("POST", "/api/v1/me/orders", "jwt-abc", "{\"items\":[...]}")));    }}
Output
[log] GET /api/v1/products
[log] -> 200
200 page of products
[log] POST /api/v1/me/orders
[log] -> 401
401 unauthorized
[log] POST /api/v1/me/orders
[log] -> 400
400 validation-failed: items is required
[log] POST /api/v1/me/orders
[log] -> 201
201 order created

What this code does

  • LoggingFilter wraps AuthFilter, which wraps the controller, so every request is logged and every /me/ request is checked for a token in exactly one place.
  • The controller only checks the request shape (a missing body gives 400). Spring Security's filter chain from Section 17 is the real version of this pattern.

Where each concern lives:

  • Logging and authentication: in filters that wrap every request before it reaches a controller (Spring Security's filter chain, from Section 17).
  • Request-shape validation (required fields, 1-10 items): at the controller edge, with Bean Validation in Spring.
  • Business validation that needs data (enough stock, order still PLACED): in the service.
  • Caching: around service or repository calls that read popular data, never inside the controller.

Smells: skipping a layer, HTTP inside the service

A layering smell is code that works today but breaks the one-job-per-layer rule, such as a controller that reads the database directly or a service that returns HTTP objects.

Two smells are common: a controller that reads the data itself, and a service that returns a status code. Run both and compare the answers, then see the fix.

Example 4 · Smell: a controller that reads the table itself

LayerSmellDemo.javaJava
import java.util.HashMap;import java.util.Map;
record Product(int id, String name, boolean active) {}
record HttpResult(int status, String body) {}
class ProductService {    final Map<Integer, Product> table;
    ProductService(Map<Integer, Product> table) {        this.table = table;    }
    HttpResult getProduct(int id) {                  // smell 2: HTTP inside the service        Product p = table.get(id);        if (p == null || !p.active()) {            return new HttpResult(404, "not found");        }        return new HttpResult(200, p.name());    }}
class SmellyController {    private final ProductService service;    private final Map<Integer, Product> table;
    SmellyController(ProductService service, Map<Integer, Product> table) {        this.service = service;        this.table = table;    }
    String getProduct(int id) {        HttpResult r = service.getProduct(id);        return r.status() + " " + r.body();    }
    String searchByName(String name) {               // smell 1: controller reads the table itself        for (Product p : table.values()) {            if (p.name().contains(name)) {                return "200 " + p.name();            }        }        return "404 not found";    }}
public class LayerSmellDemo {    public static void main(String[] args) {        Map<Integer, Product> table = new HashMap<>();        table.put(3, new Product(3, "Old Nokia 3310", false));   // inactive
        SmellyController c = new SmellyController(new ProductService(table), table);        System.out.println("GET /products/3         -> " + c.getProduct(3));        System.out.println("GET /products?q=Nokia   -> " + c.searchByName("Nokia"));    }}
Output
GET /products/3         -> 404 not found
GET /products?q=Nokia   -> 200 Old Nokia 3310

What this code does

  • getProduct goes through the service, which hides inactive products. searchByName reads the map directly and returns the inactive Nokia 3310: the business rule was skipped.
  • The service also returns HttpResult, a status code. A background job calling it would have to understand HTTP, which it should never need.

Example 5 · Fix: rules in the service, HTTP only in the controller

LayerFixDemo.javaJava
import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.Optional;
record Product(int id, String name, boolean active) {}
class ProductNotFoundException extends RuntimeException {    ProductNotFoundException(int id) {        super("product " + id + " not found");    }}
class ProductRepository {    private final Map<Integer, Product> table = new HashMap<>();
    ProductRepository() {        table.put(3, new Product(3, "Old Nokia 3310", false));        table.put(4, new Product(4, "Nokia G42", true));    }
    Optional<Product> findById(int id) {        return Optional.ofNullable(table.get(id));    }
    List<Product> findByNameContaining(String text) {        List<Product> found = new ArrayList<>();        for (Product p : table.values()) {            if (p.name().contains(text)) {                found.add(p);            }        }        return found;    }}
class ProductService {                       // business rules live here, once    private final ProductRepository repository;
    ProductService(ProductRepository repository) {        this.repository = repository;    }
    Product getProduct(int id) {        return repository.findById(id)                .filter(Product::active)                .orElseThrow(() -> new ProductNotFoundException(id));    }
    List<String> search(String text) {        List<String> names = new ArrayList<>();        for (Product p : repository.findByNameContaining(text)) {            if (p.active()) {                names.add(p.name());            }        }        return names;    }}
class ProductController {                    // HTTP lives here: paths, status codes    private final ProductService service;
    ProductController(ProductService service) {        this.service = service;    }
    String getProduct(int id) {        try {            return "200 " + service.getProduct(id).name();        } catch (ProductNotFoundException e) {            return "404 " + e.getMessage();        }    }
    String search(String text) {        return "200 " + service.search(text);    }}
public class LayerFixDemo {    public static void main(String[] args) {        ProductController c = new ProductController(new ProductService(new ProductRepository()));        System.out.println("GET /products/3         -> " + c.getProduct(3));        System.out.println("GET /products?q=Nokia   -> " + c.search("Nokia"));    }}
Output
GET /products/3         -> 404 product 3 not found
GET /products?q=Nokia   -> 200 [Nokia G42]

What this code does

  • Both endpoints now go through ProductService, so the "inactive is hidden" rule is applied once and search returns only the active Nokia G42.
  • The service throws ProductNotFoundException; the controller alone turns it into 404. The same service could now be called from a queue worker unchanged.

The fix is the same in both cases: move the rule into the service once, let the service return domain data or throw a meaningful exception, and let only the controller map results to HTTP status codes.

A quick test for any pull request: does every call go only one layer down? A controller that calls a repository, or a service that mentions ResponseEntity, fails it.

Find the bug

Find the layering smell

Each snippet breaks the layering rule. Tap the line that is wrong, then check the fix.

A search endpoint. The service already hides inactive products.

Round 1 of 2

Next step

Check your understanding

10 quick questions