Video in progress
How do you notice in prod that an aggregate has grown too big, and how do you shrink it?
Optimistic lock conflicts go up, loading the whole graph to change one record, and lock wait times grow. The fix is to re-check the real invariants, split the aggregate, and make the consistency between the pieces eventual through events.
📖 Answer
A real case: the Course aggregate contained lessons, the list of students, reviews and the rating. Every new review bumped the Course version. On a popular course, when dozens of users wrote reviews at the same time, the share of OptimisticLockException went above 10%, and retries raised the load even more. And for every review, thousands of student records were loaded into memory.
Symptoms:
- lots of
ObjectOptimisticLockingFailureException, especially on popular objects; - in Hibernate statistics, hundreds of entities loaded for one simple operation;
- lock waits on the
UPDATE course SET version = ...row in the database; - GC pressure: a big graph on every request.
Before shrinking, ask: which rule has to be consistent instantly?
- "A course can't have more than 100 students": is that really strict, or is it acceptable if the 101st student is rejected within a few seconds?
- "The rating equals the average of the reviews": a delay of a few seconds is perfectly fine.
The split model:
Course(id, title, lessons) - content, rarely changes
Enrollment(courseId, userId) - a separate aggregate
Review(courseId, userId, stars) - a separate aggregate
CourseRating(courseId, avg, cnt) - updated from the ReviewAdded event
Now adding a review is just an INSERT into Review. The rating is computed asynchronously, with an atomic UPDATE course_rating SET cnt = cnt + 1, sum = sum + ? if needed, so the lock is short.
The cost: the UI and the business must understand eventual consistency; you need an outbox against lost events; and a reconciliation job to recompute. For strict limits (such as the number of seats), use an atomic conditional UPDATE or a separate small "counter" aggregate, without locking the whole course.
Sign up to mark studied questions and save your progress.