Skip to lesson

Practice: running in production

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.

Production problems are rarely new: the same few situations come back in different clothes. Practise the calm response here, so you are ready when ShopLite breaks.

Liveness or readiness? Classifying checks

Six checks, six decisions. The program below sorts each check into liveness or readiness.

Example 1 · Classifying six checks

ProbeClassifierDemo.javaJava
import java.util.LinkedHashMap;import java.util.Map;
public class ProbeClassifierDemo {    public static void main(String[] args) {        // check -> would restarting this instance fix it?        Map<String, Boolean> checks = new LinkedHashMap<>();        checks.put("MySQL answers a validation query", false);        checks.put("request threads are not deadlocked", true);        checks.put("Flyway migrations have finished", false);        checks.put("payment gateway is reachable", false);        checks.put("JVM is not stuck after OutOfMemoryError", true);        checks.put("app is not shutting down", false);
        checks.forEach((check, restartHelps) ->                System.out.printf("%-42s -> %s%n", check, restartHelps ? "liveness" : "readiness"));    }}
Output
MySQL answers a validation query           -> readiness
request threads are not deadlocked         -> liveness
Flyway migrations have finished            -> readiness
payment gateway is reachable               -> readiness
JVM is not stuck after OutOfMemoryError    -> liveness
app is not shutting down                   -> readiness

What this code does

  • One question decides each row: does a restart of this instance fix it? Only a deadlock and a stuck JVM pass that test.
  • Outside services such as MySQL or a payment gateway are never liveness checks, because every instance would be restarted at once while the outside service stays down.

Ask one question for every check: would restarting this instance fix it? If yes, it belongs in liveness (a deadlocked thread pool, a JVM that ran out of memory and stopped answering). If no, because the problem is outside the app or temporary, it belongs in readiness (the database or another service is down, start-up is not finished, shutdown has begun, a cache is still loading).

When in doubt, choose readiness. A wrong readiness check only stops traffic for a while; a wrong liveness check restarts healthy instances in a loop.

Predict the output

Liveness or readiness?

Pick the probe for each check.

Round 1 of 3

The SMS provider cannot be reached.

check: SMS provider reachable
would a restart fix it? no

Roll back, fix forward or ignore?

Three situations, three decisions. The program below applies the rules to each one.

Example 2 · Three situations, three decisions

DecisionDemo.javaJava
import java.util.List;
record Situation(String name, double errorRatePercent, double normalPercent, boolean startedAfterDeploy,                 boolean oldCodeWorksWithSchema, boolean tinyTestedFixReady) {}
public class DecisionDemo {    static String decide(Situation s) {        boolean real = s.errorRatePercent() >= 2 * s.normalPercent() && s.errorRatePercent() >= 1;        if (!real) {            return "ignore and note it";        }        if (!s.startedAfterDeploy()) {            return "no rollback: find the outside cause";        }        if (s.tinyTestedFixReady()) {            return "fix forward";        }        return s.oldCodeWorksWithSchema() ? "roll back now" : "make schema compatible, then roll back";    }
    public static void main(String[] args) {        List<Situation> list = List.of(                new Situation("A: 500s on orders after deploy", 9.0, 0.3, true, true, false),                new Situation("B: errors since MySQL maintenance", 6.0, 0.3, false, true, false),                new Situation("C: a bot causing 404s", 0.4, 0.3, false, true, false),                new Situation("D: deploy with NOT NULL column", 12.0, 0.3, true, false, false));        for (Situation s : list) {            System.out.println(s.name() + " -> " + decide(s));        }    }}
Output
A: 500s on orders after deploy -> roll back now
B: errors since MySQL maintenance -> no rollback: find the outside cause
C: a bot causing 404s -> ignore and note it
D: deploy with NOT NULL column -> make schema compatible, then roll back

What this code does

  • The order of the checks is the decision process: is it real, did it start with a deploy, is a tiny fix ready, can the old code run on the schema?
  • Situation B shows why the timing question comes early: rolling back code would not fix a database that was under maintenance.

Decide from evidence, in this order. Is it real and user-facing? Error rate or latency clearly above normal, not one odd request. Did it start with a deploy? Then roll back first, unless the old code cannot run with the new schema. Is the fix tiny, certain and already tested? Then fixing forward can be faster. Did it start without a deploy (database, traffic, an outside service)? Then a rollback does not help; work on the cause.

Ignore (and note it) only when users are not affected: a handful of 404s from a bot, or one slow request during a backup.

Mistake: Actuator showing env and heapdump to everyone

One star in the exposure setting publishes everything. The program below finds the dangerous settings in a configuration.

Example 3 · Finding dangerous Actuator settings

ActuatorAuditDemo.javaJava
import java.util.Arrays;import java.util.List;import java.util.Set;
public class ActuatorAuditDemo {    static final Set<String> DANGEROUS = Set.of("env", "configprops", "heapdump", "threaddump", "beans",            "loggers", "shutdown", "mappings");
    static void audit(String include, String showDetails) {        System.out.println("include=" + include + ", show-details=" + showDetails);        List<String> exposed = Arrays.stream(include.split(",")).map(String::trim).toList();        if (exposed.contains("*")) {            System.out.println("  PROBLEM: * publishes every endpoint, including env and heapdump");        }        exposed.stream().filter(DANGEROUS::contains)                .forEach(e -> System.out.println("  PROBLEM: " + e + " should not be public"));        if (showDetails.equals("always")) {            System.out.println("  PROBLEM: health details are shown to everyone");        }    }
    public static void main(String[] args) {        audit("*", "always");        audit("health,info,env,heapdump", "when-authorized");        audit("health,info", "when-authorized");        System.out.println("  (no problems)");    }}
Output
include=*, show-details=always
  PROBLEM: * publishes every endpoint, including env and heapdump
  PROBLEM: health details are shown to everyone
include=health,info,env,heapdump, show-details=when-authorized
  PROBLEM: env should not be public
  PROBLEM: heapdump should not be public
include=health,info, show-details=when-authorized
  (no problems)

What this code does

  • The audit splits the exposure list exactly as Spring reads it and checks each name against endpoints that reveal settings or memory.
  • The safe configuration is the last one: only health and info, with details for authorised admins.

management.endpoints.web.exposure.include: "*" publishes every Actuator endpoint. env and configprops list settings (Boot masks values by default, but names, hosts and anything a custom setting reveals still leak), and heapdump downloads the JVM's memory, which can contain passwords, tokens and customer data in plain text. With show-details: always, health also shows the database type and disk paths to anyone.

The fix is short: expose health,info (plus prometheus only on a private network), show-details: when-authorized with roles: ADMIN, and if you need the other endpoints, put them on a management port that is not published.

Fix the error

Lock down Actuator

Pick the line that fixes each problem.

Round 1 of 2

The memory dump is public.

management:
endpoints:
web:
exposure:
include: "*"

Error

GET /actuator/heapdump -> 200 OK (download: heapdump.hprof)

Rolling back a release that added a NOT NULL column

The old code cannot insert orders without gift_note. The commands below roll back in the safe order.

Example 4 · Rolling back the NOT NULL release, in order

Runs in: a terminal on your laptop with SSH access to the VM and the repository

Terminal
# 1. The schema must accept the old code's INSERTs: add a forward migrationcat src/main/resources/db/migration/V7__gift_note_nullable.sql#    ALTER TABLE orders MODIFY gift_note VARCHAR(200) NULL;#    (merged as a hotfix on top of the previous good code, so CI builds image 5d0c3aa)# 2. Deploy that hotfix image (old features + V7) and check an orderssh deploy@203.0.113.25 "/opt/shoplite/deploy.sh 5d0c3aa9e1f2b4c6d8e0a2b4c6d8e0f1a3b5c7d9"curl -s -o /dev/null -w "%{http_code}\n" -X POST https://api.shoplite.example/api/v1/me/orders \  -H "Authorization: Bearer $ASHA" -H "Content-Type: application/json" \  -d '{"addressId":1,"items":[{"productId":6,"quantity":1}]}'
Sample output
ALTER TABLE orders MODIFY gift_note VARCHAR(200) NULL;
[+] Running 2/2
 ✔ Container shoplite-api-1    Healthy                           41.2s
 ✔ Container shoplite-caddy-1  Running                            0.0s
Deployed 5d0c3aa9e1f2b4c6d8e0a2b4c6d8e0f1a3b5c7d9
201

What this code does

  • The hotfix is the previous good code plus one migration, built and tested by the normal pipeline. Flyway applies V7 on start-up, so the column becomes optional before any old-style INSERT runs.
  • The final POST returning 201 proves the important path works again, which is the real end of the incident, not just a green health check.

Release 8b41d07 added V6, which made orders.gift_note NOT NULL without a default, and it also had a bug. Redeploying the previous image alone is not enough: the old code inserts orders without gift_note, and MySQL refuses them.

The safe order: first make the schema compatible with the old code by a small forward migration (make the column nullable or give it a default) shipped in a hotfix image, or, in an emergency, run the same statement by hand and add it as a migration right after. Then redeploy the previous SHA, check that an order can be placed, and only later bring the feature back with expand and contract.

Interview drill: "Your API is slow in production. What do you do?"

Say what you would measure before naming a fix. The program below walks through a triage for a slow API.

Example 5 · Triage for a slow API

SlowApiTriageDemo.javaJava
import java.util.LinkedHashMap;import java.util.Map;
public class SlowApiTriageDemo {    public static void main(String[] args) {        Map<String, Integer> p95ByUri = new LinkedHashMap<>();        p95ByUri.put("/api/v1/products", 48);        p95ByUri.put("/api/v1/me/orders", 2350);        p95ByUri.put("/api/v1/auth/login", 210);        int poolActive = 5;        int poolMax = 5;        int poolPending = 14;        double heapUsedPercent = 61;        boolean deployInLastHour = false;        boolean backupRunning = false;
        System.out.println("1. Confirm: p95 by route");        p95ByUri.forEach((uri, ms) -> System.out.printf("   %-20s %5d ms%s%n", uri, ms, ms > 1000 ? "  <- slow" : ""));        System.out.println("2. What changed? deploy=" + deployInLastHour + ", backup=" + backupRunning);        System.out.println("3. Where does the time go?");        if (poolActive == poolMax && poolPending > 0) {            System.out.println("   pool full (" + poolActive + "/" + poolMax + "), " + poolPending                    + " waiting -> slow queries; check the slow query log for /me/orders");        }        System.out.println("   heap " + heapUsedPercent + "% -> memory is not the problem");        System.out.println("4. Act: no deploy to roll back; fix the query (index or N+1), then watch p95");    }}
Output
1. Confirm: p95 by route
   /api/v1/products        48 ms
   /api/v1/me/orders     2350 ms  <- slow
   /api/v1/auth/login     210 ms
2. What changed? deploy=false, backup=false
3. Where does the time go?
   pool full (5/5), 14 waiting -> slow queries; check the slow query log for /me/orders
   heap 61.0% -> memory is not the problem
4. Act: no deploy to roll back; fix the query (index or N+1), then watch p95

What this code does

  • The program follows the spoken answer: confirm with per-route p95, check what changed, then look at the pool and the heap before choosing an action.
  • A full pool with requests waiting means requests queue for database connections, so the fix is in the queries of the slow route, not in more JVM memory.

A good answer is a calm sequence, not a guess. Confirm and size it: which endpoints, since when, p95 or everything, how many users. Check what changed: a deploy, a migration, traffic, a backup or batch job. Find where the time goes: per-uri latency, the connection pool (active at max, pending rising means slow queries or too small a pool), JVM heap and GC, then the slow query log for the database. Act: roll back if a release caused it, otherwise fix the cause (an index, an N+1 query, more memory) and watch the metric recover. Write it up.

Say what you would measure before naming a fix. Interviewers listen for the order more than for the tool names.

Order of execution

Triage a slow API

Tap the steps in the order you would take them.

Finish up

Mark complete & continue

Next: Project: ShopLite production runbook