Skip to main content

Integer Primary Key Overflow: Why Your IDs Run Out Before Your Rows Do

The counter behind an auto-increment column counts numbers handed out, not rows kept. Here's how to measure your real runway and find every hidden 32-bit copy.

Updated 11 min readMarkdown
Part of seriesThe Systems Behind the Software
Integer Primary Key Overflow: Why Your IDs Run Out Before Your Rows Do

The query most teams use to check for integer overflow can report 0.0001% used on a table that is 99% full. And the table doesn't need anywhere near 2.1 billion rows to get there.

Both facts come from the same misunderstanding: an auto-increment column doesn't count rows. It counts numbers handed out. This guide covers how to measure the right number on PostgreSQL and MySQL, why upsert-heavy tables burn IDs dozens of times faster than they grow, and how to find every place the 32-bit limit survives after you migrate to BIGINT.

The 60-second check

Run this first. It measures every serial and identity column in a PostgreSQL 10+ database against the column's type, which matters for reasons covered below.

SELECT a.attrelid::regclass                  AS table_name,
       a.attname                             AS column_name,
       format_type(a.atttypid, a.atttypmod)  AS column_type,
       pg_sequence_last_value(s.seqrelid)    AS last_value,
       round(100.0 * pg_sequence_last_value(s.seqrelid) /
         CASE a.atttypid
           WHEN 'int2'::regtype THEN 32767
           WHEN 'int4'::regtype THEN 2147483647
           ELSE 9223372036854775807
         END, 2)                             AS pct_used
FROM pg_sequence s
JOIN pg_depend d
  ON d.classid = 'pg_class'::regclass
 AND d.objid = s.seqrelid
 AND d.refclassid = 'pg_class'::regclass
 AND d.deptype IN ('a', 'i')     -- serial and identity columns
JOIN pg_attribute a
  ON a.attrelid = d.refobjid
 AND a.attnum = d.refobjsubid
ORDER BY pct_used DESC NULLS LAST;

On MySQL 8.0+, disable the statistics cache first. information_schema.TABLES.AUTO_INCREMENT is cached for 24 hours by default.

SET SESSION information_schema_stats_expiry = 0;

SELECT t.table_schema, t.table_name, c.column_type, t.auto_increment,
       ROUND(100 * t.auto_increment / CASE
         WHEN c.column_type LIKE 'int%unsigned'    THEN 4294967295
         WHEN c.column_type LIKE 'int%'            THEN 2147483647
         WHEN c.column_type LIKE 'bigint%unsigned' THEN 18446744073709551615
         WHEN c.column_type LIKE 'bigint%'         THEN 9223372036854775807
       END, 2) AS pct_used
FROM information_schema.tables t
JOIN information_schema.columns c
  ON c.table_schema = t.table_schema
 AND c.table_name = t.table_name
 AND c.extra LIKE '%auto_increment%'
WHERE t.auto_increment IS NOT NULL
ORDER BY pct_used DESC;

If anything near the top surprises you, the rest of this explains why.

Why the sequence-only check lies

The common shortcut is pg_sequences, comparing last_value to max_value. That compares the counter with the sequence's maximum, and the sequence and the column can disagree in both directions:

  • Sequence smaller than the column. Since PostgreSQL 10, a serial column gets a sequence declared AS integer. If you ALTER the column to bigint and stop there, inserts still fail at 2,147,483,647. You also need ALTER SEQUENCE ... AS bigint.
  • Sequence bigger than the column. Before PostgreSQL 10, sequences always had a bigint range, even behind an integer column. Databases that started on older versions can still carry them, and the sequence-only check reports almost nothing used while the column is nearly full.

Measure against the column type and both cases show up correctly.

Why IDs run out before rows do

A sequence works like the ticket roll at a deli counter. It counts tickets pulled, not customers served, and it never takes a ticket back. That's by design: reclaiming numbers would force every insert to wait for every other insert to commit. PostgreSQL's own developers state plainly that sequences can't give you gapless numbering.

So any code path that pulls a number and keeps no row moves the counter without moving COUNT(*):

Two gauges against the INT limit: 40 million rows stored is 2 percent, 2.14 billion IDs handed out is 99.7 percent. Five ways code spends a number without keeping a row are listed below.
Burner PostgreSQL MySQL
Upsert that updates ON CONFLICT DO UPDATE evaluates nextval() before it detects the conflict ON DUPLICATE KEY UPDATE is a "mixed-mode insert"; the allocated value may go unused
Insert that's ignored ON CONFLICT DO NOTHING INSERT IGNORE
Rollback / failed constraint value is never returned value is "lost"
Retry after deadlock or timeout new value per attempt new value per attempt
Delete-and-reload sync every reload re-spends the whole table same

ORM helpers such as Laravel's upsert() and insertOrIgnore() or Rails' upsert_all compile to the statements in the first two rows, so the burn often hides behind a single method call.

The number worth tracking is the leak ratio: IDs handed out divided by rows kept. A normal append-only table sits near 1. Here's what high ratios look like (both illustrative):

  • A device_settings table upserted on every app open: 40 million rows, around 54 upserts per row on average, and 2.1 billion IDs spent.
  • A 200,000-row catalog reloaded hourly: 4.8 million IDs a day, out of integer range in about 447 days. The table never grows.

Runway, not percentage

A percentage is a position. You need a date.

runway_days = (type_max - current_counter) / counter_increase_per_day

Snapshot the counter (not the row count) daily and diff it. Then compare runway with lead time, the time the fix really takes:

  • PostgreSQL: ALTER COLUMN ... TYPE bigint rewrites the table under an ACCESS EXCLUSIVE lock. On a busy table, even waiting for that lock blocks everything queued behind it. See the migration lock queue.
  • MySQL: changing a column's type, even INT to INT UNSIGNED, can't run INPLACE or INSTANT; it rebuilds the table.
  • The online route (new column, trigger or batched backfill, swap) takes weeks once testing and every dependent system are included.

Rule of thumb: alert while runway is still at least twice the lead time. This is clock-driven debt, the kind hotspot-based tech debt reviews never see, because nobody is committing to the table that's about to fail.

The canonical cautionary tale: in November 2018, Basecamp 3 was read-only for almost five hours when its events table hit 2,147,483,647. The team had already been working on expanding that table. They misjudged how fast the headroom was going.

The copies: where 32 bits survive a BIGINT migration

Coffee Meets Bagel's engineers migrated primary keys to bigint, then watched inserts fail because foreign key columns in related tables were still integers. The type was never one column.

orders.id migrated to BIGINT in the centre, with arrows to six places still limited to 32 bits: foreign key columns, the sequence, API schemas, app code, installed clients, and downstream systems.

Checklist:

  1. Foreign keys (declared ones are queryable, below).
  2. Undeclared references: polymorphic *_id columns, audit logs, JSON payloads, queue messages, search documents.
  3. The sequence (PostgreSQL 10+ serial).
  4. API contracts: GraphQL's built-in Int is a signed 32-bit integer, and graphql-js rejects larger values. Protobuf int32 has the same ceiling.
  5. Application types: Java int, Go int32, C# int, typed DTOs.
  6. Clients you don't deploy: installed mobile app versions. DoorDash treated cross-platform client compatibility as its own workstream when moving to bigint IDs.
  7. Downstream: warehouse schemas, importers, analytics events.

Declared foreign keys pointing at a table, with their types:

SELECT c.conrelid::regclass                 AS child_table,
       a.attname                            AS child_column,
       format_type(a.atttypid, a.atttypmod) AS child_type
FROM pg_constraint c
JOIN pg_attribute a
  ON a.attrelid = c.conrelid AND a.attnum = ANY (c.conkey)
WHERE c.contype = 'f'
  AND c.confrelid = 'orders'::regclass;

If the runway is already short

1. Stop the burner. If the leak ratio is the cause, fixing it is the cheapest runway available. Ask whether the table needs a surrogate ID at all: device_settings has a natural key (device_id). Make it the primary key and upserts stop consuming a sequence.

2. PostgreSQL stopgap: go negative. Restarting the sequence at −2,147,483,648 buys roughly two billion more values. It also breaks every assumption that IDs are positive and increasing: validation, route constraints like [0-9]+, ORDER BY id DESC as "newest", and cursor pagination keyed on id, which will skip every new row. MySQL has no equivalent.

3. The real fix: BIGINT everywhere. Column, sequence and every copy. The cost is about four extra bytes per value in the table and each index holding it. Framework defaults moved years ago (Rails 5.1, Laravel 5.8's bigIncrements stubs, Django 3.2's BigAutoField for new projects), but tables created before those switches kept INT.

Prove it: the Skip-Ahead Test

In a staging environment running the real stack, jump the counter past the 32-bit limit:

-- PostgreSQL
SELECT setval('orders_id_seq', 2147483700);

-- MySQL
ALTER TABLE orders AUTO_INCREMENT = 2147483700;

Then exercise real flows: API create, GraphQL reads, a current mobile build, background jobs, exports, the warehouse load. Every remaining 32-bit copy fails now, together, in staging. If the column or sequence itself is still 32-bit, the test fails at the first step, which is a preview of the outage on a day you chose.

The Runway Check: read the counter not the table, measure burn not growth, find the leak ratio, hunt the copies, alarm on runway then skip ahead.

Key Takeaways

  • Integer primary keys overflow on IDs handed out, not rows stored. COUNT(*) is the wrong metric.
  • Upserts, ignored inserts, rollbacks, retries and delete-and-reload jobs all spend IDs without keeping rows. Track the leak ratio.
  • Measure against the column type. PostgreSQL sequences can be smaller or larger than the column they feed.
  • Plan with runway vs lead time, and alert while runway is at least twice the lead time.
  • A BIGINT migration isn't done until foreign keys, the sequence, API types, app code, clients and pipelines are too. The Skip-Ahead Test proves it.

FAQ

What happens when an INT primary key reaches its maximum value?

Inserts fail. PostgreSQL raises nextval: reached maximum value of sequence once the sequence hits 2,147,483,647 (or integer out of range if the sequence is bigger than the column). MySQL fails the next attempt to generate a value, typically with a duplicate-key or "failed to read auto-increment value" error. Reads keep working, which is why outages like Basecamp's look like "read-only mode".

How do I check how close my auto-increment IDs are to overflowing?

Compare the current counter value with the maximum of the column's type, not the row count and not only the sequence's own maximum. The PostgreSQL and MySQL queries at the top of this article do exactly that. On MySQL 8.0+, set information_schema_stats_expiry = 0 first or you may read a value up to a day old.

Why do IDs run out faster than the number of rows?

Sequences never return numbers. Upserts that update, inserts ignored as duplicates, rolled-back transactions, retries and delete-and-reload jobs all consume IDs without leaving a row. A table can hold 2% of the limit in rows while its counter sits at 99%.

Does changing a column to BIGINT also fix the sequence in PostgreSQL?

Not for serial columns created on PostgreSQL 10 or later. Their sequence is declared AS integer and keeps its 2,147,483,647 maximum after the column changes. Run ALTER SEQUENCE <name> AS bigint as part of the same migration and confirm with \d <sequence>.

How long does an INT to BIGINT migration take?

The SQL can take minutes to hours, but a direct ALTER rewrites the table under a blocking lock, so large production tables usually go the online route: add a bigint column, keep it in sync, backfill in batches, swap. Counting foreign keys, APIs, clients and pipelines, plan in weeks, and start while runway is at least twice that.

Should new tables use BIGINT or UUID primary keys?

Either avoids the 32-bit trap. BIGINT keeps keys small and ordered and is the sensible minimum for any auto-incremented key; modern Rails, Laravel and Django defaults already use it. UUIDs remove the central counter and are useful across systems or in public URLs, at the cost of larger keys. For tables with a real natural key, such as one row per device, consider using that key and no counter at all.

Get one of these in your inbox each week: subscribe to Simply Explained on Substack.

The bottom line

Two billion feels like forever because we picture two billion rows. Rows aren't what runs out. Numbers are, and they get spent by code nobody thinks of as writing.

Run the counter query this week. The table you're not worried about is the one to check.

Adam Jaber is a software engineer who writes Simply Explained: complex topics, made simple, with no jargon and no hype.

About the author

  • I'm a senior software engineer. I write Simply Explained, a plain-English breakdown of how AI and software actually work, and the quiet ways they break: AI fixes that hide bugs, agents that pick the wrong tool, health checks that take down healthy servers. One symptom, one analogy, one fix per piece. New here? Start with the pinned Start Here guide, or get one breakdown a week by email.

No comments yet. Be the first to comment.

The Systems Behind the Software

Part 1 of 23

Plain-English deep dives into the backend and system-design ideas that quietly run everything — caching, idempotency, databases, distributed systems, and the subtle bugs the obvious approach never prevents. No jargon, no hype. Each piece starts with a real production problem, builds the intuition, then shows how to actually get it right.

Up nextWebhooks Arrive Late, Twice, Out of Order, or Never. Design for All Four.The doorbell pattern: treat each event as a pointer, fetch current state, guard the write, and reconcile on a schedule.

More from this blog