Postgres sequence repair: protect the allocation boundary
Diagnose a generated primary-key collision without moving a healthy allocator backwards.
Quick answer
Repair a lagging Postgres sequence only after identifying the generated-key constraint and reconciling every allocator consumer. Imported explicit keys can leave the generator behind, while cached or reserved values can put it ahead of stored rows. Pause writers, choose a forward value within the sequence bounds, and verify a normal insert without an explicit ID.
On this page
A Postgres sequence repair is justified when a generated key collides with an existing row and the allocator is demonstrably behind the imported data. First identify the failing constraint and the generator that supplies that column. Then establish a maintenance boundary before changing allocation state. A table maximum alone cannot tell you whether resetting a busy sequence would reuse a value already allocated elsewhere. [1][2][4]
Scenario: a fictional invoice import preserves external IDs, while the destination table's default sequence still starts near its initial value. Ordinary inserts begin failing on the primary key. The exercise below uses a small, explicitly named sequence so you can see each state transition. It is an isolated reproduction, not a script for resetting every sequence in an application database.
Before choosing a reset value, identify every process that can allocate an invoice ID and establish how it will stop. If the answer is unclear, gathering that evidence is the next action. A convenient reset command cannot supply it.
Does the error actually implicate the sequence?#
Read the named constraint and the conflicting key in the error. A duplicate email address or invoice reference requires a different investigation from a generated primary-key collision. Even an ID collision can come from an application explicitly sending the value, a trigger supplying it, or a custom allocator. Confirm the insertion path before changing the sequence.
For an identity column, PostgreSQL uses an implicit sequence, but identity alone does not guarantee uniqueness. The primary key or a unique constraint supplies that enforcement. Explicit values can also enter an identity column under the rules of BY DEFAULT or OVERRIDING SYSTEM VALUE. Switching an existing definition to identity is therefore not a substitute for reconciling imported keys. [1]
Capture the table definition, default expression, associated sequence and sequence parameters. Check whether that generator serves another table or application path. Our worked example assumes an ascending, non-cycling allocator with its ordinary increment and no custom ID reservation service. Descending sequences, unusual increments and shared allocators need their own next-value calculation.
Sequence state and row state are separate. nextval allocates a value; it does not search a table for its largest ID. PostgreSQL explicitly describes the sequence as its own generator object. An explicit import can add rows without making the sequence follow them. Conversely, failed transactions can allocate numbers without leaving rows behind. [2][4]
Do not call nextval merely to inspect the current value in production. That call advances the generator. Read its known state and parameters under the appropriate permissions instead, while acknowledging that a busy system can change immediately after the observation. The documentation permits examining a sequence's state with SELECT; the result is not a lock on the allocator. [4]
What does the imported ledger demonstrate?#
The following SQL creates a disposable fixture with a deliberately lagging allocator. Run it only in a test database you own. The schema name is specific to this exercise, and the table's default refers to the explicitly created sequence rather than an inferred naming convention.
CREATE SCHEMA editorial_sequence_demo;
CREATE SEQUENCE editorial_sequence_demo.invoice_id_seq
START WITH 1 INCREMENT BY 1 NO CYCLE CACHE 1;
CREATE TABLE editorial_sequence_demo.invoice (
id bigint PRIMARY KEY
DEFAULT nextval('editorial_sequence_demo.invoice_id_seq'),
external_ref text NOT NULL
);
ALTER SEQUENCE editorial_sequence_demo.invoice_id_seq
OWNED BY editorial_sequence_demo.invoice.id;
INSERT INTO editorial_sequence_demo.invoice (id, external_ref)
VALUES (1, 'import-one'), (100, 'import-hundred');Scenario: the import has inserted IDs 1 and 100. It has not called the default generator. A subsequent insert omitting id asks the sequence for its initial value and collides with the existing primary key. That is the failure we want to explain; the import's business references are invented labels.
-- Expected failure in the disposable fixture; run separately.
INSERT INTO editorial_sequence_demo.invoice (external_ref)
VALUES ('first-generated');
-- Read state after that failed statement, outside an aborted transaction.
SELECT max(id) FROM editorial_sequence_demo.invoice;
SELECT last_value, is_called
FROM editorial_sequence_demo.invoice_id_seq;The distinction between a failed statement and an aborted transaction matters during diagnosis. If you reproduce an error inside an explicit transaction, roll that transaction back before issuing more queries. The failed allocation itself is not recovered by rollback. PostgreSQL sequences intentionally permit holes rather than serializing every allocation around transaction success. [2][4]
For this controlled fixture, choose a next value above the imported range and the observed allocation state. The example restart value is a literal derived from the fixture, not an instruction to use the same number in a real table. Save the chosen restart value with the observed table maximum and sequence state.
BEGIN;
SET LOCAL lock_timeout = '3s';
LOCK TABLE editorial_sequence_demo.invoice IN ACCESS EXCLUSIVE MODE;
SELECT max(id) FROM editorial_sequence_demo.invoice;
SELECT last_value, is_called
FROM editorial_sequence_demo.invoice_id_seq;
ALTER SEQUENCE editorial_sequence_demo.invoice_id_seq
RESTART WITH 101;
COMMIT;
INSERT INTO editorial_sequence_demo.invoice (external_ref)
VALUES ('accepted-generated') RETURNING id;Scenario: the acceptance insert should return 101 in the isolated fixture. It also creates a real test row. A production acceptance insert needs a legitimate business record or a separately approved cleanup policy; do not add disposable invoice records to a live ledger to imitate this exercise.
Why must the allocation boundary be quiet?#
The table lock in the example protects that table's maintenance step, but it is not a universal lock on every way the sequence can be used. A caller can allocate an ID before inserting a row, keep a reserved value outside the database, or use the same generator from a different path. Stop and reconcile those producers before treating the table as the whole allocation boundary.
Cached allocations add another complication. PostgreSQL can reserve sequence values for a session, and the recorded last_value may reflect allocation rather than the last row stored in your table. Its documentation also warns that other sessions can continue through preallocated values before noticing changed sequence-generation parameters. A MAX-based repair that ignores the allocator can move backwards over valid reservations. [3][4]
Our conservative maintenance procedure pauses application writers, importers, jobs and direct sequence consumers, lets active work finish, and replaces or reconnects the relevant client sessions according to the service's maintenance policy. The operator must still account for durable IDs or reservation ranges stored outside those sessions. Reconnecting a pool cannot revoke an ID already handed to another system.
Treat a generator ahead of the table as a stop condition for this recipe. A deleted high row, an aborted transaction or a reserved range can all explain that state. Gaps are not evidence that the allocator needs to be reduced. If the business needs a contiguous document number, design that requirement separately from the database surrogate key. [2][4]
The other stop condition is an unknown consumer. If nobody can explain a direct sequence caller or a shared generator, leave the repair pending and identify its owner. That may be inconvenient during an incident, but it is more precise than declaring that a lock on one table makes a global reset safe.
Which repair should the operator approve?#
For the paused, ascending fixture, a deliberate RESTART WITH states which value the next allocation should return. PostgreSQL distinguishes transactional restart from setval: restart blocks concurrent operations on the sequence, while a setval change is immediately visible and is not undone when its surrounding transaction rolls back. Ownership is required for ALTER SEQUENCE. [2][3]
setval remains a valid tool when its semantics are the intended ones. Its optional boolean determines whether the supplied value itself or an incremented value comes next. Write that boolean explicitly in a repair record, and calculate the supplied value under the generator's actual increment and bounds. Do not combine “maximum plus increment” with “advance again” accidentally. [2]
The rollback difference deserves its own test because it can invalidate a proposed recovery plan. This separate disposable sequence avoids changing the invoice fixture while demonstrating that a transaction rollback does not restore setval state.
CREATE SEQUENCE editorial_sequence_demo.rollback_probe;
BEGIN;
SELECT setval('editorial_sequence_demo.rollback_probe', 500, false);
ROLLBACK;
SELECT nextval('editorial_sequence_demo.rollback_probe');
-- The requested value still applies: expect 500, not the initial value.For an empty table, the maximum is absent. Do not let a generic expression quietly turn that absence into an arbitrary repair value. Determine whether the table is newly created, intentionally cleared, or missing data, and inspect the sequence's configured start and existing allocations. These are different operational states even though the row count is the same.
The same caution applies to a complete database restore. Do not assume that every restore leaves every sequence behind, and do not run a database-wide reset because one custom import bypassed a default. Check the actual restore or import process and the affected generator. A targeted diagnosis preserves unrelated allocators and makes the repair auditable.
What belongs in the maintenance decision record?#
Record the actual generator and the affected consumers, not just a copied reset statement. For the fictional invoice table, the handoff identifies the imported key range, the observed sequence state, the generator's increment and bounds, and the chosen restart value. It names who paused the API, jobs and importer, and who confirmed that no outstanding externally reserved IDs remain. These are evidence fields an operator must fill, not defaults this article can infer.
Write the proposed next invoice ID in its own field, beside the table maximum and known allocations. A reviewer should be able to explain why that value is above every relevant assigned or reserved value before checking whether the command uses RESTART or setval. This ordering exposes an incorrect calculation that otherwise hides inside a syntactically valid statement.
Use explicit failure branches in the same handoff:
| Observation before repair | Decision for this procedure |
|---|---|
| Imported keys are above the known allocator and all consumers are paused | Review a forward restart within the configured bounds |
| Allocator is ahead of the table maximum | Preserve it and investigate gaps or reservations |
| Another application shares the generator | Reconcile that application before choosing a value |
| Table is empty after an unexplained import | Investigate missing data before changing allocation |
| Sequence cannot represent the chosen next value | Plan capacity or key-type work rather than forcing the restart |
Our rollback plan also has distinct meanings. Rolling back an uncommitted transactional restart is different from restoring deleted data, undoing an already committed import or recovering a value handed to another system. Write which operation can actually be reversed and which effects require reconciliation. PostgreSQL's sequence semantics do not supply a general undo function for a business migration. [2][3]
If the maintenance lock times out, the decision remains unapplied. Preserve the error and inspect the blocking work through the normal operational process. Do not respond by removing the timeout and leaving an unobserved maintenance command in the queue. The purpose of this record is to let another operator determine whether allocation changed, whether writers resumed and which acceptance evidence is still missing.
How do you verify the next real insert?#
Verify the normal insertion path without an explicit ID, inspect the returned key, and confirm that the expected row and constraints exist. Then resume writers in a controlled order while watching for the same named constraint failure. A successful hand-written insert with a manually chosen ID bypasses the behavior under repair.
Preserve the before-state, selected restart value, transaction outcome and returned application key. Distinguish the evidence that the sequence moved from the evidence that the importer is fixed. If the importer keeps supplying conflicting explicit IDs, repairing the generator only removes one source of collisions.
Our upsert input guide covers a different duplicate-key family: multiple source rows competing for the same conflict key. The ALTER TABLE lock guide explains why a maintenance command waiting behind long transactions can itself affect service availability. Keep these diagnoses separate even when they produce errors in the same migration window.
The disposable SQL exercise was run on PostgreSQL 17.11, including the generated collision, restart acceptance, setval rollback, restart rollback and a direct allocation while the table was locked. It did not test a production repair or reconciliation of cached multi-session reservations. PostgreSQL documentation cited here is version 18 [1][2][3][4]; review the matching documentation and observed behavior for your installed release before applying a maintenance plan.
What else should you check?#
- Does an identity column prevent imported-key collisions?
- Identity uses an implicit sequence but does not itself enforce uniqueness. PostgreSQL can accept explicit values under the identity definition's rules, and a primary key or unique constraint enforces collisions. Reconcile the imported values and allocator state rather than assuming identity repairs them. [1]
- Does rolling back undo setval?
- PostgreSQL states that setval changes are immediately visible and are not undone when the calling transaction rolls back. Include that behavior in the recovery plan. A transactional sequence restart has different semantics and still needs a coordinated allocation boundary. [2][3]
- Should I reset every sequence after a restore?
- Investigate the actual restore or import process and the generator implicated by the error. A custom explicit-ID import does not establish that every database sequence is wrong. Database-wide resets can change unrelated allocators and discard the evidence needed for a targeted diagnosis.
- What if the sequence is already ahead of MAX(id)?
- Preserve that state while investigating allocations, gaps and external reservations. Stored rows are only part of the allocator's history. Moving the generator backwards can reuse values already handed out, and PostgreSQL does not promise gapless numbering. [2][4]