Video in progress
What happens if `allocationSize` in `@SequenceGenerator` doesn't match the database sequence's `INCREMENT BY`?
Hibernate's pooled optimizer treats the sequence value as a block boundary. With allocationSize = 50 and increment by 1 in the database, two instances or two sessions can land in each other's ranges, generate the same id, and fail with a duplicate key error.
📖 Answer
How the pooled optimizer thinks: nextval returned 100, so the range 51…100 is mine and I'll hand those out from memory. That's correct only if the sequence in the database also advances by 50.
Suppose the migration says:
create sequence order_seq start with 1 increment by 1;
and the entity says:
@SequenceGenerator(name = "order_seq", sequenceName = "order_seq", allocationSize = 50)
Instance A got nextval = 2 and uses the 50 ids before 2. Instance B got nextval = 3, and its range is almost the same. The result: duplicate key value violates unique constraint "orders_pkey", but only under load and at random.
If Hibernate (5.4+) can read the sequence metadata at startup, it checks for this mismatch: hibernate.id.sequence.increment_size_mismatch_strategy (default EXCEPTION, also LOG, FIX, NONE). But the metadata can't always be read, so don't rely on it. Make both match by hand:
create sequence order_seq start with 1 increment by 50;
Choosing allocationSize:
- 1: a
nextvalround trip for every insert, and batch inserts slow down; - 50 (the JPA default): enough for most cases;
- larger: fewer round trips, but after a restart you get big "gaps" in the ids. Gaps are normal; don't give any business meaning to the ids being consecutive.
In Spring Boot, if you write @GeneratedValue(strategy = SEQUENCE) without a generator, Hibernate 6 expects a <entity>_seq sequence with a step of 50 derived from the entity name, so match your Flyway migration to that.
Sign up to mark studied questions and save your progress.