All labs ยท intermediate ยท about 25 min
๐ The open orders report got slow
The waiter brings the list of open tables in one trip, then walks back to the kitchen for every table's guest card and dishes. The more tables are open, the slower the room gets. Make it one trip.
Java 21Hibernate 6H2JUnit 5๐จ The incident
Every morning the manager asks the waiter for a list of the open tables: who sits there, how many dishes they ordered and what the bill is. When the restaurant was small, the waiter came back almost at once. Now there are thousands of open tables and the list takes minutes, while the kitchen is flooded with tiny requests. The waiter brings the list in one go, and the guest cards were even marked "always bring them", yet the waiter still keeps walking back. Your job: get the list in a few trips, and keep it right, including tables that have not ordered anything yet.
๐ What people saw
- The list takes longer every month, in step with the number of open tables.
- The kitchen log is full of identical little requests that differ only by a table number.
- Each single request is quick; there are just far too many of them.
- Marking the guest cards "always bring them" did not help.
[report] DEBUG select o.id, o.customer_id, o.status from orders o where o.status=? order by o.id [report] DEBUG select c.id, c.name from customer c where c.id=? [report] DEBUG select c.id, c.name from customer c where c.id=? [report] DEBUG select l.order_id, l.id, l.quantity, l.sku, l.unit_price_cents from order_line l where l.order_id=? [report] DEBUG select l.order_id, l.id, l.quantity, l.sku, l.unit_price_cents from order_line l where l.order_id=? [report] DEBUG select l.order_id, l.id, l.quantity, l.sku, l.unit_price_cents from order_line l where l.order_id=? ... [report] INFO open-orders report: 2000 open orders, 2121 statements, 38.2 s
โถ๏ธ Start the lab
- Unzip it and open the
jpa-slow-ordersfolder in your editor. - Run
mvn test. The failing tests are the bug report: read what they expect. - Fix the code in
src/mainuntilmvn testpasses. Leave the tests alone: they describe what the system must guarantee.
๐ Start reading here
src/main/java/lab/orders/OpenOrdersReport.java
1package lab.orders;23import java.util.ArrayList;4import java.util.List;56public class OpenOrdersReport {7public record Row(Long orderId, String customer, int lineCount, long totalCents) {}89private final OrderRepository orders;1011public OpenOrdersReport(OrderRepository orders) {12this.orders = orders;13}1415public List<Row> build() {16List<Row> rows = new ArrayList<>();17for (Order order : orders.findByStatus(Order.Status.OPEN)) {18long total = 0;19for (OrderLine line : order.getLines()) {20total += line.totalCents();21}22rows.add(new Row(order.getId(), order.getCustomer().getName(),23order.getLines().size(), total));24}25return rows;26}27}
src/main/java/lab/orders/OrderRepository.java
1package lab.orders;23import jakarta.persistence.EntityManager;4import java.util.List;56public class OrderRepository {7private final EntityManager em;89public OrderRepository(EntityManager em) {10this.em = em;11}1213public List<Order> findByStatus(Order.Status status) {14return em.createQuery(15"select o from Order o where o.status = :status order by o.id", Order.class)16.setParameter("status", status)17.getResultList();18}19}
src/main/java/lab/orders/Order.java
1package lab.orders;23import jakarta.persistence.Entity;4import jakarta.persistence.FetchType;5import jakarta.persistence.Id;6import jakarta.persistence.ManyToOne;7import jakarta.persistence.OneToMany;8import jakarta.persistence.Table;9import java.util.LinkedHashSet;10import java.util.Set;1112@Entity13@Table(name = "orders")14public class Order {15public enum Status { OPEN, SHIPPED }1617@Id18private Long id;19private Status status;20@ManyToOne(fetch = FetchType.EAGER)21private Customer customer;22@OneToMany(mappedBy = "order")23private Set<OrderLine> lines = new LinkedHashSet<>();2425protected Order() {}2627public Order(Long id, Customer customer, Status status) {28this.id = id;29this.customer = customer;30this.status = status;31}3233public Long getId() { return id; }34public Status getStatus() { return status; }35public Customer getCustomer() { return customer; }36public Set<OrderLine> getLines() { return lines; }37}
src/test/java/lab/orders/OpenOrdersReportTest.java
1package lab.orders;23import static org.junit.jupiter.api.Assertions.assertEquals;4import static org.junit.jupiter.api.Assertions.assertTrue;56import jakarta.persistence.EntityManager;7import jakarta.persistence.EntityManagerFactory;8import jakarta.persistence.Persistence;9import java.util.List;10import org.hibernate.SessionFactory;11import org.hibernate.stat.Statistics;12import org.junit.jupiter.api.AfterEach;13import org.junit.jupiter.api.BeforeEach;14import org.junit.jupiter.api.Test;1516class OpenOrdersReportTest {17private static final int OPEN_ORDERS = 50;1819private EntityManagerFactory emf;20private Statistics stats;2122@BeforeEach23void seed() {24emf = Persistence.createEntityManagerFactory("orders");25EntityManager em = emf.createEntityManager();26em.getTransaction().begin();27Customer[] customers = new Customer[10];28for (int c = 0; c < customers.length; c++) {29customers[c] = new Customer((long) c, "customer-" + c);30em.persist(customers[c]);31}32long lineId = 1;33for (long id = 1; id <= OPEN_ORDERS + 10; id++) {34Order.Status status = id <= OPEN_ORDERS ? Order.Status.OPEN : Order.Status.SHIPPED;35Order order = new Order(id, customers[(int) (id % 10)], status);36em.persist(order);37if (id % 5 != 0) {38for (int i = 1; i <= 3; i++) {39em.persist(new OrderLine(lineId++, order, "sku-" + i, i, 100 * id));40}41}42}43em.getTransaction().commit();44em.close();45stats = emf.unwrap(SessionFactory.class).getStatistics();46}4748@AfterEach49void close() {50emf.close();51}5253private List<OpenOrdersReport.Row> run() {54try (EntityManager em = emf.createEntityManager()) {55return new OpenOrdersReport(new OrderRepository(em)).build();56}57}5859@Test60void theReportShowsEachOpenOrderWithItsCustomerAndTotal() {61List<OpenOrdersReport.Row> rows = run();6263assertEquals(OPEN_ORDERS, rows.size());64OpenOrdersReport.Row row = rows.get(6);65assertEquals(7L, row.orderId());66assertEquals("customer-7", row.customer());67assertEquals(3, row.lineCount());68assertEquals(4200L, row.totalCents());69}7071@Test72void anOpenOrderWithNoLinesIsStillReportedWithATotalOfZero() {73List<OpenOrdersReport.Row> rows = run();7475OpenOrdersReport.Row empty = rows.get(4);76assertEquals(5L, empty.orderId());77assertEquals(0, empty.lineCount());78assertEquals(0L, empty.totalCents());79}8081@Test82void theReportForFiftyOpenOrdersRunsInAtMostThreeQueries() {83stats.clear();8485run();8687long queries = stats.getPrepareStatementCount();88assertTrue(queries <= 3,89"report for " + OPEN_ORDERS + " open orders ran " + queries + " SQL statements");90}91}
๐ก Hints
โ What really happened
Fixed it? Or completely stuck? Either way, here's what really happened.