Skip to lesson

Common mistakes in fresher answers

A friend says ShopLite needs Kafka, microservices and sharding to handle 100 times more users. Weak answers fail in the same few ways: parts added with no numbers, no failure plan and no rule that keeps them correct.

Your turn: test the "add Kafka" advice

ShopLite takes 50,000 orders a day, and a friend says "just add Kafka, split into microservices and shard the database". Before reading on, work out your own answers.

  • How many order writes per second is that, on average and at a sale peak 10 times higher?
  • What happens to ShopLite if its only MySQL server dies?
  • If you cache product prices, what must happen when a price changes?

Keep your answers. Each of the next sections is one common mistake, and each shows the numbers or rule you need.

Jumping to microservices and Kafka without numbers

Over-engineering is adding parts the problem does not need, such as microservices, Kafka, sharding and Kubernetes for a few writes per second.

Compute first. Here ShopLite's order writes are measured against what one MySQL server can handle.

Example 1 · Let the numbers decide: ShopLite order writes

NumbersFirstDemo.javaJava
public class NumbersFirstDemo {    public static void main(String[] args) {        long ordersPerDay = 50_000;        int peakFactor = 10;        int mysqlSafeWritesPerSecond = 1_000; // a cautious figure for simple inserts on one server
        double avgWrites = ordersPerDay / 86_400.0;        double peakWrites = avgWrites * peakFactor;        System.out.printf("Orders: %.1f writes/s on average, %.1f at peak%n", avgWrites, peakWrites);        System.out.printf("One MySQL server: about %d writes/s -> using %.1f%% at peak%n",                mysqlSafeWritesPerSecond, 100 * peakWrites / mysqlSafeWritesPerSecond);
        if (peakWrites < mysqlSafeWritesPerSecond / 10.0) {            System.out.println("Decision: one service, one MySQL primary with a replica; no Kafka, no sharding yet");        } else {            System.out.println("Decision: look at queues for slow work and plan for more write capacity");        }    }}
Output
Orders: 0.6 writes/s on average, 5.8 at peak
One MySQL server: about 1000 writes/s -> using 0.6% at peak
Decision: one service, one MySQL primary with a replica; no Kafka, no sharding yet

What this code does

  • 50,000 orders a day is 0.6 writes per second; even 10x at peak is under 6.
  • Against a cautious 1,000 simple writes per second for one MySQL server, that uses about 0.6%, so Kafka and sharding are not needed yet.
  • The if states the threshold, which is exactly what to say aloud: "I would revisit this if peak writes passed about 100 per second."

50,000 orders a day is about 0.6 writes per second, under 6 at a sale peak. Each extra part adds network calls, failure points and operations work, so say what number would make you change the design.

Interviewers do not mark you down for a simple design. They mark you down for a complex one you cannot justify.

Predict the output

Peak writes for a bigger shop

Read the code and pick what it prints.

A larger shop has 200,000 orders a day and a 10x peak. What is printed?

long ordersPerDay = 200_000;
double average = ordersPerDay / 86_400.0;
System.out.printf("%.1f%n", average * 10);

Skipping requirements and estimates

Requirements are what the system must do (functional) and how well it must do it (non-functional), written down before any design.

Starting with boxes in minute one is the most common mistake. Compare a weak opening with a strong one.

Example 2 · A weak opening and a strong opening

Text
Weak opening (minute 0):  "OK, so I will use microservices with Kafka, Redis, Cassandra and Kubernetes.   First the API gateway..."Strong opening (minutes 0-5):  "Before I draw anything, a few questions. Is this for India only? How many daily   users, and what is the busiest hour? Must an order never be lost? Then I will   write the requirements:   Functional: browse products, cart, place order, track order.   Non-functional: product page under 200 ms, checkout 99.9% available,   no lost or duplicate orders.   Numbers: 1 million daily users, 50,000 orders a day, sale-day peak 10x."
Difference
Weak: tools in the first sentence, no questions, no numbers
Strong: questions, requirements, 3 numbers in 5 minutes

What this code does

  • The weak opening names five tools before knowing the scale or the goal.
  • The strong opening ends with numbers the rest of the design can use: 1 million users, 50,000 orders a day, a 10x peak.

Without requirements you may design the wrong system; without estimates you cannot tell whether you need a cache, a replica or nothing at all.

A strong opening asks two or three clarifying questions, writes the requirements and puts three numbers on the board: daily users, requests per second and data size. It takes five minutes and shapes the next forty.

Spot it: if your first sentence names a tool, you skipped the questions.

Ignoring failure: no single-point-of-failure analysis

Single point of failure (SPOF) is one part whose failure stops the whole system, such as the only database server.

Parts in a row multiply their availability, and a spare copy beside one lifts it. The program below computes both.

Three ShopLite set-ups. One load balancer, one app and one database in a row: 99.79 percent up, about 91 minutes down a month. Two app servers: 99.89 percent, about 48 minutes. Two app servers plus a database standby: 99.99 percent, about 4 minutes. The lone database is marked red.

Example 3 · Availability in series and with redundancy

AvailabilityDemo.javaJava
public class AvailabilityDemo {    static final double MINUTES_PER_MONTH = 30 * 24 * 60;
    static double series(double... parts) {        double a = 1;        for (double p : parts) {            a *= p; // every part must be up        }        return a;    }
    static double parallel(double one, int copies) {        return 1 - Math.pow(1 - one, copies); // down only if every copy is down    }
    static void show(String name, double a) {        System.out.printf("%-34s %.4f%%  ~%.0f min down/month%n", name, a * 100, (1 - a) * MINUTES_PER_MONTH);    }
    public static void main(String[] args) {        double lb = 0.9999;        double app = 0.999;        double db = 0.999;
        show("LB + 1 app + 1 DB (series)", series(lb, app, db));        show("LB + 2 apps + 1 DB", series(lb, parallel(app, 2), db));        show("LB + 2 apps + DB with standby", series(lb, parallel(app, 2), parallel(db, 2)));    }}
Output
LB + 1 app + 1 DB (series)         99.7901%  ~91 min down/month
LB + 2 apps + 1 DB                 99.8899%  ~48 min down/month
LB + 2 apps + DB with standby      99.9898%  ~4 min down/month

What this code does

  • series multiplies: load balancer, one app and one database in a row give 99.79%, about 91 minutes down a month.
  • parallel computes 1 − (chance every copy is down); a second app server cuts downtime to about 48 minutes.
  • Adding a database standby removes the last big single point of failure: about 4 minutes a month in this simplified model.

Three parts that are each up 99.9% of the time give less than 99.9% together. Two copies side by side (redundancy) are down only when both are down, which lifts availability sharply.

The numbers use a simplified model: failures are independent and switching to the spare is instant. Real failover takes seconds to minutes, but the lesson holds.

Cache without invalidation

Invalidation is removing or updating cached data when the source changes, so the cache stops serving the old value.

The price changes in the database, but the cache keeps answering with the old one. See it happen, then step through it.

Example 4 · A stale price from a cache with no invalidation

StaleCacheDemo.javaJava
import java.util.HashMap;import java.util.Map;
class ProductService {    private final Map<Integer, Integer> database = new HashMap<>();    private final Map<Integer, Integer> cache = new HashMap<>();    private final boolean invalidateOnUpdate;
    ProductService(boolean invalidateOnUpdate) {        this.invalidateOnUpdate = invalidateOnUpdate;        database.put(42, 1_299);    }
    int price(int id) {        return cache.computeIfAbsent(id, database::get); // cache-aside read    }
    void updatePrice(int id, int newPrice) {        database.put(id, newPrice);        if (invalidateOnUpdate) {            cache.remove(id); // the next read loads the new price        }    }}
public class StaleCacheDemo {    public static void main(String[] args) {        for (boolean fix : new boolean[] {false, true}) {            ProductService s = new ProductService(fix);            int before = s.price(42);            s.updatePrice(42, 999); // Diwali sale price            int after = s.price(42);            System.out.println((fix ? "With invalidation:    " : "Without invalidation: ")                    + "before Rs. " + before + ", after update Rs. " + after);        }    }}
Output
Without invalidation: before Rs. 1299, after update Rs. 1299
With invalidation:    before Rs. 1299, after update Rs. 999

What this code does

  • Without invalidation the price drops to Rs. 999 in the database, but the cache still answers Rs. 1299.
  • cache.remove(id) after the database update makes the next read load the new price.
  • Deleting is safer than writing the new value into the cache, because two updates racing could leave the older value cached.

Whenever you add a cache, say the rule that keeps it correct in the same sentence. Without invalidation the old price lives until the entry expires, or forever.

Step through a stale price and the one-line fix.

Trace the code

A stale price, then the fix

import java.util.HashMap;
import java.util.Map;
public class StalePrice {
public static void main(String[] args) {
Map<Integer, Integer> database = new HashMap<>();
Map<Integer, Integer> cache = new HashMap<>();
database.put(42, 1299);
cache.put(42, database.get(42));
database.put(42, 999);
System.out.println("Cache says " + cache.get(42));
cache.remove(42);
cache.put(42, database.get(42));
System.out.println("Cache says " + cache.get(42));
}
}

Variables

database
{42=1299}
cache
{}

Output

(nothing printed yet)

Line 8The database holds the price of product 42: 1299.

Step 1 of 7

Sharding without a shard key

Shard key is the field that decides which server holds a row. Choose it from the most common query.

Sharding spreads rows over servers. This program counts how many shards "show my orders" must ask under two different keys.

Example 5 · Shard key decides how many shards a query touches

ShardKeyDemo.javaJava
import java.util.ArrayList;import java.util.List;import java.util.Set;import java.util.TreeSet;
record Order(int orderId, int userId) {}
public class ShardKeyDemo {    static final int SHARDS = 4;
    public static void main(String[] args) {        List<Order> orders = new ArrayList<>();        int orderId = 1000;        for (int user = 1; user <= 3; user++) {            for (int k = 0; k < 6; k++) {                orders.add(new Order(orderId++, user));            }        }
        int user = 2;        Set<Integer> byOrderId = new TreeSet<>();        Set<Integer> byUserId = new TreeSet<>();        for (Order o : orders) {            if (o.userId() == user) {                byOrderId.add(Math.floorMod(o.orderId(), SHARDS));                byUserId.add(Math.floorMod(o.userId(), SHARDS));            }        }        System.out.println("\"My orders\" for user " + user + ":");        System.out.println("  shard key orderId -> must ask shards " + byOrderId);        System.out.println("  shard key userId  -> asks only shard " + byUserId);    }}
Output
"My orders" for user 2:
  shard key orderId -> must ask shards [0, 1, 2, 3]
  shard key userId  -> asks only shard [2]

What this code does

  • With the order id as the key, one user's 6 orders are spread over all 4 shards, so "my orders" asks every shard.
  • With the user id as the key, all of a user's orders sit on one shard, so the same query asks only shard 2.
  • Math.floorMod keeps the shard number between 0 and 3 even for negative numbers.

If orders are spread by order id, "show my orders" has to ask every shard. For orders the user id is usually the better key, because the most common query is one user's orders.

Predict how many shards each key touches.

Predict the output

Which shards hold one user's orders?

Read the code and pick what it prints.

Round 1 of 2

One user has orders 1000 to 1003 and there are 4 shards, sharded by order id. What is printed?

int shards = 4;
for (int orderId = 1000; orderId < 1004; orderId++) {
System.out.print(Math.floorMod(orderId, shards));
}

Rewriting weak answers into strong ones

Strong design answer gives requirements and numbers, the simplest design that meets them, how each single point of failure is covered, and the rule for each extra part.

A weak answer is fixed by adding the missing reasoning, not more tools. Below is a weak answer and its rewrite.

Example 6 · A weak answer to rewrite

Text
Weak answer to "Design the order backend for a college bookstore":  "I will use microservices for users, catalogue, orders and payments, Kafka between   them, Redis for caching everything, and shard the database. It will be highly   available and scale infinitely."
Rewritten answer
Requirements: 2,000 students, order and pay by UPI, pickup notification; peak 300 orders in the first hour of term.
Numbers: 300 orders/hour is under 0.1 per second, so one service and one MySQL are plenty.
Design: [App] --> [Bookstore API x2] --> [(MySQL: catalogue, orders)]; UPI callback --> [Bookstore API].
Failure: two API copies; MySQL with daily backups and a standby; if payments are slow, the order waits as PENDING.
Cache: only the catalogue, 5-minute TTL, deleted when the bookstore edits it. No sharding needed.

What this code does

  • Every tool in the weak answer is either justified by a number or removed.
  • The cache comes with its invalidation rule, and failure has a line of its own.

The rewritten answer is often shorter, and it sounds like someone who has built real systems.

Put the four moves of a rewrite in order.

Order of execution

Rewrite a weak answer in four moves

Put the four moves in the order you would say them.

Next step

Check your understanding

12 quick questions