Home / Databases / MySQL

DatabasesRunbookAdvanced

Sev1: MySQL inserts fail with duplicate entry 2147483647. AUTO_INCREMENT reached the INT maximum

Every insert into a busy table fails because its AUTO_INCREMENT key hit the column type's maximum. Stop the outage with a table swap or a BIGINT migration, and find the other tables that are close.

Deepak Bhardwaj6 min read

Applies toMySQL 8.0 and 8.4 LTS (InnoDB), Amazon RDS / Aurora MySQL, Azure Database for MySQL Flexible Server

Symptoms

  • All inserts into one table fail at the same time with an error such as ERROR 1062 (23000): Duplicate entry '2147483647' for key 'orders.PRIMARY'.
  • The number in the error is a type maximum: 2147483647 (signed INT), 4294967295 (INT UNSIGNED), 8388607 (signed MEDIUMINT) and so on.
  • Some versions and code paths report ERROR 1467 (HY000): Failed to read auto-increment value from storage engine instead.
  • Updates and reads on the table still work. Only new rows fail.

1. Confirm scope and impact

Check the column type and the current counter:

SHOW CREATE TABLE app.orders\G
SELECT MAX(id) FROM app.orders;

If MAX(id) equals the type maximum, you have confirmed the problem. Then find every other table that is close, because the same pattern often affects child or audit tables too. In MySQL 8.0 and later, information_schema.TABLES values are cached, so turn off the cache for your session first:

SET SESSION information_schema_stats_expiry = 0;

SELECT t.table_schema, t.table_name, c.column_name, c.column_type, t.auto_increment,
       ROUND(100 * t.auto_increment /
         CASE c.data_type
           WHEN 'tinyint'   THEN IF(c.column_type LIKE '%unsigned%', 255, 127)
           WHEN 'smallint'  THEN IF(c.column_type LIKE '%unsigned%', 65535, 32767)
           WHEN 'mediumint' THEN IF(c.column_type LIKE '%unsigned%', 16777215, 8388607)
           WHEN 'int'       THEN IF(c.column_type LIKE '%unsigned%', 4294967295, 2147483647)
           WHEN 'bigint'    THEN IF(c.column_type LIKE '%unsigned%', 18446744073709551615, 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
WHERE c.extra LIKE '%auto_increment%'
  AND t.table_schema NOT IN ('mysql', 'sys', 'performance_schema', 'information_schema')
ORDER BY pct_used DESC
LIMIT 20;

If the sys schema is installed, sys.schema_auto_increment_columns returns the same information.

2. Pick the mitigation

Table profile Fastest safe option Time to restore inserts
Append-only log, event or queue table, old rows rarely read Swap in a new empty table with a BIGINT key (step 3a) Seconds
Small table (a few GB) ALTER TABLE ... MODIFY to BIGINT (step 3b) Minutes, writes blocked meanwhile
Large OLTP table that must keep all rows Online migration with gh-ost or pt-online-schema-change (step 3c) Hours. Inserts stay down unless you add a workaround
Signed INT and no negative IDs Changing to INT UNSIGNED doubles the range, but it is still a rebuild Same as 3b or 3c

You cannot set AUTO_INCREMENT to a lower value than MAX(id), and InnoDB does not reuse gaps. Changing the counter alone does not help.

3. Restore inserts

3a. Table swap for log-style tables

Create an empty copy with a wider key. Start its counter above the old maximum so IDs stay unique across both tables, then swap the tables atomically:

CREATE TABLE app.events_new LIKE app.events;
ALTER TABLE app.events_new MODIFY id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
                           AUTO_INCREMENT = 2147483648;
RENAME TABLE app.events TO app.events_old, app.events_new TO app.events;

RENAME TABLE waits for a metadata lock, so long-running transactions on the table delay it. Check SHOW PROCESSLIST first. Afterwards, copy any rows you still need, in batches, or point reporting at events_old.

Warning

A table swap breaks foreign keys from other tables that point at events (they follow the renamed table), and it breaks triggers and grants that are defined per table. Check information_schema.REFERENTIAL_CONSTRAINTS before you swap. If any foreign keys reference the table, use 3b or 3c instead.

3b. In-place type change for small tables

ALTER TABLE app.orders
  MODIFY id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  ALGORITHM = COPY, LOCK = SHARED;

Changing a column's data type rebuilds the table with the COPY algorithm. Reads work, but writes are blocked until the rebuild finishes. Allow free disk space of at least the table size. On a replica setup, the rebuild replays on every replica and causes replication lag.

Columns in other tables that reference orders.id through a foreign key must change to the same type. MySQL rejects the change if the types become incompatible. List them first:

SELECT table_name, column_name, constraint_name
FROM information_schema.KEY_COLUMN_USAGE
WHERE referenced_table_schema = 'app' AND referenced_table_name = 'orders';

3c. Online migration for large tables

gh-ost --host=db-primary --database=app --table=orders \
  --alter="MODIFY id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT" \
  --allow-on-master --chunk-size=2000 --max-load=Threads_running=50 --execute
pt-online-schema-change \
  --alter "MODIFY id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT" \
  D=app,t=orders --chunk-size=2000 --max-load Threads_running=50 --execute

Both tools copy rows into a shadow table while the original stays online, then swap the tables. Inserts into the original still fail until the swap, so tell the business how long the copy will take. Do a --dry-run first. gh-ost needs row-based binary logging and does not support tables that have foreign keys. pt-online-schema-change creates triggers and needs special handling for foreign keys (--alter-foreign-keys-method).

Caution

Do not take a backup, drop the table and reload it during the incident to "reset" the IDs. If the application or other tables store these IDs, reused values silently link new rows to old data.

4. Find why the counter ran out early

Counters often run out years before the row count would suggest. Compare the row count with MAX(id):

SELECT COUNT(*) AS row_count, MAX(id) AS max_id FROM app.orders;
SHOW VARIABLES WHERE Variable_name IN
  ('auto_increment_increment', 'auto_increment_offset', 'innodb_autoinc_lock_mode');
Cause Sign
INSERT ... ON DUPLICATE KEY UPDATE, INSERT IGNORE or REPLACE used for upserts Each attempt can use up an ID even when no row is inserted
Rolled-back transactions and failed batch inserts Large gaps in the ID sequence
auto_increment_increment > 1 (multi-primary or Group Replication) IDs advance in steps of the increment
Bulk inserts with innodb_autoinc_lock_mode = 2 IDs are reserved in blocks, leaving gaps

5. Verify recovery

  • Insert a test row, or watch application inserts succeed, and check the new ID is above the old maximum.
  • Run the capacity query again and confirm pct_used for the fixed table is near 0%.
  • Check replicas are in sync: SHOW REPLICA STATUS\G should show no SQL thread error and Seconds_Behind_Source falling.
  • Confirm the application handles 64-bit IDs. JavaScript clients lose precision above 2^53, and some ORMs map INT to a 32-bit type.

Communicate

Tell users that new records could not be created between the first and last error times, and that existing data was not affected. Ask owners of queues and batch jobs to replay the inserts that failed.

Prevent it next time

  • Use BIGINT UNSIGNED for every new AUTO_INCREMENT key. Add a schema linter rule that blocks INT keys.
  • Run the capacity query weekly and alert at 70% used, which gives you time for an online migration.
  • Replace high-volume INSERT IGNORE and ON DUPLICATE KEY upserts on hot tables with a read-then-write pattern, or accept the gaps and size the key accordingly.
  • If you also run PostgreSQL, check it too: sequences behind integer keys run out the same way (PostgreSQL sequence exhausted).