Quick revision
The short answer
A sequence cannot give gapless numbers, because it hands out values outside the transaction: a rollback or crash throws the number away, and caching throws away more. A correct design keeps a counter row per year and increments it with UPDATE ... RETURNING in the same transaction that finalises the invoice, so a rollback undoes both. That serialises numbering per year, so we keep the transaction short, assign the number only at finalisation, split counters by legal series if the rules allow, and keep a normal surrogate key for joins.
What to remember
In this answer, we saw that a sequence hands out numbers outside the transaction, so rollbacks, crashes and caching always leave gaps. A counter row per series and year, incremented with UPDATE ... RETURNING inside the finalising transaction, rolls back together with the invoice and so cannot leave holes. Its row lock serialises numbering, so we keep that transaction short, number invoices only at finalisation, split counters by legal series if the rules allow, and keep a separate surrogate key for joins.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
A sequence cannot give gapless numbers, because it hands out values outside the transaction: a rollback or crash throws the number away, and caching throws away more. A correct design keeps a counter row per year and increments it with UPDATE ... RETURNING in the same transaction that finalises the invoice, so a rollback undoes both. That serialises numbering per year, so we keep the transaction short, assign the number only at finalisation, split counters by legal series if the rules allow, and keep a normal surrogate key for joins.
Why this question is asked
Gapless numbering is one of those requirements that sounds trivial and catches experienced developers out. In many countries invoice numbers must form an unbroken series per year, and an auditor who sees 2026-000041 followed by 2026-000043 will ask where 42 went. Interviewers like the question because the obvious answer, a database sequence, is wrong for an interesting reason, and because the correct answer forces a trade-off between correctness and throughput. In this answer, we will see exactly why a sequence leaves gaps, build a counter table that cannot, look at the cost of the lock it takes, and decide how to keep it fast enough for a real business.
1Why a Sequence Leaves Gaps
A sequence is built for speed under concurrency. When a session calls nextval, the sequence moves forward at once and that move is never undone, even if the transaction that asked for the number rolls back. If it were undone, every other session would have to wait until we committed or rolled back before it could take the next number, and the sequence would become a bottleneck. So the database chooses speed and accepts gaps.
Gaps appear in ordinary situations, not only in rare failures. A validation error after the number was taken, a deadlock, a timeout or a crashed application server all burn a number. With CACHE 20 on the sequence, each session reserves twenty numbers at a time and loses the unused ones when it disconnects, and a server crash can skip a whole block.
So the developer's proposal fails on the first rollback. No sequence setting fixes it; NOCACHE only makes the gaps smaller.
2A Counter Row Updated in the Same Transaction
The fix is to make the number part of the transaction. We keep a small table with one row per year (or per series and year) holding the last number used. When we finalise an invoice, we increment that row and use the new value, inside the same transaction that writes the invoice. If anything fails, the rollback undoes the increment as well, so the number is never lost.
7 messages in order. Play them, or step through them one at a time.
Because the increment rolls back with the transaction, B reuses number 1 and the series stays gapless.
Notice what the UPDATE does besides adding one. It takes a row lock on the counter row, and that lock is held until COMMIT or ROLLBACK. A second transaction finalising another invoice waits on the same UPDATE. If the first one commits, the second sees last_number = 1 and gets 2. If the first one rolls back, the second sees 0 and gets 1. In both cases the series has no hole. We add a unique constraint on (series, year, number) in the invoice table as a safety net.
In Spring this is one @Transactional method that runs the counter update, writes the number and commits. With JPA we can run the UPDATE ... RETURNING as a native query, or load the counter entity with PESSIMISTIC_WRITE, increment it and flush; the native statement is shorter and does the work in one round trip.
3What the Lock Costs and How to Keep It Small
The price of correctness is that invoice finalisation is serialised per counter row: only one transaction at a time can hold the 2026 row. Throughput therefore depends on how long each transaction holds the lock. If the transaction takes 5 milliseconds from the counter update to commit, we can finalise about 200 invoices per second; if it calls a tax service over HTTP while holding the lock and takes 300 milliseconds, we drop to about 3 per second.
So we design the flow around a short critical section. Invoices are created as drafts with only the surrogate id, edited freely, and get their legal number only at the moment of finalisation, when nothing else can fail. All slow work, such as computing taxes, rendering the PDF and sending emails, happens before the number is taken or after the commit. The counter update should be the last statement before COMMIT, so the lock is held for as little time as possible.
4Scaling Beyond One Counter
For most companies a few hundred finalisations per second is far more than enough. If it is not, we look at the legal rules rather than at clever code. Many tax regimes allow separate numbering series, for example per legal entity, per branch or per sales channel, each with its own prefix. Each series gets its own counter row, so the series lock independently and throughput grows with the number of series. We must confirm this with finance and the auditors before doing it, because a series split that the law does not allow is worse than a slow system.
Another option, when the business accepts it, is to finalise in batches: a scheduled job takes all invoices approved in the last minute, takes one counter update for the whole block, and numbers them in order inside one transaction.
5Keeping a Separate Surrogate Key
The gapless number is a business attribute, not the primary key. The invoice row keeps a normal bigint id from a sequence or identity column, created when the draft is created. Foreign keys, joins, caches and URLs use that id. The invoice number is a separate column with a unique constraint, empty until finalisation.
This separation keeps the constraints of the two worlds apart. The surrogate key can have gaps, can be generated in bulk and never changes. The business number obeys finance rules and might even change format next year, for example to include a branch code, without touching any foreign key.
6Follow-up questions
Could we use SELECT max(number) + 1 instead of a counter table?
Not safely. Two transactions can read the same maximum at the same time and both insert the same next number; the unique constraint would then fail one of them, or without it we get duplicates. Locking the table to prevent that is far coarser than locking one counter row, and the max query gets slower as the table grows.
What if an invoice is cancelled after it has been numbered?
It keeps its number. Finance rules usually require a credit note or a cancellation record rather than deleting the invoice, so the series stays unbroken and the history is explained. The database design should make deleting a finalised invoice impossible, for example by revoking DELETE and using a status column.
Does SERIALIZABLE isolation remove the need for the lock?
It changes how conflicts show up but does not remove them. Two transactions incrementing the same counter at SERIALIZABLE would see a serialization failure and one must retry, so we still serialise on the counter, only with retries instead of waiting. The plain row lock at READ COMMITTED is simpler and predictable.
7Conclusion
In this answer, we saw that a sequence hands out numbers outside the transaction, so rollbacks, crashes and caching always leave gaps. A counter row per series and year, incremented with UPDATE ... RETURNING inside the finalising transaction, rolls back together with the invoice and so cannot leave holes. Its row lock serialises numbering, so we keep that transaction short, number invoices only at finalisation, split counters by legal series if the rules allow, and keep a separate surrogate key for joins.
Open with
A sequence fails because it is non-transactional by design. nextval moves forward immediately and is never rolled back, so any failed transaction, deadlock or crash burns a number, and with caching a restart can skip a whole block.
Then, if they want more
That is fine for ids but breaks a legal gapless series. What I would build is a counter table keyed by series and year. When an invoice is finalised, the same transaction runs UPDATE invoice_counter SET last_number = last_number + 1 WHERE series and year match, RETURNING last_number, formats the number and writes it on the invoice.
If the transaction rolls back, the counter rolls back too, and the next transaction reuses the number. The update takes a row lock, so finalisation is serialised per series, and throughput is roughly one over the lock hold time.
So I keep that transaction tiny: invoices live as drafts with only a surrogate id, all slow work like tax calculation or PDF rendering happens outside, and the counter update is the last thing before commit. That easily gives hundreds per second.
If we needed more, I would ask finance whether separate legal series per entity or branch are allowed, each with its own counter. Finally, the invoice keeps a normal bigint primary key from a sequence for joins, and the invoice number is a separate column with a unique constraint as a safety net.
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.
- Official documentation
- PostgreSQL documentation, MySQL reference manual
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 "Finance requires invoice numbers that are strictly gapless per year, such as...": https://scrivio-interview-library.netlify.app/databases/stored-code/840d1c6435/