Microservices: what they are and why not to start with them
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)On sale day ShopLite's traffic is mostly product browsing, yet to handle it you must copy the whole app. A friend says "use microservices, like the big companies". What would you gain, what would it cost, and is it time?
Your turn: should ShopLite split up?
ShopLite has three teams, and on sale day 90% of the traffic is product browsing. Think before you read on:
- What do you gain if the catalogue runs as its own program? Which numbers would tell you the gain is real?
- "Place order" is one method call and one database transaction today. What can go wrong when it becomes three network calls?
- How many teams, how many copies of each part and how much slower one request would make you decide?
A microservice: deployed alone, owning its data
A microservice is a small application that does one business job, is deployed on its own and owns its own data. Other services reach that data only through its API.
Two rules define it: it is deployed alone, and it owns its data. Run the example: orders cannot read the catalogue's database, so it has to ask the catalogue.
Example 1 · Each service owns its data; others must ask
import java.util.HashMap;import java.util.Map;
// Each "service" is its own program with its own database in real life.// Here they are classes, and the only way in is the public method (the API).class CatalogueService { private final Map<Integer, Integer> productsDb = new HashMap<>();
CatalogueService() { productsDb.put(1, 17999); }
int priceApi(int productId) { System.out.println(" HTTP GET catalogue/products/" + productId + "/price"); return productsDb.get(productId); }}
class OrderService { private final Map<Integer, String> ordersDb = new HashMap<>(); private final CatalogueService catalogue;
OrderService(CatalogueService catalogue) { this.catalogue = catalogue; }
String place(int orderId, int productId, int qty) { int price = catalogue.priceApi(productId); // no JOIN with the products table: ask the owner ordersDb.put(orderId, "PLACED"); return "order " + orderId + " = Rs " + price * qty + " (saved in the orders database)"; }}
public class OwnDataDemo { public static void main(String[] args) { OrderService orders = new OrderService(new CatalogueService()); System.out.println(orders.place(501, 1, 2)); }}HTTP GET catalogue/products/1/price order 501 = Rs 35998 (saved in the orders database)
What this code does
productsDbis private toCatalogueService.OrderServicecannot read it, so it callspriceApi, which stands in for an HTTP request.- In a monolith this would be one SQL
JOIN. Here it is a network call that can be slow or fail, which is the price of owning data separately.
The first rule means you can release a new catalogue service without touching orders. The second rule is the hard one: in a monolith an order query can JOIN the products table, but with services there is no shared table to join.
So the order service must call the catalogue service, or keep its own copy of the few fields it needs. Both choices cost more than a JOIN.
Fix the error
Fix the data access
The order service reads another service's data. Pick the line that follows the rules.
OrderService needs a product price. CatalogueService owns its productsDb and offers priceApi(id).
Error
OrderService.java:3: error: productsDb has private access in CatalogueService
int price = catalogue.productsDb.get(1);
^
1 errorWhat you gain
Independent scaling means adding copies of only the busy part of the system, such as the catalogue, instead of copying the whole application.
On sale day, 90% of traffic is product browsing. The example compares copying the whole app with scaling only the catalogue.
Example 2 · Scaling only the busy part on sale day
public class IndependentScalingDemo { static int instances(double rps, double rpsPerInstance) { return (int) Math.ceil(rps / rpsPerInstance); }
public static void main(String[] args) { double saleRps = 3000; double browseShare = 0.9; // 90% of sale-day traffic is product browsing double orderShare = 0.1;
// Monolith: every copy carries all features, so copy everything int monolithCopies = instances(saleRps, 300); System.out.println("Monolith: " + monolithCopies + " copies x 2 GB = " + monolithCopies * 2 + " GB");
// Split: scale each service for its own traffic int catalogueCopies = instances(saleRps * browseShare, 400); int orderCopies = instances(saleRps * orderShare, 150); double memory = catalogueCopies * 1.0 + orderCopies * 1.0; System.out.println("Services: catalogue " + catalogueCopies + " x 1 GB, orders " + orderCopies + " x 1 GB = " + (int) memory + " GB"); System.out.println("Gain: scale the busy part only. Cost: 2 services to build, deploy and watch."); }}Monolith: 10 copies x 2 GB = 20 GB Services: catalogue 7 x 1 GB, orders 2 x 1 GB = 9 GB Gain: scale the busy part only. Cost: 2 services to build, deploy and watch.
What this code does
- The monolith needs 10 full copies (20 GB) because every copy carries every feature. Split services need 7 catalogue and 2 order copies (9 GB).
- The capacity numbers are a simplified model. The saving is real at large scale, but it comes with two services to build, deploy and monitor.
Independent deploys: a team can release its service many times a day without a company-wide release. Team autonomy: each team owns a service end to end, from code to database to on-call, and can even pick another language or database for a strong reason.
These benefits matter most when there are many teams. For one small team the gains are small.
Predict the output
How many catalogue copies?
Work out the number of copies you need.
Sale day: 3000 requests per second, 90% of them for the catalogue. One copy handles 400. How many catalogue copies?
What you pay
Partial failure means one part of the system is down or too slow while the rest still works, so one request can succeed in some steps and fail in others.
Every gain has a cost. The clearest one is partial failure: orders is up, but payments does not answer. Run the example and see what the orders database is left with.
Example 3 · Partial failure: the order is saved, the payment answer is lost
import java.util.LinkedHashMap;import java.util.Map;
class PaymentServiceDown extends RuntimeException { PaymentServiceDown() { super("payment service did not answer in 2 s"); }}
class PaymentClient { private int calls = 0;
// Every 3rd call times out: a fixed pattern so the output is repeatable String charge(int orderId, int rupees) { calls++; if (calls % 3 == 0) { throw new PaymentServiceDown(); } return "PAY-" + (9000 + calls); }}
public class PartialFailureDemo { static Map<Integer, String> ordersDb = new LinkedHashMap<>();
public static void main(String[] args) { PaymentClient payments = new PaymentClient(); int[] orderIds = {501, 502, 503, 504};
for (int id : orderIds) { ordersDb.put(id, "PLACED"); try { String ref = payments.charge(id, 1299); // step 2: a network call to another service ordersDb.put(id, "PAID " + ref); } catch (PaymentServiceDown e) { ordersDb.put(id, "PAYMENT_UNKNOWN"); // was the customer charged? we cannot tell System.out.println("order " + id + ": " + e.getMessage()); } } System.out.println("Orders database: " + ordersDb); }}order 503: payment service did not answer in 2 s
Orders database: {501=PAID PAY-9001, 502=PAID PAY-9002, 503=PAYMENT_UNKNOWN, 504=PAID PAY-9004}What this code does
- The orders database saves each order, then a separate service is called to charge. The 3rd call times out (a fixed pattern so the output repeats).
- Order 503 is
PAYMENT_UNKNOWN: the charge may or may not have happened. In a monolith with one transaction this state could not exist; with services you must design for it (the API Design at Scale module covers safe retries).
Four costs that a monolith does not have:
- Network calls: a method call that took microseconds becomes an HTTP call that takes milliseconds and can time out.
- Partial failure: every call needs a plan for "no answer", and "no answer" may still mean the customer was charged.
- Distributed data: no single database transaction across services, so keeping stock, payment and order in agreement needs extra steps such as compensating actions.
- Observability and ops: one request crosses many services, so you need central logs, tracing and monitoring, plus a deploy pipeline per service.
Why start with a monolith, and when to split
Most projects should start as a (modular) monolith. The example counts the signals that justify a split. Read the rules, then try your own company in your head.
Example 4 · A rough guide to when splitting is justified
import java.util.List;
record Company(String name, int teams, int deployClashesPerMonth, boolean veryDifferentLoad, boolean hasOpsSkills) {}
public class SplitSignals { // A rough guide, not a law: count the signals that justify the cost of splitting. static String advise(Company c) { int signals = 0; if (c.teams() >= 4) signals++; if (c.deployClashesPerMonth() >= 3) signals++; if (c.veryDifferentLoad()) signals++; if (!c.hasOpsSkills()) { return "stay a (modular) monolith: no one to run many services yet"; } return switch (signals) { case 0, 1 -> "stay a (modular) monolith (" + signals + " signal)"; case 2 -> "split out the one module that hurts most (2 signals)"; default -> "split along module boundaries, one service at a time (" + signals + " signals)"; }; }
public static void main(String[] args) { List<Company> companies = List.of( new Company("Fresher startup, 3 devs", 1, 0, false, false), new Company("ShopLite year 2, 12 devs", 2, 1, true, true), new Company("Marketplace, 60 devs", 8, 6, true, true), new Company("Ticketing, sale spikes", 4, 4, false, true));
for (Company c : companies) { System.out.printf("%-26s %s%n", c.name(), advise(c)); } }}Fresher startup, 3 devs stay a (modular) monolith: no one to run many services yet ShopLite year 2, 12 devs stay a (modular) monolith (1 signal) Marketplace, 60 devs split along module boundaries, one service at a time (3 signals) Ticketing, sale spikes split out the one module that hurts most (2 signals)
What this code does
advisecounts signals: many teams, frequent deploy clashes, very different load. With no one able to run services, the answer is always "stay a monolith".- Only the 60-developer marketplace gets a full split. The ticketing company splits one painful module. The rule is a thinking aid, not a formula.
With one team, the gains are small and the costs are immediate. Many well-known companies began as monoliths and split only parts of them years later.
Signals that can justify splitting a module out: several teams blocking each other, frequent deploy clashes, one part with very different load or reliability needs, and a team that can run many services (pipelines, monitoring, on-call). Split one module at a time, along a boundary that already exists in the modular monolith.
Predict the output
Count the split signals
ShopLite in year 2: apply the rule.
How many signals does ShopLite in year 2 show?
ShopLite split into three services
An API gateway is the single entry point that receives every client request and forwards it to the right service.
Imagine ShopLite's orders, catalogue and payments modules each become a service with its own database. A "place order" request now crosses several network hops.
[Phone] --> [API gateway] --> [Order service] --> [Orders DB] |--HTTP--> [Catalogue service] --> [Catalogue DB] |--HTTP--> [Payment service] --> [Payments DB]New failure points: gateway, each HTTP arrow (timeouts),each service, each database, and "charged but no reply" in payments.Example 5 · One order request: monolith vs three services
import java.util.List;
record Hop(String what, boolean network, double ms, double availability) {}
public class SplitPathDemo { static void report(String name, List<Hop> hops) { double ms = 0; double availability = 1; int networkHops = 0; for (Hop h : hops) { ms += h.ms(); availability *= h.availability(); if (h.network()) { networkHops++; } } System.out.printf("%-12s %d network hops, %5.1f ms, %.2f%% available, parts that can fail: %d%n", name, networkHops, ms, availability * 100, hops.size()); }
public static void main(String[] args) { List<Hop> monolith = List.of( new Hop("ShopLite app", false, 6, 0.999), new Hop("MySQL", true, 4, 0.999));
List<Hop> services = List.of( new Hop("API gateway", true, 2, 0.9995), new Hop("order service", false, 3, 0.999), new Hop("order DB", true, 3, 0.999), new Hop("catalogue service", true, 5, 0.999), new Hop("catalogue DB", true, 3, 0.999), new Hop("payment service", true, 5, 0.999), new Hop("payment DB", true, 3, 0.999));
System.out.println("POST /orders, one request:"); report("Monolith", monolith); report("3 services", services); }}POST /orders, one request: Monolith 1 network hops, 10.0 ms, 99.80% available, parts that can fail: 2 3 services 6 network hops, 24.0 ms, 99.35% available, parts that can fail: 7
What this code does
- The split version has 6 network hops instead of 1, so the request takes more than twice as long in this model.
- Availability drops from 99.80% to 99.35% because 7 parts are in series instead of 2. More services means more things that must all be up.
Each new box and arrow is a new way to fail: the gateway, every HTTP arrow (timeouts), every service, every database, and "charged but no reply" in payments. Compare this with the two boxes of the monolith.
Order of execution
Follow POST /orders
Tap the steps in the order they happen.
Next step
Check your understanding
10 quick questions