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.
On this page
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.
@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 = 0decreaseStock 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.2is0.30000000000000004. UseBigDecimalbuilt from strings orvalueOf, compare withcompareTo(equalstreats2.0and2.00as different), andDECIMALcolumns. - Order status is a small state machine:
PENDING → CONFIRMED → SHIPPING → DELIVERED, cancellable fromPENDINGorCONFIRMED.changeStatusthrows on invalid moves; cancelling an order that took stock adds it back in the same transaction. - Order history:
@EntityGraph(attributePaths = "lines")gives oneleft joininstead of N+1. - Don't put a collection-fetching
@EntityGraphon a query withPageable: Hibernate 6 warnsHHH90003004and paginates in memory after loading every order. Paginateorderswithout lines, or fetch a page of ids first and load lines withwhere 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
UPDATEor a lock, notfindByIdthensetStock. - There is a
requestIdand a unique(user_id, request_id). - Order lines store name and price; cart lines don't store price.
- No
doublefor money; the total is computed in one place. - No
clearAutomatically = truein 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.
@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, conditionalUPDATE, 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. clearAutomaticallydetaches loaded entities; use onlyflushAutomatically.
Read more: Part 3: Pagination and dynamic filters.
Comments
Community rules