Databases at scale 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.
A traffic spike hits ShopLite and everyone asks for more servers. Four habits decide the right fix before any money is spent: read the symptoms, add up connections, test a shard key, and match data to a store.
Picking the first fix for a slow database
Match each symptom to its step on the scaling path. This program tests four slow-database scenarios.
Example 1 · Four slow-database scenarios and their first fix
import java.util.List;
public class FirstFixDemo { record Symptoms(String name, boolean fullScans, boolean poolTimeoutsDbIdle, int readPercent, boolean primaryCpuHigh, boolean writesOrDataTooBigForOneServer) { }
static String firstFix(Symptoms s) { if (s.fullScans()) { return "add the missing index / fix the query"; } if (s.poolTimeoutsDbIdle()) { return "shorten transactions, fix leaks, size the pool"; } if (s.writesOrDataTooBigForOneServer()) { return "shard (after archiving and partitioning old data)"; } if (s.primaryCpuHigh() && s.readPercent() >= 80) { return "cache hot reads, then add read replicas"; } return "measure more before changing anything"; }
public static void main(String[] args) { List<Symptoms> cases = List.of( new Symptoms("A: order search slow, EXPLAIN type=ALL", true, false, 70, true, false), new Symptoms("B: timeouts waiting for connections", false, true, 60, false, false), new Symptoms("C: 92% reads, all indexed, CPU 85%", false, false, 92, true, false), new Symptoms("D: 9,000 writes/s, 6 TB, indexed", false, false, 40, true, true)); for (Symptoms s : cases) { System.out.printf("%-42s -> %s%n", s.name(), firstFix(s)); } }}A: order search slow, EXPLAIN type=ALL -> add the missing index / fix the query B: timeouts waiting for connections -> shorten transactions, fix leaks, size the pool C: 92% reads, all indexed, CPU 85% -> cache hot reads, then add read replicas D: 9,000 writes/s, 6 TB, indexed -> shard (after archiving and partitioning old data)
What this code does
- The rules are checked in the order of the scaling path: query fixes first, then the pool, then sharding for write or size limits, then caching and replicas for read load.
- Scenario C has no full scans and 92% reads, so caching and replicas fit; scenario D is write- and size-bound, which replicas cannot fix.
Match the symptom to the step, in this order. Full scans in EXPLAIN mean an index or query fix. Requests waiting for connections while the database is idle mean long transactions, leaks or pool sizing. A primary busy with reads that are already indexed means caching, then read replicas. Writes or data too big for one server mean partitioning old data and, last, sharding.
The common mistake is jumping to the most impressive step. Replicas copy a missing index to every server; sharding a database with N+1 queries gives N slow shards.
Order of execution
The scaling path
Put the fixes in the order you should try them.
Connection maths for a fleet
Add up every client of the database and compare the total with max_connections. This program checks today's fleet and the sale-day fleet.
Example 2 · Today's fleet fits; the sale-day fleet does not
public class FleetMathDemo { public static void main(String[] args) { int maxConnections = 300; // raised from MySQL's default 151 int apiServers = 12, apiPool = 20; int workers = 4, workerPool = 5; int reserved = 10; // admin, monitoring, replication
int total = apiServers * apiPool + workers * workerPool + reserved; System.out.println("API: " + apiServers + " x " + apiPool + " = " + apiServers * apiPool); System.out.println("Workers: " + workers + " x " + workerPool + " = " + workers * workerPool); System.out.println("Reserved: " + reserved); System.out.println("Total: " + total + " of " + maxConnections + (total <= maxConnections ? " -> OK" : " -> TOO MANY"));
int sale = 2 * apiServers * apiPool + workers * workerPool + reserved; // auto-scale doubles the API servers System.out.println("Sale day (24 API servers): " + sale + (sale <= maxConnections ? " -> OK" : " -> TOO MANY")); int safePool = (maxConnections - workers * workerPool - reserved) / (2 * apiServers); System.out.println("Safe API pool size for 24 servers: " + safePool); }}API: 12 x 20 = 240 Workers: 4 x 5 = 20 Reserved: 10 Total: 270 of 300 -> OK Sale day (24 API servers): 510 -> TOO MANY Safe API pool size for 24 servers: 11
What this code does
- 12 API servers with pools of 20, 4 workers with pools of 5, and a reserve of 10 use 270 of 300 connections.
- Auto-scaling to 24 API servers would need 510. A pool of 11 per API server keeps the sale-day total within the limit.
Add up every client of the database: API servers × pool size, background workers × their pool, plus a reserve for admin tools, monitoring and replication. Compare the total with max_connections, and do it for the largest fleet auto-scaling can create, not today's.
If the sale-day number is too high, lower the pool per server (usually fine when transactions are short), raise the limit carefully (each connection costs database memory), or put a connection proxy in between.
Choosing and testing a shard key for orders
Test each candidate key on realistic data before choosing. This program spreads 40,000 orders with three shard keys.
Example 3 · Testing three shard keys on 40,000 orders
import java.util.Arrays;import java.util.Random;import java.util.function.IntUnaryOperator;
public class ShardKeyCompareDemo { static final int SHARDS = 4;
static int mix(int x) { // spreads numbers evenly (MurmurHash3 finaliser) x ^= x >>> 16; x *= 0x85EBCA6B; x ^= x >>> 13; x *= 0xC2B2AE35; x ^= x >>> 16; return x; }
record Order(int id, int customerId, int month, int status) { }
static void report(String key, Order[] orders, IntUnaryOperator shardOfIndex) { int[] perShard = new int[SHARDS]; for (int i = 0; i < orders.length; i++) { perShard[shardOfIndex.applyAsInt(i)]++; } System.out.printf("%-26s rows per shard %s%n", key, Arrays.toString(perShard)); }
public static void main(String[] args) { Random random = new Random(21); Order[] orders = new Order[40_000]; for (int i = 0; i < orders.length; i++) { int month = i < 30_000 ? 1 + random.nextInt(9) : 10; // October is the big sale month int status = random.nextInt(100) < 85 ? 2 : random.nextInt(4); // most orders are DELIVERED orders[i] = new Order(i + 1, 1 + random.nextInt(20_000), month, status); } report("hash(customer_id)", orders, i -> Math.floorMod(mix(orders[i].customerId()), SHARDS)); report("status", orders, i -> orders[i].status()); report("month range (3 per shard)", orders, i -> Math.min((orders[i].month() - 1) / 3, SHARDS - 1)); int[] octoberWrites = new int[SHARDS]; for (Order o : orders) { if (o.month() == 10) { octoberWrites[Math.min((o.month() - 1) / 3, SHARDS - 1)]++; } } System.out.printf("%-26s new rows in October %s%n", "month range (3 per shard)", Arrays.toString(octoberWrites)); System.out.println("\"My orders\" by customer: hash(customer_id) asks 1 shard; the others ask all 4"); }}hash(customer_id) rows per shard [10143, 9807, 10113, 9937] status rows per shard [1541, 1532, 35430, 1497] month range (3 per shard) rows per shard [10012, 9985, 10003, 10000] month range (3 per shard) new rows in October [0, 0, 0, 10000] "My orders" by customer: hash(customer_id) asks 1 shard; the others ask all 4
What this code does
hash(customer_id)gives four nearly equal shards.statusputs 35,430 orders on the DELIVERED shard.- The month range looks even over the year, but all 10,000 October orders land on one shard: that shard takes every write during the sale.
A shard key must spread rows and load evenly and let the most common queries hit one shard. Test candidates on realistic data before choosing. For ShopLite orders, hash(customer_id) spreads evenly and keeps each customer's orders together. status has four values, one of which holds most orders. A date range looks even over a year, but every new order of the month goes to the same shard: a write hot spot exactly during the sale.
seller#0 to seller#3) spreads it without changing every other key.SQL or NoSQL for five data sets
Give each data set a store and a reason. This program prints the choice for five data sets.
Example 4 · A store for each data set, with the reason
import java.util.LinkedHashMap;import java.util.Map;
public class StoreChoiceDemo { public static void main(String[] args) { Map<String, String[]> choices = new LinkedHashMap<>(); choices.put("Payments ledger", new String[] {"MySQL", "money moves need transactions and audits"}); choices.put("Login sessions", new String[] {"Redis (key-value)", "read by session id, expire with TTL"}); choices.put("Product specs", new String[] {"MySQL JSON column or MongoDB", "fields differ by category"}); choices.put("Click stream, 20k events/s", new String[] {"Cassandra or an analytics store", "huge append-only writes by time"}); choices.put("Also-bought links", new String[] {"graph store, or precomputed tables", "questions follow relationships"}); choices.forEach((data, c) -> System.out.printf("%-27s -> %-33s (%s)%n", data, c[0], c[1])); }}Payments ledger -> MySQL (money moves need transactions and audits) Login sessions -> Redis (key-value) (read by session id, expire with TTL) Product specs -> MySQL JSON column or MongoDB (fields differ by category) Click stream, 20k events/s -> Cassandra or an analytics store (huge append-only writes by time) Also-bought links -> graph store, or precomputed tables (questions follow relationships)
What this code does
- Each choice is tied to one property of the data: transactions, key lookups with expiry, varying fields, write volume or relationships.
- Two answers name a simpler option too (a JSON column, precomputed tables): adding a new database is a cost, not a feature.
For each data set, say the reason in one line: transactions and relations point to SQL; lookups by key with expiry to a key-value store; records whose fields differ to documents or a JSON column; a firehose of time-ordered events to a wide-column or analytics store; questions that follow relationships to a graph. If no reason stands out, SQL is the default.
Predict the output
Pick the store
Choose the best store and think about why.
Round 1 of 2
Finish up
Mark complete & continue
Next: Project: ShopLite database scaling plan