Skip to lesson

ShopLite just got popular. One night a script copies every price, another guesses passwords and a buggy app retries forever, so real shoppers see slow pages. How do you protect the shared server?

Your turn: ShopLite is being flooded

Tonight one address sends ShopLite 3,000 requests a minute, while a normal shopper sends about 20. Take two minutes and think before you read on.

  • What breaks first, and who suffers?
  • What one rule would you add, and which number would you pick?
  • Where would you put it: in the browser, in front of the servers, or in your Spring Boot code?
There is no wrong answer yet. Compare your design with the one below, and keep the parts you got right.

Threats: scrapers, password guessers and buggy retry loops

Rate limit is a cap on how many requests one client may send in a time window, such as 60 a minute. Requests over the cap are refused, usually with 429 Too Many Requests.

A person clicks a few times a minute, but a script can send hundreds of requests a second. Three kinds of client cause most floods: scrapers, password guessers and buggy retry loops.

Example 1 · How far each threat is from a normal shopper

ThreatRatesDemo.javaJava
import java.util.LinkedHashMap;import java.util.Map;
public class ThreatRatesDemo {    public static void main(String[] args) {        int normalPerMinute = 20;   // a shopper clicking through product pages        int limitPerMinute = 60;    // one simple limit per client
        Map<String, Integer> perMinute = new LinkedHashMap<>();        perMinute.put("Normal shopper", normalPerMinute);        perMinute.put("Price scraper", 3_000);           // 50 pages a second        perMinute.put("Password guesser", 600);        perMinute.put("Buggy retry loop", 600);
        System.out.printf("%-17s %7s %8s  %s%n", "Client", "req/min", "x normal", "60/min limit");        for (Map.Entry<String, Integer> e : perMinute.entrySet()) {            int rate = e.getValue();            int times = rate / normalPerMinute;            String verdict = rate > limitPerMinute                    ? "blocks " + (rate - limitPerMinute) + " a minute"                    : "never noticed";            System.out.printf("%-17s %7d %7dx  %s%n", e.getKey(), rate, times, verdict);        }    }}
Output
Client            req/min x normal  60/min limit
Normal shopper         20       1x  never noticed
Price scraper        3000     150x  blocks 2940 a minute
Password guesser      600      30x  blocks 540 a minute
Buggy retry loop      600      30x  blocks 540 a minute

What this code does

  • A real shopper sends about 20 requests a minute. Each threat sends 30 to 150 times more from a single client.
  • One plain rule, "60 requests a minute per client", never touches the shopper but cuts every threat down to a normal rate.
  • The numbers are rough on purpose: the point is the gap between a person and a script, not the exact figures.

A client is anything that calls the API: a browser, a mobile app or a script. A scraper copies all product prices, a brute-force login guesses passwords one after another, and a buggy retry loop retries a failed call every 100 ms, forever.

The last one is not an attacker at all. One bad release of ShopLite's own Android app can flood the API more than any hacker.

Predict the output

Predict what the limit blocks

Read the code, then pick what it prints.

Round 1 of 2

Each client may make 2 requests. Which requests are blocked?

Map<String, Integer> counts = new HashMap<>();
int limit = 2;
int blocked = 0;
for (String c : new String[]{"bot", "asha", "bot", "bot", "bot"}) {
if (counts.merge(c, 1, Integer::sum) > limit) {
blocked++;
}
}
System.out.println(blocked);
Rate limiting does not decide who is good or bad. It only makes sure no single client can use far more than a normal share.

Protecting shared resources and keeping fairness

Fairness means one heavy client cannot take the share of everyone else. A per-client limit turns "first come, first served" into "everyone gets a fair turn".

A shared resource such as ShopLite's database pool has a fixed number of connections, and a scraper's request takes one away from a real shopper.

Example 2 · One scraper starves three real users

FairnessDemo.javaJava
import java.util.ArrayList;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;
public class FairnessDemo {    static final int CAPACITY = 100;       // requests the server can finish in one second
    static List<String> arrivals() {       // one second of traffic, in arrival order        List<String> list = new ArrayList<>();        for (int i = 1; i <= 300; i++) {            list.add("scraper");            if (i % 60 == 0) {             // a real user's click every so often                list.add("Asha");                list.add("Ravi");                list.add("Meena");            }        }        return list;    }
    static Map<String, Integer> serve(List<String> arrivals, int perClientLimit) {        Map<String, Integer> sent = new LinkedHashMap<>();        Map<String, Integer> served = new LinkedHashMap<>();        int busy = 0;        for (String client : arrivals) {            int n = sent.merge(client, 1, Integer::sum);            served.putIfAbsent(client, 0);            if (n > perClientLimit) continue;            if (busy == CAPACITY) continue;            busy++;            served.merge(client, 1, Integer::sum);        }        return served;    }
    public static void main(String[] args) {        List<String> traffic = arrivals();        System.out.println("No limit:        " + serve(traffic, Integer.MAX_VALUE));        System.out.println("20 per client/s: " + serve(traffic, 20));    }}
Output
No limit:        {scraper=97, Asha=1, Ravi=1, Meena=1}
20 per client/s: {scraper=20, Asha=5, Ravi=5, Meena=5}

What this code does

  • The scraper sends 300 requests and each user sends 5. With no limit the server fills up with scraper work, and each user gets only 1 of 5 clicks answered.
  • With 20 requests per client per second, the scraper is stopped at 20, the server has room, and every user click is served.
  • A rejected request still arrives, but saying "no" costs far less than loading a product page from the database.

A shared resource is something every request competes for: CPU time, database connections, memory or a paid SMS gateway.

A rejected request still reaches the server, but it is answered from a small counter in memory. That costs microseconds, while a real product page may need a database query and several milliseconds.

Rate limiting vs throttling vs load shedding

Load shedding means dropping the least important work when the whole server is overloaded, whichever client sent it. Checkout keeps running while recommendations are refused, usually with 503 Service Unavailable.

Three tools protect a service. Rate limiting refuses a client's extra requests with 429, throttling delays them, and load shedding drops low-priority work when the server is overloaded.

Example 3 · Same burst: rate limit, throttle and load shedding

ProtectionStylesDemo.javaJava
import java.util.List;
public class ProtectionStylesDemo {    record Request(int no, String path, int priority) { }   // priority 1 = most important
    public static void main(String[] args) {        List<Request> burst = List.of(                new Request(1, "/checkout", 1), new Request(2, "/products", 2),                new Request(3, "/recommendations", 3), new Request(4, "/products", 2),                new Request(5, "/checkout", 1), new Request(6, "/recommendations", 3));
        int limit = 4;                         // 4 requests a second for this client        System.out.println("Rate limit (4 per second):");        for (Request r : burst) {            System.out.println("  #" + r.no() + " " + (r.no() <= limit ? "200 OK" : "429 Too Many Requests"));        }
        System.out.println("Throttle (one every 250 ms):");        for (Request r : burst) {            System.out.println("  #" + r.no() + " starts at " + (r.no() - 1) * 250 + " ms");        }
        System.out.println("Load shedding (server overloaded, drop priority 3):");        for (Request r : burst) {            String result = r.priority() >= 3 ? "503 shed" : "200 OK";            System.out.println("  #" + r.no() + " " + r.path() + " " + result);        }    }}
Output
Rate limit (4 per second):
  #1 200 OK
  #2 200 OK
  #3 200 OK
  #4 200 OK
  #5 429 Too Many Requests
  #6 429 Too Many Requests
Throttle (one every 250 ms):
  #1 starts at 0 ms
  #2 starts at 250 ms
  #3 starts at 500 ms
  #4 starts at 750 ms
  #5 starts at 1000 ms
  #6 starts at 1250 ms
Load shedding (server overloaded, drop priority 3):
  #1 /checkout 200 OK
  #2 /products 200 OK
  #3 /recommendations 503 shed
  #4 /products 200 OK
  #5 /checkout 200 OK
  #6 /recommendations 503 shed

What this code does

  • Rate limiting answers the extra requests with 429 at once. The client must slow down itself.
  • Throttling accepts every request but spaces them out, so request 6 waits 1,250 ms.
  • Load shedding looks at the whole server, not one client: when it is overloaded, it drops the least important work first and keeps checkout alive.

Interviewers often ask how the three differ:

  • Rate limiting: per client, "too many from you", answer 429.
  • Throttling: per client, "slow down", requests are delayed, not refused.
  • Load shedding: per server, "too many from everyone", drop low-priority work, answer 503.

Throttling puts extra requests in a queue and runs them later. Load shedding keeps important paths such as checkout and payment alive.

Where limits sit: API gateway, load balancer, application

API gateway is a server in front of all your services that every request passes through first, such as Nginx, Kong or a cloud gateway. It is the cheapest place to stop floods.

A request passes the API gateway, the load balancer and then the application. Each layer can hold a limit, and each knows different things about the client.

A request travels from the client through the API gateway, the load balancer and the ShopLite app to MySQL. The gateway holds a broad limit per IP or API key, 100 a minute. The load balancer caps connections per IP. The app holds precise limits per user and endpoint, such as 2 orders a minute.

Example 4 · Two layers: a gateway limit per IP and an app limit per user

LayeredLimitsDemo.javaJava
import java.util.HashMap;import java.util.List;import java.util.Map;
class CountingLimit {    private final String name;    private final int limit;    private final Map<String, Integer> counts = new HashMap<>();
    CountingLimit(String name, int limit) {        this.name = name;        this.limit = limit;    }
    boolean allow(String key) {        return counts.merge(key, 1, Integer::sum) <= limit;    }
    String name() { return name; }}
public class LayeredLimitsDemo {    record Request(String ip, String user, String method, String path) { }
    public static void main(String[] args) {        CountingLimit gateway = new CountingLimit("gateway", 6);       // 6 requests per IP per minute        CountingLimit orders = new CountingLimit("app", 2);            // 2 orders per user per minute
        List<Request> minute = List.of(                new Request("49.36.10.5", "asha", "GET", "/api/v1/products"),                new Request("49.36.10.5", "asha", "POST", "/api/v1/orders"),                new Request("49.36.10.5", "asha", "POST", "/api/v1/orders"),                new Request("49.36.10.5", "asha", "POST", "/api/v1/orders"),                new Request("103.21.8.9", "-", "GET", "/api/v1/products"),                new Request("103.21.8.9", "-", "GET", "/api/v1/products"),                new Request("103.21.8.9", "-", "GET", "/api/v1/products"),                new Request("103.21.8.9", "-", "GET", "/api/v1/products"),                new Request("103.21.8.9", "-", "GET", "/api/v1/products"),                new Request("103.21.8.9", "-", "GET", "/api/v1/products"),                new Request("103.21.8.9", "-", "GET", "/api/v1/products"));
        int reachedApp = 0;        for (Request r : minute) {            String result;            if (!gateway.allow(r.ip())) {                result = "429 from " + gateway.name();            } else {                reachedApp++;                boolean isOrder = r.method().equals("POST") && r.path().equals("/api/v1/orders");                result = isOrder && !orders.allow(r.user()) ? "429 from " + orders.name() : "200";            }            System.out.printf("%-11s %-4s %-17s %s%n", r.ip(), r.method(), r.path(), result);        }        System.out.println("Requests that reached the app: " + reachedApp + " of " + minute.size());    }}
Output
49.36.10.5  GET  /api/v1/products  200
49.36.10.5  POST /api/v1/orders    200
49.36.10.5  POST /api/v1/orders    200
49.36.10.5  POST /api/v1/orders    429 from app
103.21.8.9  GET  /api/v1/products  200
103.21.8.9  GET  /api/v1/products  200
103.21.8.9  GET  /api/v1/products  200
103.21.8.9  GET  /api/v1/products  200
103.21.8.9  GET  /api/v1/products  200
103.21.8.9  GET  /api/v1/products  200
103.21.8.9  GET  /api/v1/products  429 from gateway
Requests that reached the app: 10 of 11

What this code does

  • The gateway knows only the IP address, so it applies one broad cap to everything. The scraper's 7th request never reaches ShopLite.
  • The app knows the signed-in user and the endpoint, so it can apply the precise rule "2 orders a minute per user". Asha's third order gets 429 from the app.
  • Each layer does the job it has the information for: cheap broad limits outside, detailed business limits inside.

Rejected requests never reach the app when the gateway stops them, which is why a broad limit belongs there. The load balancer can cap connections per IP address. The application knows the most: the signed-in user, the endpoint and the business rule, so a limit such as "2 orders a minute per user" lives there.

Real systems use more than one layer: a broad limit outside and precise limits inside. Compare this with the design you sketched in Your turn.

Order of execution

Follow one order request through the layers

Put the steps in the order they happen.

Real limits: login attempts, OTP sends, public API tiers

API tier is a plan for outside developers with its own limit, such as free: 1,000 calls a day and paid: 100,000 calls a day. The limit is part of the product.

Login, OTP sends and order creation need much stricter limits than reading products. Here is one OTP rule in code.

Example 5 · OTP sends: 3 per phone number in 10 minutes

OtpLimitDemo.javaJava
import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;
public class OtpLimitDemo {    static final int MAX_SENDS = 3;    static final int WINDOW_MINUTES = 10;    static final Map<String, List<Integer>> sentAt = new HashMap<>();
    static boolean trySend(String phone, int minute) {        List<Integer> times = sentAt.computeIfAbsent(phone, p -> new ArrayList<>());        int recent = 0;        for (int t : times) {            if (minute - t < WINDOW_MINUTES) recent++;     // sent in the last 10 minutes        }        if (recent >= MAX_SENDS) return false;        times.add(minute);                                 // SMS is sent and paid for        return true;    }
    public static void main(String[] args) {        String phone = "98xxxxxx21";        int[] clicks = {0, 1, 2, 3, 9, 10, 12};        int smsCount = 0;        for (int minute : clicks) {            boolean ok = trySend(phone, minute);            if (ok) smsCount++;            System.out.println("minute " + minute + ": " + (ok ? "OTP sent" : "429, try again later"));        }        System.out.println("SMS paid for: " + smsCount + " of " + clicks.length + " clicks");    }}
Output
minute 0: OTP sent
minute 1: OTP sent
minute 2: OTP sent
minute 3: 429, try again later
minute 9: 429, try again later
minute 10: OTP sent
minute 12: OTP sent
SMS paid for: 5 of 7 clicks

What this code does

  • Every OTP is an SMS that ShopLite pays for, so "Resend OTP" gets a strict limit: 3 sends per phone in any 10 minutes.
  • At minute 3 and minute 9 there are already 3 sends in the last 10 minutes, so both are refused. At minute 10 the send from minute 0 is old enough, so one is allowed again.
  • Without the limit, a script could make ShopLite send thousands of paid SMS to one number: a cost attack and harassment at the same time.

Login gets a small limit per e-mail and per IP, so password guessing takes years instead of minutes. OTP sends get a limit per phone number, because each SMS costs money and a flood is harassment for the person who owns that number.

A tier protects the service and gives customers a reason to pay. The strict login and OTP limits stay the same for every tier.

Find the bug

Spot the limiter bug

Each snippet has one wrong line. Tap it, then read the fix.

Count only the OTP sends from the last 10 minutes.

Round 1 of 2

Next step

Check your understanding

11 quick questions