Scrivio Interview library
ScenarioIntermediate7 min read · updated 12 November 2026

Two users add items to the same shopping cart at the same moment. The rule is that a cart holds at most 50 items. Using a Cart aggregate with JPA, how do you guarantee the rule under concurrency?

The Cart root checks the 50-item limit in addItem, and a @Version field on the root makes concurrent changes visible through optimistic locking. Because adding a child item may not touch the root's own row, we force a version increment, for example with LockModeType.OPTIMISTIC_FORCE_INCREMENT or by updating an item count on the root. Then the second of two concurrent commits fails with an optimistic lock exception, and we retry by reloading the cart and checking the limit again; without a lock on the root, both transactions could pass the check and the cart could end up with 51 items.

Why this question is asked

Business rules that look simple in a single-threaded test often break as soon as two requests arrive together. A maximum number of items in a cart, seats on a flight, or the balance of an account are all rules about a group of rows, and checking them in Java is only safe if the database can tell us that someone else changed the group in the meantime. Interviewers ask this scenario to see whether we can combine aggregate design with JPA locking correctly, including the subtle part about child rows. In this answer, we will put the rule in the aggregate, reproduce the race, add a version to the root, force the version to change when items are added, and handle the failure with a retry.

1Putting the Rule in the Aggregate Root

In DDD terms, the Cart is an aggregate: the cart and its items form one consistency unit, and the Cart entity is the root through which every change goes. The rule that a cart holds at most 50 items is one of its invariants, so the check lives in the root's method, not in a controller or service.

Java
@Entity
public class Cart {
@Id private UUID id;
@Version private long version; // optimistic lock on the root
private int itemCount; // a root column that every change updates
@OneToMany(mappedBy = "cart", cascade = CascadeType.ALL, orphanRemoval = true)
private List<CartItem> items = new ArrayList<>();
public void addItem(ProductId product, int quantity) {
if (itemCount + quantity > 50) throw new CartFullException(id);
items.add(new CartItem(this, product, quantity));
itemCount += quantity;
}
}

The check is correct for one request at a time. The question is what happens when two requests run it at the same moment.

2Reproducing the Race

Suppose the cart holds 49 items. User A and user B each add one item at the same moment. Both transactions load the cart, both see 49, both pass the check, and both insert a new CartItem row. Each transaction is correct on its own, but the result is 51 items.

Step throughTwo requests pass the same check
Request ADatabaseRequest B
load cart: 49 items, version 7
load cart: 49 items, version 7
49 + 1 <= 50, pass
49 + 1 <= 50, pass
insert item, commit
insert item, commit
cart now has 51 items

7 messages in order. Play them, or step through them one at a time.

Without a lock on the root, the database sees two unrelated inserts.

Notice that the two transactions wrote different rows, two new cart_item rows. Nothing in the database connects them, so nothing stops the second commit.

3Why the Child Insert May Not Bump the Version

Optimistic locking with @Version works like this: when JPA updates the root's row, it adds the version to the WHERE clause and increments it, as in UPDATE cart SET ..., version = 8 WHERE id = ? AND version = 7. If another transaction already moved the version to 8, the update matches zero rows, and JPA throws an optimistic lock exception.

But there is a catch. The version is only checked when the root's own row is updated. With the usual bidirectional @OneToMany(mappedBy = "cart"), the foreign key lives in the cart_item row, so adding an item is just an INSERT into cart_item, and the cart row may not be updated at all. Whether a collection change increments the owner's version depends on the mapping and the provider, so we should not rely on it. If the root row is not written, both transactions commit with version 7 untouched, and the race is back.

4Forcing the Version Increment

There are two common ways to make sure every change to the aggregate touches the root. The first is the one already in our entity: a root field such as itemCount that addItem always changes. Because the root is now dirty, Hibernate issues the versioned UPDATE on every add. The second is to ask JPA explicitly to increment the version, even if no root field changed, with OPTIMISTIC_FORCE_INCREMENT.

Java
public interface CartRepository extends JpaRepository<Cart, UUID> {
@Lock(LockModeType.OPTIMISTIC_FORCE_INCREMENT)
@Query("select c from Cart c where c.id = :id")
Optional<Cart> findForUpdate(UUID id);
}
@Transactional
public void addItem(UUID cartId, ProductId product, int qty) {
Cart cart = carts.findForUpdate(cartId).orElseThrow(); // version 7 read
cart.addItem(product, qty);
} // at commit: UPDATE cart SET version = 8 WHERE id = ? AND version = 7
// Request A commits first: 1 row updated, version 8
// Request B commits second: 0 rows updated -> ObjectOptimisticLockingFailureException, rolled back

So the second transaction's insert is rolled back along with its failed version update, and the cart keeps 50 items. We only need one of the two techniques: if itemCount already makes the root dirty, the forced increment adds nothing, and the code above shows both only for comparison. Using a root field like itemCount has the extra benefit that the check no longer needs to load all the items, which matters for larger aggregates.

5Retrying the Losing Request

The losing request did nothing wrong; it just read a cart that changed. The right response is to retry: start a new transaction, reload the cart, which now shows 50 items and version 8, and run the check again. This time addItem throws CartFullException, and we return a clear message to the user.

Java
public void addItemWithRetry(UUID cartId, ProductId product, int qty) {
for (int attempt = 1; ; attempt++) {
try {
cartService.addItem(cartId, product, qty); // a new transaction each time
return;
} catch (OptimisticLockingFailureException e) {
if (attempt == 3) throw e; // give up after a few attempts
}
}
}
// attempt 1: conflict; attempt 2: CartFullException("cart is full")
Step throughAdding an item safely
  1. Load cart with its versionOPTIMISTIC_FORCE_INCREMENT
  2. Root checks count + qty <= 50
    YesAdd item, bump countNoReject: cart is full
  3. Commit: UPDATE ... WHERE version = 7
    YesDoneNoOptimistic lock failure
  4. Retry with a fresh transactionreload, check again; at most 3 attempts

4 steps in order. Play them, or step through them one at a time.

Notice that the retry wraps the transactional method from outside, so each attempt gets a fresh transaction and a fresh read. Spring Retry's @Retryable, or the retry support built into Spring Framework 7, can do the same declaratively; check your version. Retries also need a small limit, because under heavy contention endless retries just add load.

6Why Not a Pessimistic Lock?

We could instead lock the cart row with SELECT ... FOR UPDATE, through LockModeType.PESSIMISTIC_WRITE. The second request would then wait for the first to commit and see 50 items. That is a valid choice when conflicts are frequent. For carts, two simultaneous adds to the same cart are rare, so optimistic locking costs nothing in the normal case and only does work when a real conflict happens. Either way, the lock must be on the root, the single row that represents the whole aggregate.

7Follow-up questions

Could a database constraint enforce the limit instead?

A check constraint cannot count rows in another table. A trigger could, but it moves a business rule into the database where the domain code cannot see it, and it still needs care under concurrency. Keeping the rule in the aggregate with a versioned root is clearer and portable.

What happens if both users remove items concurrently?

The same mechanism applies: each removal changes itemCount and bumps the root version, so one commit wins and the other retries. Because every change goes through the root, all of them are serialised by the version check.

Is @Version on child entities needed too?

Not for this rule. The root's version protects the aggregate as a whole. Child versions only help when children are updated independently, which, in an aggregate, should not happen.

8Conclusion

In this answer, we saw that the Cart root checks the 50-item limit in addItem, but two concurrent requests can both pass the check and exceed the limit unless the database can detect the conflict on the root. A @Version field on the root gives optimistic locking, and because adding a child item may not update the root's own row, we force a version increment with OPTIMISTIC_FORCE_INCREMENT or by updating a root field such as an item count. The second commit then fails with an optimistic lock exception, and we retry by reloading the cart and checking again.

What to say in the interviewAbout 90 seconds aloud

Open with

I would put the rule inside the Cart aggregate root, so addItem checks that the count plus the new quantity is at most 50. That is correct for one request, but if the cart has 49 items and two users add at the same moment, both transactions read 49, both pass, and both insert a cart item row.

Then, if they want more

They touch different rows, so the database sees nothing wrong and we get 51. To make the conflict visible, I add a @Version field to the Cart root.

Optimistic locking only checks the version when the root's row is updated, though, and adding a child item with a mapped-by one-to-many is just an insert into the item table, so the root row may not change at all.

So I make sure every change bumps the root: either addItem also updates an itemCount column on the cart, which also saves loading all items for the check, or I load the cart with LockModeType.OPTIMISTIC_FORCE_INCREMENT.

Now the first commit updates the version from 7 to 8, and the second commit's update matches zero rows, so it fails with an optimistic locking exception and its insert rolls back.

I catch that outside the transaction and retry a couple of times with a fresh transaction, which reloads the cart, sees 50 items, and rejects the add with a clear message. If conflicts were frequent, a pessimistic lock on the cart row would also work.

About this answer

Last updated
12 November 2026
Versions it names
Spring Framework 7
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Two users add items to the same shopping cart at the same moment. The rule is that a...": https://scrivio-interview-library.netlify.app/java/domain-driven-design/bf0a122756/