Backend architecture practice
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
Four mistakes show up again and again in design reviews: choosing microservices by fashion, hiding state in one server, doing slow work inside the request, and letting layers skip each other. Each has a one-line question that catches it.
Mistake 1: choosing microservices by fashion
"Netflix uses microservices, so we will too" ignores why they paid for them. Run the example to see what team size and load suggest.
Example 1 · Picking an architecture from team size and load
import java.util.List;
record Company(String name, int developers, int teams, boolean partsScaleVeryDifferently, boolean canRunManyServices) {}
public class ArchitecturePicker { static String pick(Company c) { if (c.teams() >= 4 && c.partsScaleVeryDifferently() && c.canRunManyServices()) { return "microservices, split one module at a time"; } if (c.developers() >= 6 || c.teams() >= 2) { return "modular monolith"; } return "monolith"; }
public static void main(String[] args) { List<Company> companies = List.of( new Company("Library app (2 students)", 2, 1, false, false), new Company("ShopLite (8 devs, 2 teams)", 8, 2, true, false), new Company("Ticketing app (120 devs)", 120, 15, true, true), new Company("Exam portal (5 devs)", 5, 1, false, true));
for (Company c : companies) { System.out.printf("%-31s -> %s%n", c.name(), pick(c)); } }}Library app (2 students) -> monolith ShopLite (8 devs, 2 teams) -> modular monolith Ticketing app (120 devs) -> microservices, split one module at a time Exam portal (5 devs) -> monolith
What this code does
pickasks the three questions in order. Only the 120-developer company with very different load and the ability to run services gets microservices.- ShopLite has scaling differences but no team to run many services, so a modular monolith is the right step. The rules are a thinking aid, not a formula.
Ask three questions: how many teams change this code, do parts need very different scaling, and can we run many services?
For one team the answer is a monolith; for a few teams, a modular monolith; only with many teams, very different load and the skills to operate them, split services, one module at a time.
Mistake 2: hidden per-server state
Per-server state hides in maps, sessions, OTP stores, "already used" sets and local files. Run the example to see an OTP vanish between two servers.
Example 2 · An OTP saved on one server, checked on another
import java.util.HashMap;import java.util.Map;
class AuthServer { final String name; private final Map<String, String> otpByPhone = new HashMap<>(); // hidden per-server state
AuthServer(String name) { this.name = name; }
String sendOtp(String phone, String otp) { otpByPhone.put(phone, otp); return name + ": OTP sent to " + phone; }
String verify(String phone, String otp) { boolean ok = otp.equals(otpByPhone.get(phone)); return name + ": " + (ok ? "login OK" : "wrong or expired OTP"); }}
public class OtpStateBug { public static void main(String[] args) { AuthServer app1 = new AuthServer("app-1"); AuthServer app2 = new AuthServer("app-2");
System.out.println(app1.sendOtp("9876543210", "482913")); // request 1 -> app-1 System.out.println(app2.verify("9876543210", "482913")); // request 2 -> app-2 }}app-1: OTP sent to 9876543210 app-2: wrong or expired OTP
What this code does
- The OTP is stored in app-1's own map. The verify request lands on app-2, which has never seen it, so a correct OTP is rejected.
- On a single laptop this never fails, which is why per-server state survives code review. Practice 3 fixes it with a shared store.
It works on one server and on a developer's laptop, then fails quietly behind a load balancer.
The quick question: if the next request lands on a different server, does it still work? If not, move that data to a shared store or into a signed token.
Mistake 3: slow work inside the request
Ask of each step in a request: does the user need this result before they can continue? The example sorts steps into sync and queue.
Example 3 · Sync or queue: does the user need the result now?
import java.util.List;
record Action(String name, boolean userNeedsResultNow, boolean slowOrExternal) {}
public class SyncOrQueue { static String decide(Action a) { if (a.userNeedsResultNow()) { return "sync"; } return a.slowOrExternal() ? "queue" : "queue (or sync if trivial)"; }
public static void main(String[] args) { List<Action> actions = List.of( new Action("Charge payment at checkout", true, true), new Action("Send order confirmation email", false, true), new Action("Check stock before placing order", true, false), new Action("Resize uploaded product photos", false, true));
for (Action a : actions) { System.out.printf("%-34s %s%n", a.name(), decide(a)); } }}Charge payment at checkout sync Send order confirmation email queue Check stock before placing order sync Resize uploaded product photos queue
What this code does
decidekeeps an action synchronous only when the user needs its result to continue.- Payment and stock checks stay in the request; the email and photo resizing go to a queue.
Charging the payment and checking stock: yes, keep them synchronous. Emails, invoices, photo resizing and analytics: no, put a job on a queue.
When you queue, remember the two follow-ups: retries with a dead-letter queue, and an idempotent consumer for duplicates.
Mistake 4: layers that skip each other
Layering violations creep in as shortcuts. The example checks that every call goes only one layer down.
Example 4 · Checking every call goes one layer down
import java.util.List;import java.util.Map;
public class LayerCallCheck { // Which layer each layer may call directly static final Map<String, List<String>> ALLOWED = Map.of( "Controller", List.of("Service"), "Service", List.of("Repository", "Service"), "Repository", List.of());
static String layerOf(String className) { for (String layer : List.of("Controller", "Service", "Repository")) { if (className.endsWith(layer)) { return layer; } } return "Other"; }
public static void main(String[] args) { List<String[]> calls = List.of( new String[] {"OrderController", "OrderService"}, new String[] {"OrderController", "CouponRepository"}, new String[] {"OrderService", "ProductRepository"}, new String[] {"ProductRepository", "EmailService"}, new String[] {"OrderService", "PaymentService"});
for (String[] c : calls) { String from = layerOf(c[0]); String to = layerOf(c[1]); boolean ok = ALLOWED.get(from).contains(to); System.out.printf("%-17s -> %-17s %s%n", c[0], c[1], ok ? "ok" : "VIOLATION"); } }}OrderController -> OrderService ok OrderController -> CouponRepository VIOLATION OrderService -> ProductRepository ok ProductRepository -> EmailService VIOLATION OrderService -> PaymentService ok
What this code does
ALLOWEDlists which layer may call which. The class name suffix gives the layer.- A controller calling a repository and a repository calling an email service are both flagged. Service to service is allowed here, because one rule may need another.
Typical shortcuts: a controller that reads a repository "just for this endpoint", a repository that sends an email, a service that returns a status code. Each one bypasses a rule or ties business logic to the wrong technology.
The quick question: does every call go only one layer down? Controller to service, service to repository or another service, repository to nothing but the database.
Finish up
Mark complete & continue
Next: Project: ShopLite modular monolith with an order queue