Video in progress

Why do gaps appear in a sequence, and how does `allocationSize` in Hibernate relate to the sequence?

A sequence isn't tied to the transaction: a value taken isn't returned even on rollback, and caching and crashes also leave gaps. If Hibernate's allocationSize=50, it reserves a block of 50 ids in one call, so the DB sequence's INCREMENT BY must also be 50.

📖 Answer

A sequence is deliberately non-transactional: if it were returned on rollback, all transactions would have to wait for it and run one after another. So gaps are normal, and it's a mistake to treat an id as a gapless "account number" or "invoice number". If you need gapless numbers, you work with a separate counter row and a lock.

On the Hibernate side:

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "order_seq")
@SequenceGenerator(name = "order_seq", sequenceName = "order_seq", allocationSize = 50)
private Long id;
CREATE SEQUENCE order_seq INCREMENT BY 50;

With the pooled optimizer, if nextval returns 101, Hibernate hands out the range 52..101 from memory (the exact range depends on the optimizer type). One DB call for 50 inserts speeds up batch inserts.

A mismatch is dangerous: if the sequence is INCREMENT BY 1 and Hibernate thinks 50, two instances hand out the same ids and you get duplicate key errors. Hibernate 6 tries to detect this mismatch when it validates the schema, but be careful with sequences written by hand with Flyway.

The IDENTITY strategy disables batch inserts, because Hibernate has to know the id after every insert. For write-heavy tables I choose a sequence.