Practical technical guides / Core IT: databases (PostgreSQL sequences)

PostgreSQL Sequences Leave Gaps: Rollbacks, Caching and Crashes, and a Gapless Counter When You Need One

Measured on PostgreSQL 18.4: rollbacks, ON CONFLICT and failed inserts use up ids, CACHE interleaves sessions, a crash skips 32 values. A gapless counter costs a lock.

By Sandeep Belgavi · Published 2026-11-18

Measured on PostgreSQL 18.4: rollbacks, ON CONFLICT and failed inserts use up ids, CACHE interleaves sessions, a crash skips 32 values. A gapless counter costs a lock.

Why order 2 is missing

Hansini runs the finance reports at Belgavi's Book Store. The orders table uses an identity column, and one morning the report shows orders 1, 3, 5, 7, 8 and 9. Orders 2, 4 and 6 do not exist. Nobody deleted them. Later, after a server restart that followed a crash, the next order is numbered 34 instead of 10.

Both are normal PostgreSQL behaviour, and both surprise people who read an identity column as a count. The PostgreSQL 18 documentation for sequence functions is explicit: to avoid blocking concurrent transactions, a value obtained by nextval is not reclaimed if the transaction aborts, so aborts or crashes can leave gaps, and an INSERT ... ON CONFLICT computes the row, including nextval, before it detects the conflict. Sequences therefore cannot provide gapless numbering.

This article reproduces every source of gaps on PostgreSQL 18.4, explains when gaps are harmless, and builds a gapless counter for the one place the store needs it: invoice numbers.

Each source of gaps, measured

The companion probe runs against a scratch PostgreSQL 18.4 cluster. Two sessions, a and b, insert synthetic orders into a table whose id is GENERATED ALWAYS AS IDENTITY.

ScenarioIds present afterwards
Insert, then a transaction that inserts and rolls back, then insert1, 3
Add an INSERT ... ON CONFLICT DO NOTHING that conflicts, then insert1, 3, 5
Add an insert that fails a NOT NULL check (SQLSTATE 23502), then insert1, 3, 5, 7

Each failed or skipped insert consumed a value. The rollback is the classic case; the other two catch people out because no transaction was rolled back by the application. A statement that fails a constraint has already evaluated its defaults.

A sequence with CACHE 20 adds another effect. With two sessions calling nextval alternately, the probe recorded a getting 1, b getting 21, a getting 2 and b getting 22. Each session reserved a block of 20 and hands out values from its own block. The CREATE SEQUENCE documentation warns that with a cache above one, values are distinct but not generated in order across sessions, and that unused cached values are lost when a session ends.

Commit order is not id order

Gaps are not only permanent. Session a begins a transaction and inserts order BB-1307, which takes id 8. Before a commits, session b inserts BB-1308 and commits; it gets id 9. While a is still open, a reader sees ids 1, 3, 5, 7, 9. After a commits, the reader sees 1, 3, 5, 7, 8, 9.

So a consumer that reads new rows with WHERE id > last_seen_id and saves the largest id it saw would record 9, then skip 8 forever. An increasing identity column is an increasing value, not a log of commits. Incremental readers need a commit-ordered source, such as logical decoding, or a look-back window with deduplication.

Crash recovery skips values

PostgreSQL does not write a WAL record for every nextval. The source for sequences in 18.4 defines SEQ_LOG_VALS as 32 and explains that it pre-logs that many values in advance, so in the event of a crash up to that many values can be skipped. The probe confirms it with an immediate shutdown, which takes the same recovery path as a crash:

SequenceValues taken before the crashFirst value after recoveryValues skipped
CACHE 1, one value13432
CACHE 1, five values1 to 53428
CACHE 1, forty values1 to 406726
CACHE 20, one value15351

With CACHE 20 the logged block is the cache plus the 32 pre-logged values, so a crash right after the first call jumps to 53. A promoted standby is in the same position, because it knows only the values logged in the WAL; the probe did not test failover.

Identity columns are sequences

An identity column is backed by an ordinary sequence that PostgreSQL creates and owns, so everything above applies to GENERATED ALWAYS AS IDENTITY, GENERATED BY DEFAULT AS IDENTITY and the older serial types alike. Sequence options, including CACHE, can be set on an identity column with ALTER TABLE ... ALTER COLUMN ... SET CACHE. The choice between them is about who may supply values, not about gaps: ALWAYS rejects explicit values unless the insert says OVERRIDING SYSTEM VALUE, which protects the sequence from collisions after someone loads rows by hand. None of the variants promises consecutive values.

When gaps are fine

For a surrogate key they are fine. The id identifies a row; its value carries no meaning, and nobody should count rows by subtracting ids. The cheap, concurrent sequence is exactly what a key needs. Check your reports instead: a dashboard that computes order counts as max(id) - min(id) + 1 is wrong from the first rollback.

Gaps are not fine when an external rule requires consecutive numbers, such as invoice numbering in many tax regimes, or when people treat the number as evidence that nothing was deleted. Then the number is a business value and must be generated as one.

A gapless counter and its cost

Keep a counter row per series and take the next number inside the same transaction that creates the invoice:

CREATE TABLE invoice_counter (series text PRIMARY KEY, last_no bigint NOT NULL);
INSERT INTO invoice_counter VALUES ('BB-2026', 0);

BEGIN;
UPDATE invoice_counter SET last_no = last_no + 1
 WHERE series = 'BB-2026'
RETURNING last_no;                       -- use this value for the invoice
INSERT INTO invoice (series, no, order_ref) VALUES ('BB-2026', 1, 'BB-1301');
COMMIT;

The UPDATE takes a row lock that is held until commit or rollback. A rollback undoes the increment along with the invoice, so the probe's sequence of commit, rollback, commit leaves invoices 1 and 2, with no gap.

That lock is also the cost. In the probe, session a takes a number and keeps its transaction open; session b with lock_timeout of 300 ms fails with SQLSTATE 55P03 instead of getting a number. Without the timeout it would simply wait. Every invoice in a series is serialised through one row, for as long as each invoice transaction lasts. That is acceptable for invoices, which are few and short, and unacceptable for every order line.

Keep the transaction that holds the counter short. Do the slow work, such as rendering a PDF or calling a payment service, before taking the number or after committing. Use separate series, for example per legal entity or per year, if contention matters. Never fetch the number in one transaction and use it in another, or a crash in between creates exactly the gap the counter exists to prevent.

Verification

  • Assert gaplessness directly: SELECT no FROM invoice WHERE series = $1 ORDER BY no must equal 1..n.
  • Test the rollback path, a constraint failure after taking the number, and a crash between taking and using it.
  • Measure lock waits on the counter row in production with pg_stat_activity wait events, and alert before they become user-visible.
  • For identity columns, test that no report or consumer assumes consecutive or commit-ordered ids.

Failure modes

  • Copying the counter into an application cache to avoid the lock reintroduces gaps on every crash.
  • Using SELECT max(no) + 1 without a lock gives two transactions the same number; the primary key then rejects the second invoice and the caller has to retry.
  • Resetting a sequence with setval while sessions hold cached blocks: the documentation notes other sessions do not see the change until they use up their cached values.
  • Unlogged sequences reset to their initial state after a crash, so they can hand out values that already exist.

Primary references and authorship

Original explanation and synthetic examples by Sandeep Belgavi. Companion code: Sandeep-BA/agent-decision-lab/examples/python/postgres_sequence_gaps. Views are my own and do not represent any employer, past or present.