SteelReed

Search

Search posts, questions…

5. Spring Boot

Cart and checkout with Spring: the model, the transaction and never overselling

Designing Cart, CartItem, Order and OrderLine; merging lines when the same product is added twice; money as BigDecimal; placing an order in one transaction with a requestId against double clicks, an atomic stock decrement and a rollback when stock runs out; order status and order history without N+1. With a Spring Boot 3 lab verified by tests.

18 Nov 20268 min readSenior

–

1. The problem

A flash sale has 1 laptop left and 2 people click "Place order": both succeed and stock goes to -1. The same day, a customer double-clicks on a slow network and gets two orders. Later an admin changes the price, and old invoices change too because order lines didn't store the price.

2. Key idea

A cart is a draft the customer edits. An order is a printed invoice: fixed prices, printed only if stock exists.

Table Key constraint Why
cart user_id unique one cart per user
cart_item unique (cart_id, product_id) one line per product
orders unique (user_id, request_id) no two orders from one click
order_line product_name, unit_price not null a snapshot for invoices and reconciliation

Name the table orders: order is an SQL keyword. Take the user id from the principal, never from the form, or anyone can add items to someone else's cart. To delete a line, load the current user's cart and remove from it; never delete by an id the client sent.

2.1 How do you decrement stock?

Approach Use when Don't use when
UPDATE ... WHERE stock >= :qty the rule fits in a WHERE you must read other data before deciding
Optimistic (@Version) complex rules, low contention hot items: endless retries
Pessimistic (SELECT ... FOR UPDATE) you want simple reasoning long-held locks; for many products lock by ascending product_id
Cart in the session anonymous visitors you need a durable cart across devices

A session cart holds only ids and quantities, never JPA entities. On login, merge each line into the DB cart.

3. In Java

One @Transactional; an unchecked exception rolls everything back.

JAVA
@Transactional
public ShopOrder placeOrder(Long userId, CheckoutForm form) {
    var existing = orders.findByUserIdAndRequestId(userId, form.requestId());
    if (existing.isPresent()) return existing.get();               // second click: old order
 
    Cart cart = carts.findByUserId(userId).orElseThrow();
    var order = new ShopOrder(userId, form.requestId(), form.receiver());
    for (CartItem item : cart.items()) {
        int changed = products.decreaseStock(item.productId(), item.quantity());
        if (changed == 0) throw new OutOfStockException(item.productId());   // rolls back the order
        order.addLine(item.productName(), item.unitPrice(), item.quantity()); // adds to the total
    }
    cart.clear();                                                  // dirty checking deletes cart_item
    return orders.save(order);
}
// 2 buyers, last item: one gets the order, the other OutOfStockException, stock = 0

decreaseStock is @Modifying(flushAutomatically = true) @Query("update Product p set p.stock = p.stock - :qty where p.id = :id and p.stock >= :qty"). The unique (user_id, request_id) catches two parallel requests that both see "no order yet"; catch DataIntegrityViolationException and reload the order. Redirect after checkout (Post/Redirect/Get) so F5 doesn't resubmit.

Money, order status and order history
  • With double, 0.1 + 0.2 is 0.30000000000000004. Use BigDecimal built from strings or valueOf, compare with compareTo (equals treats 2.0 and 2.00 as different), and DECIMAL columns.
  • Order status is a small state machine: PENDING → CONFIRMED → SHIPPING → DELIVERED, cancellable from PENDING or CONFIRMED. changeStatus throws on invalid moves; cancelling an order that took stock adds it back in the same transaction.
  • Order history: @EntityGraph(attributePaths = "lines") gives one left join instead of N+1.
  • Don't put a collection-fetching @EntityGraph on a query with Pageable: Hibernate 6 warns HHH90003004 and paginates in memory after loading every order. Paginate orders without lines, or fetch a page of ids first and load lines with where order_id in (...).

4. Working with AI

Hand to AI: entities and repositories, Thymeleaf pages, Testcontainers integration tests with two parallel buyers.

Check in AI-written code:

  • Stock is decremented with a conditional UPDATE or a lock, not findById then setStock.
  • There is a requestId and a unique (user_id, request_id).
  • Order lines store name and price; cart lines don't store price.
  • No double for money; the total is computed in one place.
  • No clearAutomatically = true in a method that still uses loaded entities.

5. Exercises

Exercise 1: Review a "safe" stock reservation

The AI wrote this, saying "it's @Transactional, so we can't oversell". Find the bug, name a test that proves it, fix it.

JAVA
@Transactional
public void reserve(Long productId, int qty) {
    Product p = products.findById(productId).orElseThrow();
    if (p.getStock() < qty) throw new OutOfStockException(productId);
    p.setStock(p.getStock() - qty);
}
Solution to Exercise 1

Check-then-act: two transactions both read stock = 1, both see enough, both write 0. Under READ COMMITTED (PostgreSQL's default) this is a lost update: stock reaches 0 but there are two orders.

Test: Testcontainers PostgreSQL, stock 1, two threads call reserve(id, 1) via a CountDownLatch, count successes: 2.

Fix: UPDATE product SET stock = stock - :qty WHERE id = :id AND stock >= :qty and check the row count; or @Version with retries; or @Lock(PESSIMISTIC_WRITE) on the read.

Exercise 2: Read a "cart not empty" incident

After changing decreaseStock to @Modifying(clearAutomatically = true, flushAutomatically = true), a test reports: checkout succeeds, the order is right, but the cart still holds 3 items. No exception. Diagnose and fix.

Solution to Exercise 2

clearAutomatically calls EntityManager.clear() after the UPDATE, so the Cart loaded at the start of the method is detached. cart.clear() then only changes an in-memory object; dirty checking no longer tracks it, so no DELETE is issued.

Fix: keep only flushAutomatically. If you need the product's new stock, call entityManager.refresh(product). Add a test asserting cartItems.count() == 0 after checkout.

Summary

  • Order lines snapshot name and price; cart lines don't.
  • Checkout: requestId, conditional UPDATE, create order, clear cart, all in one transaction.
  • A unique constraint is the last safety net for check-then-act.
  • Money uses BigDecimal, totals computed in one place.
  • clearAutomatically detaches loaded entities; use only flushAutomatically.

Read more: Part 3: Pagination and dynamic filters.

Practice interview questions on this topic

All Spring Boot questions →All JPA & Hibernate questions →

Loading comments…