TwiceToldby Develoker
ConceptsSystem designLabsCheat sheetsAbout

Develoker makes free tools for learning to build software. TwiceTold explains each idea twice, as an everyday analogy and the real thing; CloudArch lets you design cloud systems and put load on them.

About ยท Labs ยท Cheat sheets ยท Learning paths

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

Practises๐Ÿฝ๏ธ The N+1 query problem (JPA and Hibernate)

๐Ÿšจ 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

โฌ‡ Download the projectNeeds Java 21 and Maven.
  1. Unzip it and open the jpa-slow-orders folder in your editor.
  2. Run mvn test. The failing tests are the bug report: read what they expect.
  3. Fix the code in src/main until mvn test passes. Leave the tests alone: they describe what the system must guarantee.

๐Ÿ“‚ Start reading here

src/main/java/lab/orders/OpenOrdersReport.java
1package lab.orders;2 3import java.util.ArrayList;4import java.util.List;5 6public class OpenOrdersReport {7  public record Row(Long orderId, String customer, int lineCount, long totalCents) {}8 9  private final OrderRepository orders;10 11  public OpenOrdersReport(OrderRepository orders) {12    this.orders = orders;13  }14 15  public List<Row> build() {16    List<Row> rows = new ArrayList<>();17    for (Order order : orders.findByStatus(Order.Status.OPEN)) {18      long total = 0;19      for (OrderLine line : order.getLines()) {20        total += line.totalCents();21      }22      rows.add(new Row(order.getId(), order.getCustomer().getName(),23          order.getLines().size(), total));24    }25    return rows;26  }27}
src/main/java/lab/orders/OrderRepository.java
1package lab.orders;2 3import jakarta.persistence.EntityManager;4import java.util.List;5 6public class OrderRepository {7  private final EntityManager em;8 9  public OrderRepository(EntityManager em) {10    this.em = em;11  }12 13  public List<Order> findByStatus(Order.Status status) {14    return 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;2 3import 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;11 12@Entity13@Table(name = "orders")14public class Order {15  public enum Status { OPEN, SHIPPED }16 17  @Id18  private Long id;19  private Status status;20  @ManyToOne(fetch = FetchType.EAGER)21  private Customer customer;22  @OneToMany(mappedBy = "order")23  private Set<OrderLine> lines = new LinkedHashSet<>();24 25  protected Order() {}26 27  public Order(Long id, Customer customer, Status status) {28    this.id = id;29    this.customer = customer;30    this.status = status;31  }32 33  public Long getId() { return id; }34  public Status getStatus() { return status; }35  public Customer getCustomer() { return customer; }36  public Set<OrderLine> getLines() { return lines; }37}
src/test/java/lab/orders/OpenOrdersReportTest.java
1package lab.orders;2 3import static org.junit.jupiter.api.Assertions.assertEquals;4import static org.junit.jupiter.api.Assertions.assertTrue;5 6import 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;15 16class OpenOrdersReportTest {17  private static final int OPEN_ORDERS = 50;18 19  private EntityManagerFactory emf;20  private Statistics stats;21 22  @BeforeEach23  void seed() {24    emf = Persistence.createEntityManagerFactory("orders");25    EntityManager em = emf.createEntityManager();26    em.getTransaction().begin();27    Customer[] customers = new Customer[10];28    for (int c = 0; c < customers.length; c++) {29      customers[c] = new Customer((long) c, "customer-" + c);30      em.persist(customers[c]);31    }32    long lineId = 1;33    for (long id = 1; id <= OPEN_ORDERS + 10; id++) {34      Order.Status status = id <= OPEN_ORDERS ? Order.Status.OPEN : Order.Status.SHIPPED;35      Order order = new Order(id, customers[(int) (id % 10)], status);36      em.persist(order);37      if (id % 5 != 0) {38        for (int i = 1; i <= 3; i++) {39          em.persist(new OrderLine(lineId++, order, "sku-" + i, i, 100 * id));40        }41      }42    }43    em.getTransaction().commit();44    em.close();45    stats = emf.unwrap(SessionFactory.class).getStatistics();46  }47 48  @AfterEach49  void close() {50    emf.close();51  }52 53  private List<OpenOrdersReport.Row> run() {54    try (EntityManager em = emf.createEntityManager()) {55      return new OpenOrdersReport(new OrderRepository(em)).build();56    }57  }58 59  @Test60  void theReportShowsEachOpenOrderWithItsCustomerAndTotal() {61    List<OpenOrdersReport.Row> rows = run();62 63    assertEquals(OPEN_ORDERS, rows.size());64    OpenOrdersReport.Row row = rows.get(6);65    assertEquals(7L, row.orderId());66    assertEquals("customer-7", row.customer());67    assertEquals(3, row.lineCount());68    assertEquals(4200L, row.totalCents());69  }70 71  @Test72  void anOpenOrderWithNoLinesIsStillReportedWithATotalOfZero() {73    List<OpenOrdersReport.Row> rows = run();74 75    OpenOrdersReport.Row empty = rows.get(4);76    assertEquals(5L, empty.orderId());77    assertEquals(0, empty.lineCount());78    assertEquals(0L, empty.totalCents());79  }80 81  @Test82  void theReportForFiftyOpenOrdersRunsInAtMostThreeQueries() {83    stats.clear();84 85    run();86 87    long queries = stats.getPrepareStatementCount();88    assertTrue(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.