Scrivio Interview library
DebuggingIntermediate6 min read · updated 12 November 2026

After a migration that created sequences with INCREMENT BY 1, a service using @SequenceGenerator with allocationSize = 50 starts throwing duplicate key errors. Explain.

Hibernate's pooled optimizer assumes the sequence increases by allocationSize, so it treats each sequence value as a reservation of a block of 50 ids. After the migration the sequence increases by 1, so consecutive values reserve blocks that overlap almost completely, and two instances, or even one instance moving to its next block, generate ids that are already used. The fix is to make the sequence increment match allocationSize, or to set allocationSize = 1 and pay one round trip per insert; Hibernate can also check the increment at startup.

Why this question is asked

Duplicate key errors on a generated primary key look impossible at first: the database sequence never returns the same number twice, so how can two rows get the same id? The answer lies in how Hibernate turns one sequence value into many ids, and it is a common outcome of migrations that recreate sequences with tool defaults. Interviewers ask it to see whether we understand the pooled optimizer instead of treating ids as a black box. In this answer, we will recap how the pooled optimizer reserves blocks, reproduce the overlap with real numbers, look at the fixes and their costs, and see how to catch the mismatch at startup.

1A Quick Recap of the Pooled Optimizer

Calling the sequence for every insert would cost a round trip per row. So Hibernate uses an optimizer, and the default for sequences is the pooled optimizer. With allocationSize = 50, Hibernate calls nextval once and uses the returned value to define a block of 50 ids that this instance may hand out from memory. It assumes that the next nextval call, from any instance, will return a value 50 higher, so blocks never overlap.

That assumption only holds if the sequence itself was created with INCREMENT BY 50. The mapping and the database object must agree, and nothing in the SQL forces them to.

2What Goes Wrong With INCREMENT BY 1

In the pooled scheme, a sequence value v reserves the block of 50 ids that ends at v, that is v - 49 to v (the pooled-lo variant starts the block at v instead; it overlaps in the same way). Let us follow two instances after the migration recreated the sequence with INCREMENT BY 1.

Java
-- after the migration: create sequence customer_seq start with 1000 increment by 1;
-- Instance A: select nextval('customer_seq') -> 1000 block 951..1000
-- Instance B: select nextval('customer_seq') -> 1001 block 952..1001
-- A inserts id 951, B inserts id 952, A inserts 952 ...
-- ERROR: duplicate key value violates unique constraint "customer_pkey"
-- Key (id)=(952) already exists.
-- even one instance: after using 951..1000 it calls nextval -> 1001, block 952..1001: 952 is reused
Blocks reserved by the pooled optimizer
Sequence callINCREMENT BY 50INCREMENT BY 1
A: nextval1000 -> ids 951..10001000 -> ids 951..1000
B: nextval1050 -> ids 1001..10501001 -> ids 952..1001
A: next block1100 -> ids 1051..11001002 -> ids 953..1002
Resultno overlap49 of 50 ids shared with the previous block

Notice that the sequence did nothing wrong: it returned 1000 and 1001 as promised. The duplicates come from Hibernate expanding each of those values into 50 ids. With the correct INCREMENT BY 50, the two calls would have returned 1000 and 1050, giving the separate blocks 951 to 1000 and 1001 to 1050. It also explains why the errors started after the migration and why they are intermittent: they appear when the blocks in use happen to collide, and also when existing rows already occupy ids in the new blocks.

3Fix 1: Make the Sequence Match allocationSize

The best fix is to correct the database object. We change the increment and move the sequence past the highest id already used, so the next blocks start above existing data.

SQL
-- PostgreSQL
ALTER SEQUENCE customer_seq INCREMENT BY 50;
SELECT setval('customer_seq', (SELECT max(id) FROM customer) + 50);
-- next nextval returns a value whose whole block lies above max(id)

This keeps the performance benefit of the pooled optimizer: one sequence call per 50 inserts and batched inserts. We put the change in a new migration, not by hand, so every environment gets it, and we fix the migration template that created the wrong increment.

4Fix 2: Set allocationSize = 1

The alternative is to change the mapping so that Hibernate's assumption matches the sequence. With allocationSize = 1, Hibernate calls nextval for every new entity and uses the value as it is, so there is nothing to overlap.

Java
@SequenceGenerator(name = "customer_seq", sequenceName = "customer_seq", allocationSize = 1)
// each persist: select nextval('customer_seq') -> one extra round trip per insert

This is safe but slower: 10,000 inserts now need 10,000 sequence calls in addition to the inserts. It is reasonable for low-volume tables, or when other applications insert into the same table using nextval directly and we cannot change the increment. When other writers exist, matching increments matter even more, because they would otherwise take values inside Hibernate's blocks.

5Catching the Mismatch at Startup

Hibernate can compare the mapping with the database. When it starts, it can read the increment of each sequence from the database metadata and compare it with allocationSize. The setting hibernate.id.sequence.increment_size_mismatch_strategy decides what happens on a mismatch: throw an exception and stop startup, log a warning, fix the in-memory allocation size to the database value, or do nothing. The default and the exact behaviour depend on the Hibernate version, so check your version and set it explicitly to fail fast.

Schema validation with spring.jpa.hibernate.ddl-auto=validate also checks that the sequences exist, and an integration test that inserts from two concurrent sessions catches the overlap in a few seconds. Either one would have stopped this migration before it reached production.

Properties
spring.jpa.properties.hibernate.id.sequence.increment_size_mismatch_strategy=exception
# startup fails with a message naming customer_seq and both increments

6Follow-up questions

Why did it work before the migration?

The old sequence was presumably created by Hibernate's schema tooling or a script that used INCREMENT BY 50, matching allocationSize. The migration tool recreated it with its own default of 1, and nothing compared the two until ids collided.

Do gaps in ids indicate a problem?

No. With pooled blocks, unused ids are lost when an instance stops, so gaps are normal and harmless for surrogate keys. Duplicates are the problem; gaps are not.

Is pooled-lo safer than pooled?

No for this bug. pooled-lo uses the sequence value as the start of the block instead of the end, but it still assumes the sequence advances by the block size. With INCREMENT BY 1, its blocks overlap in the same way.

7Conclusion

In this answer, we saw that the pooled optimizer expands every sequence value into a block of allocationSize ids and assumes the sequence increments by the same amount. A migration that recreated the sequence with INCREMENT BY 1 made consecutive blocks overlap, so instances generated ids that were already used. We fix it by altering the sequence to INCREMENT BY 50 and moving it past existing ids, or by setting allocationSize = 1 at the cost of a round trip per insert, and we guard against it with Hibernate's startup check and validation.

What to say in the interviewAbout 90 seconds aloud

Open with

The key is how Hibernate's pooled optimizer uses the sequence. With allocation size 50, Hibernate does not use the sequence value as the id. It treats each value as a reservation of a block of 50 ids and hands those out from memory, assuming the next nextval call, from any instance, returns a value 50 higher.

Then, if they want more

That only works if the sequence is created with increment by 50. The migration recreated it with increment by 1. So instance A gets 1000 and uses roughly 951 to 1000, instance B gets 1001 and uses 952 to 1001, and they collide almost immediately. Even a single instance reuses ids when it moves to its next block.

The sequence itself never repeats a value; the duplicates come from Hibernate expanding overlapping values into blocks. To fix it, I would add a migration that alters the sequence to increment by 50 and uses setval to move it above the current max id plus the block size, which keeps the batching benefit.

If I could not change the sequence, for instance because other applications use it directly, I would set allocation size to 1, accepting one sequence round trip per insert.

To prevent it next time, I would set Hibernate's sequence increment mismatch strategy to fail at startup, keep ddl-auto validate or a migration test in the pipeline, and fix the migration template.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. 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 "After a migration that created sequences with INCREMENT BY 1, a service using...": https://scrivio-interview-library.netlify.app/databases/jpa-fundamentals/dd0d49f38a/