Running out of integer primary keys in PostgreSQL

A table with a 4-byte integer key stops accepting inserts at 2,147,483,647. This page explains how to find at-risk sequences, convert them to bigint with controlled locking, and choose key types for new tables.

On this page

Running out of integer primary keys in PostgreSQL: what it is and when it bites

A sequence or identity column backed by a 4-byte integer (int4) has a hard ceiling of 2,147,483,647. Once the sequence reaches that value, the next insert that needs a new key fails with an error, and the application stops accepting writes to that table until the column type and sequence are changed. The failure is abrupt: nothing degrades gradually, and the table can look healthy right up to the moment inserts start failing. The fix is a two-part change, widening the column and the sequence that feeds it to bigint (int8) and updating any foreign keys that reference it, and the work is far easier to plan while there is still headroom than to run as an emergency.

Teams usually discover this risk in three situations. The first is after a growth spike, such as a product launch, a bulk import or a new integration that multiplied insert volume, which can move a sequence toward its limit much faster than the original design assumed. The second is in long-lived event, audit or log tables, where a key that was safe for a few years of traffic can become a problem over a decade or more. The third is during planned schema work, when a migration or upgrade is a natural moment to check every sequence. Start by querying the current last_value of each sequence and the column types of every primary key and foreign key, then compare the consumption rate with the remaining headroom. Confirm the exact sequence and identity behavior against the PostgreSQL documentation for your version before you schedule any change.

Finding at-risk columns before the sequence runs out

An integer key only fails when its sequence reaches 2,147,483,647, but the columns that reach that limit are rarely the ones anyone is watching. The cards below cover how to build a complete inventory, measure remaining headroom from real insert rates, and close the gaps that a simple primary key scan misses.

Inventory every integer primary key

Query the catalog for tables whose primary key or unique constraint uses int4, including columns defined as serial and integer GENERATED ... AS IDENTITY. Record the table, column, owning sequence and whether the key is the table's sole identifier. Include partitioned tables and their partitions, because each partition can carry its own default. Treat the output as the starting list, not the finished one, since the next cards add columns that a primary key scan does not return.

Read sequence position and increment

For each sequence, read last_value, increment_by, max_value, min_value and cycle. Headroom is the distance from last_value to max_value, divided by the increment, not the distance to 2,147,483,647 alone. A sequence with an increment of 10 exhausts its range in a tenth of the inserts that a default sequence would need. Confirm the current value with the sequence itself, because pg_sequences can lag behind active sessions that have cached values.

Estimate headroom from insert rates

Sample the number of values consumed over a fixed window, such as a business cycle that includes batch jobs, and divide the remaining range by that rate. Peak periods, backfills and retries can consume values far faster than average traffic, so measure several windows. Ask the application owners about planned imports and bulk loads, which can use a large share of the remaining range in one run. The result is a date range to plan around, not a precise forecast.

Check integer foreign keys in child tables

A child table can hold an int4 foreign key that references a bigint parent, or the reverse, and the mismatch blocks the parent conversion until the child is changed too. Search for foreign key constraints where the referencing column type differs from the referenced key. Also list child tables with int4 columns that reference an int4 parent, since those must be widened in the same change window. Both lists feed the conversion order.

Find counters that are not keys

Columns such as sequence numbers, invoice counters, message offsets, version fields and int4 statistics totals can overflow just as a key does, and they seldom appear in a key inventory. Search for int4 columns that receive values from nextval(), triggers or application counters, and for UPDATE statements that increment integer columns. Ask owners whether any column is compared against an external system that expects a larger range.

Review sequences with cycles and custom increments

A sequence set to CYCLE wraps around to its minimum value and starts reusing numbers, which can violate uniqueness unless a unique constraint catches it first. Sequences with a large or negative increment, or with a max_value below the type limit, run out sooner than the column type suggests. Record each non-default setting, confirm with its owner why it exists, and decide whether it should be changed in the same work that widens the column.

How converting an int4 key to bigint works and where locks come from

Changing an integer (int4) primary key to bigint (int8) is a column type change, and in PostgreSQL a type change that alters the stored representation rewrites the whole table. The ALTER TABLE ... ALTER COLUMN ... TYPE bigint statement takes an ACCESS EXCLUSIVE lock, which blocks reads and writes on the table until it finishes. On a large table, that rewrite is the outage. The change is also larger than the column alone: the sequence that feeds the key must be altered to a bigint type, the primary key index must be rebuilt, and every foreign key that references the column, along with the child columns that hold those references, must change to match. Each dependent object has its own lock behavior, so the full list should be drawn up from your schema before any ALTER runs. Confirm the exact lock level and rewrite conditions for each statement against the PostgreSQL version you run, because the behavior has changed between releases and the PostgreSQL documentation is the reference for the version in use.

The lower-lock approach avoids rewriting the existing table in place. Add a new bigint column alongside the old one, then backfill it in batches using small primary-key ranges so that each transaction is short and autovacuum keeps pace. Keep the two columns in sync for new and updated rows, either with a trigger that copies the value on every write or by having the application write both columns during a transition window. Once the backfill is complete and verified, build the new unique index concurrently, add the primary key using that index, and move foreign keys with NOT VALID followed by VALIDATE CONSTRAINT, which checks existing rows without blocking writes for the whole scan. The final swap, where the old column is dropped or renamed and the sequence default is changed, still needs a short ACCESS EXCLUSIVE lock, so set lock_timeout on that step and run it in a low-traffic window. Test the sequence of statements on a restored copy of production first, and record the lock waits you observe there.

Conversion approaches and when each fits

This table compares four ways to move a key column from int4 to bigint, with lock profile, duration drivers, rollback difficulty and the kind of table each suits. Read it by first identifying your table size, write rate and downtime tolerance, then checking which row matches that profile before you test on a copy.

ApproachLock profileDuration and rollbackBest suited to
Direct ALTER COLUMN TYPETakes an ACCESS EXCLUSIVE lock that blocks reads and writes for the full rewriteDuration grows with table size and index count; rollback means restoring from backup or a second conversionSmall or quiet tables where a maintenance window is acceptable
Shadow column with batched backfill and swapShort lock moments for adding the column and swapping names; batches run without long locksBackfill runs over hours or days depending on write rate; rollback is possible until the swap, then harderLarge busy tables where the team can run batches and keep triggers or dual writes correct
Logical replication based migrationLittle lock pressure on the source; cutover needs a brief write pause or sequence syncSetup and sync take time; rollback is simple while the old database still receives changesVery large tables or clusters where a short cutover is required and the team already runs logical replication
Rebuilt table with application cutoverLock time is limited to the cutover window; the new table is built beside the old oneBuild time is independent of live traffic; rollback depends on whether writes went to the new table yetTables with many dependent objects or where the application can switch to a new table name or schema

Converting a key to bigint with minimal locking

This sequence moves a crowded int4 primary key to bigint in stages, so that most of the work runs online and the only blocking moment is a short, rehearsed cutover.

  1. Inventory and sign off the affected keys

    The database owner and the application owners list every int4 primary key, foreign key, sequence and column that references them, along with the code paths, ORMs and exports that assume a 32-bit type. The team signs off on the list and on a cutover window with the people who can roll back. Done means every dependent object is named in a written inventory that both sides have approved.

  2. Rehearse the conversion on a restored copy

    Restore a recent backup to a staging cluster that matches production's major version, extensions and table sizes as closely as possible. Run every step of this sequence there, with the same lock_timeout and statement settings you plan to use in production, and record how long each backfill batch and the cutover take. Done means the rehearsal finishes with no unexpected locks and the application test suite passes against the converted schema.

  3. Add bigint columns and indexes concurrently

    Add a new bigint column beside the old key, without a default or rewrite, then build any new unique index with CREATE UNIQUE INDEX CONCURRENTLY so writes are not blocked. Set lock_timeout on every DDL statement so that a queued lock fails fast instead of stalling other sessions. Done means the new column and index exist, are marked valid, and the DDL log shows no failed or waiting statements.

  4. Backfill existing rows in batches

    Copy the old values into the new column in small primary key ranges, committing after each batch, so that row locks and WAL volume stay bounded. Watch replication lag, autovacuum activity and table bloat between batches, and pause if lag grows or application latency rises. Done means a query confirms that no row has a null new value and that row counts in old and new columns match.

  5. Keep new rows in sync during the transition

    Install a trigger, or use the application write path, so that every insert and update writes both the old and new key columns while the backfill runs. Include the foreign key columns in the same mapping, since referencing tables must carry the bigint values too. Done means a sample of recent writes shows matching values in both columns and the error rate in application logs stays at its normal baseline.

  6. Switch the primary key and sequence in a short window

    During the agreed window, take the locks needed to swap the primary key constraint to the new column, set the sequence to produce bigint values from the current maximum, and point defaults at the new sequence. Keep the window as short as the rehearsal showed and roll back the constraint change if the lock wait exceeds the limit you set. Done means inserts from the application succeed with values above 2,147,483,647 and the old key is no longer used for writes.

  7. Validate foreign keys and drop old objects

    Add each foreign key as NOT VALID, then run VALIDATE CONSTRAINT separately so that the scan does not hold a long lock, and only after validation remove the old columns, indexes and triggers. Confirm with the inventory from the first step that nothing still references the int4 columns. Done means all constraints show as validated, monitoring has run through a full business cycle without errors, and the old objects are removed after a verified backup.

Choosing key types for new PostgreSQL tables

For most new tables, default to a bigint identity column created with GENERATED ALWAYS AS IDENTITY. An int8 key holds values up to 9,223,372,036,854,775,807, which removes the 2,147,483,647 ceiling that causes the problems in this topic and costs 4 bytes more per key than int4. The extra width shows up in every index on the column and in every foreign key that references it, so it matters most on large, narrow tables with many secondary indexes. Still, the cost is usually small compared with rewriting a table that has run out of range. Ask your team which tables are expected to grow past a few hundred million rows, because those are the ones where the width difference is worth measuring rather than assuming.

A UUID fits better when keys must be generated outside the database, merged across systems, or exposed in URLs without revealing row counts. Random UUIDs (version 4) spread inserts across the whole B-tree index, which increases page splits, cache misses and index size on busy tables. PostgreSQL 18 added uuidv7(), which puts a timestamp in the leading bits so new values sort roughly in insertion order and keep index writes local. Confirm that your ORM, drivers, and any code that parses or validates identifiers accept a 16-byte UUID type, and test the database's index size and insert rate on a realistic copy of the workload before committing to it.

Whatever you pick, the key type propagates. A foreign key must reference a column of the same type, so changing a parent key from int4 to bigint later means changing every child column that references it, plus the indexes and constraints on those columns. Record the chosen type in your schema standards and in any code generator or migration template, so that new tables inherit it by default. A review check that flags any new integer or serial primary key is cheap to add to a migration pipeline and prevents the conversion work this topic describes from being repeated on the next table.

How the work differs by environment

On a single primary with no standbys, the conversion runs against one cluster, and the main risks are the table rewrite itself and the recovery path if something fails midway. An ALTER COLUMN that changes int4 to bigint rewrites the table and its indexes, which takes a long lock and generates a large volume of WAL. Your rollback path is the backup you took before the change, so the restore has to be proven on a separate host before the window opens.

  • Disk headroom: Confirm free space for a full copy of the table, its indexes and the WAL the rewrite produces.
  • WAL archiving: Confirm archiving is healthy so the change is covered by point-in-time recovery.
  • Restore test: Restore the pre-change backup to a scratch host and confirm the table row counts match.
  • Lock window: Ask whether the team can accept a full outage for the rewrite, or whether a shadow-column approach is needed.
  • Application behavior: Confirm the application handles bigint values in the affected columns, including any code that stores IDs in 32-bit fields.

Before scheduling, confirm the backup tool, the restore target and the maintenance window in writing with the team that owns the database.

Operational risks to plan for during the change

Converting an int4 key to bigint touches the table, its indexes, its foreign keys and every application that reads the value. The risks below share one root: a change that looks like a type swap is really a locking, replication and code-compatibility project, so each one needs a check before the window opens.

Long lock waits blocking writes

A column type change takes an ACCESS EXCLUSIVE lock, and that lock queues behind any open transaction on the table. Every write then waits behind the lock, and the queue grows while the change waits. Before the window, find long-running sessions with pg_stat_activity, set lock_timeout on the DDL so the change fails fast instead of blocking traffic, and rehearse the exact statement on a copy of production.

PostgreSQL replication docs

Replication lag from large rewrites

Rewriting a large table generates a large volume of WAL, and streaming standbys must replay all of it. Lag grows during the rewrite and can delay failover if a standby falls behind. Check standby replay lag and synchronous commit settings before starting, and confirm the rewrite plan keeps lag inside the limit your failover design assumes.

WAL growth from backfills

Backfilling a new bigint column in one large update writes every row twice and can fill pg_wal faster than archiving or replication slots release it. If archiving is failing or a slot is inactive, the disk fills. Backfill in batches with a commit between each, watch archive status and slot retention during the run, and confirm free space on the WAL volume before starting.

Application code assuming int4 keys

ORMs, generated clients, serializers and API schemas often declare IDs as 32-bit integers, and some languages parse them into 32-bit or JavaScript safe-integer types. After the change, values above 2,147,483,647 can overflow or lose precision in those layers. Search code, ORM models and API contracts for the column, and test with IDs above that limit before cutover.

Rollback after cutover

Once writes and new sequence values land on the bigint column, reverting to int4 is not a simple type change, because values above the int4 range cannot be stored there. Decide the rollback point in advance, define what happens to rows written after it, and confirm the old column stays populated until the new one has been verified in production.

Sequence headroom monitoring afterward

The fix only postpones exhaustion if nothing watches the sequences and tables that remain on int4. Add a recurring query over sequence last values against the int4 maximum for every sequence, including those behind identity columns and those on tables you did not convert. Set an alert threshold early enough to schedule the next conversion as planned work.

Questions teams ask before converting integer keys

What drives the cost of converting integer keys to bigint?

The cost follows the amount of work the change touches, not the size of the database alone. The main drivers are the number of at-risk tables, how many foreign keys and indexes reference each key, how much write traffic the tables receive during the change, how much lock time the business tolerates, and how many application services read or write those columns. Each affected table adds rewrite, verification and rollback work, and each foreign key adds constraint rebuilds and checks. Ask any partner to show the inventory of columns, dependent constraints and services that the quote is based on, and ask which parts are one-time (analysis, migration design, rehearsal, cutover) and which recur (monitoring sequence headroom after the change).

How long does an integer key conversion take?

Duration depends on the same drivers as cost: table sizes, the number of foreign keys and indexes, write volume, how much downtime or lock time is acceptable, and how many services need coordinated releases. Large tables that need a table rewrite take longer to rehearse and verify than small ones, and a team that must schedule maintenance windows with several application owners will spend more calendar time on approvals than on SQL. Ask for a schedule with separate phases for inventory, staging rehearsal, cutover and post-change monitoring, and ask which phases depend on the client's change calendar. Timelines in a written scope should state their assumptions so they can be checked against the actual environment.

Can our own team convert integer keys without a partner?

Yes, a team with PostgreSQL operators and application owners can do this in-house, and many do. The work is mostly careful planning: finding every sequence, column and foreign key that depends on int4, rehearsing the change on a copy of production, and coordinating application code that assumes 32-bit values. Teams usually need a partner when they lack spare operators for rehearsal, when the schema has many dependent objects across services, or when a regulator or auditor expects documented evidence of the change. Compare the cost of your own staff's time with a fixed-scope engagement that includes the inventory, the rehearsal and the rollback plan.

What do we need to provide for the engagement?

The work needs a staging environment that matches production closely enough to rehearse the change, including similar table sizes, indexes and PostgreSQL version. It also needs a written maintenance window policy that states which lock levels and durations are acceptable, and named code owners for each application service that reads or writes the affected columns. Read-only access to the schema catalog, sequence definitions and query logs helps build the inventory. Ask the partner to list these inputs in the scope document so that gaps are found before the schedule starts.

Does a fixed-scope quote work for this kind of change?

A fixed-scope quote works when the inputs are known, so the first step is usually a paid or agreed inventory that counts the affected tables, keys, foreign keys, indexes and services. From that inventory, the written scope can name the tables in each wave, the rehearsal runs, the cutover steps, the rollback procedure and the verification queries. Ask the provider to state what changes would reopen the scope, such as new tables found during rehearsal, extra services or a different lock tolerance. DeployOpen plans and delivers most engagements as fixed scope, with scope, deliverables and timelines agreed in writing before work starts, and does not publish a price list, so the quote follows from that written scope.

What breaks when a bigint conversion goes wrong?

The most common failures are application code that stores or parses keys in 32-bit fields, ORM mappings that still declare integers, and foreign keys or indexes that were not converted together, which leaves the schema inconsistent. Long lock waits during the table rewrite can block writes and queue up application requests. Sequences that are not advanced correctly can cause duplicate key errors after cutover. Check that every service's data types and serializers accept values above 2,147,483,647, that the test suite includes large sequence values, and that a rollback path exists for each wave.

How do we check which columns and sequences are at risk before we start?

Start by querying the catalog for sequences and identity columns typed as integer, then compare each sequence's last value with the maximum of 2,147,483,647 to estimate headroom. Also list foreign keys that reference those columns, since each one must change in the same wave. Check for logical replication publications, triggers and views that depend on the column type. Monitoring the growth rate of the sequence over several weeks gives a more reliable runway than a single snapshot. Confirm the inventory against your application code, because some services generate their own identifiers or cache values outside the database.

How DeployOpen scopes and delivers key migrations

DeployOpen treats integer key exhaustion as a scoped change to your own PostgreSQL databases, not a one-off script. We inventory the at-risk sequences and columns, agree the conversion plan in writing, and rehearse each step on a copy of your data before anything runs in production.

How we scope

  • Inventory every int4 and serial column, its sequence, and the foreign keys and indexes that reference it.
  • Record which tables, application queries and ORM mappings must change before a bigint conversion can proceed.
  • Agree the written scope, deliverables and timeline before work starts, with engagements fixed-scope by default.

How we build

  • Rehearse the table rewrite and index rebuilds on a restored copy sized like production, timing each lock window.
  • Sequence changes so application releases, column additions and constraint validation avoid long ACCESS EXCLUSIVE locks.
  • Test rollback steps and confirm that monitoring alerts fire on sequence usage before each production change.

How we hand over

  • Deliver a written runbook covering each conversion step, the lock behavior expected and the checks to run afterward.
  • Document the sequence usage alert thresholds, the owner for each at-risk key and the key type standard for new tables.
  • Walk your database and application teams through the migration and the evidence captured for your change records.

How we support

  • Offer ongoing support and upgrades as a retainer for teams that want help with the next conversion wave.
  • Review new schema changes for key type choices before they reach production, if your retainer covers design review.
  • Confirm with DeployOpen during scoping which post-handover checks, retests and monitoring reviews your contract includes.

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.