PostgreSQL ERROR: index row size exceeds btree version 4 maximum 2704 means a single value, or combination of values, is too large to be stored as one B-tree index entry. The insert, update or index build that produced it is rolled back, and it will keep failing for that row until the index or the data changes.
ERROR: index row size 3048 exceeds btree version 4 maximum 2704 for index "pages_url_key"
DETAIL: Index row references tuple (88120,3) in relation "pages".
HINT: Values larger than 1/3 of a buffer page cannot be indexed.
Consider a function index of an MD5 hash of the value, or use full text indexing.
Every part of the message is useful. 3048 is the size of the entry PostgreSQL tried to write, 2704 is the limit, the index name tells you which index to rethink, and DETAIL gives the physical address (ctid) of the offending row. The error is raised in _bt_check_third_page() with SQLSTATE 54000, program_limit_exceeded: it is a hard limit, not a configuration setting.
Where 2704 comes from
A B-tree page must be able to hold at least three entries, so nbtree.h caps one entry at a third of the usable space on a page. With the standard 8KB page that is 2712 bytes. Version 4 B-trees, the format used for indexes built since PostgreSQL 12, reserve another 8 bytes for a heap TID that can be added to an entry as a tiebreaker, which gives 2704.
You may still see btree version 3 maximum 2712. That is an index carried over by pg_upgrade from a release before 12, still in the old format. The PostgreSQL 12 release notes warn about exactly this: the maximum entry length dropped by eight bytes, so a REINDEX of an upgraded index can fail. If you plan to rebuild old indexes after an upgrade, check them first; our major version upgrade guide covers the rest of that process. bt_metap() from pageinspect shows the version of each index.
Why it appears years after the index was created
The limit applies to the stored entry, not to the declared column type. A text column has no length limit, so the index works for every row until the first value that does not fit. Two details make this hard to predict:
- Index entries can be compressed. In
index_form_tuple(), a variable-length value above a size target is compressed in line if the column's storage mode allows it. Long but repetitive text can therefore index fine, while a shorter value that does not compress, such as a random token, Base64 or an already compressed payload, fails. - TOAST does not help. Large values are stored out of line in the table, but B-tree entries cannot point to out-of-line storage. The source comment says so directly: it would break suffix truncation and amcheck.
In our experience the usual victims are unique constraints on URLs, file paths, email bodies or API payloads, and composite indexes where several medium-length text columns add up. Non-key columns count as well: the CREATE INDEX documentation warns that wide INCLUDE columns can push an entry over the limit, and then data insertion fails.
Find the row
For a failed insert or update, the value is in the application's request. For a failed index build, use the ctid from DETAIL, then look for other long values before you try again, because the build stops at the first one.
-- candidates: long values in the indexed column (full scan: run it on a replica)
SELECT ctid, id,
octet_length(url) AS raw_bytes,
pg_column_size(url) AS stored_bytes
FROM pages
WHERE octet_length(url) > 2000
ORDER BY raw_bytes DESC
LIMIT 20;
-- the exact row from DETAIL
SELECT id, left(url, 80) FROM pages WHERE ctid = '(88120,3)';
octet_length() is the uncompressed size in bytes; pg_column_size() shows how much the value takes in the table after compression. Neither is exactly the index entry size, so treat 2000 bytes as a margin, not a precise threshold.
Pick the right replacement
The fix depends on what the index is for. Ask that first, because the B-tree on the full value is often doing more than the application needs.
- Uniqueness. Index a hash of the value, as the error's own hint suggests. The entry is a 32-character MD5 hex string, whatever the input length.
Keep the-- uniqueness on a hash of the value instead of the value itself CREATE UNIQUE INDEX CONCURRENTLY pages_url_md5_key ON pages (md5(url)); -- queries must use the same expression to hit the index SELECT id FROM pages WHERE md5(url) = md5($1) AND url = $1;url = $1condition so that the rare hash match on a different value is filtered out. Two different values with the same MD5 would be rejected as duplicates; accidental collisions are not a practical concern, but if users can craft input on purpose, weigh that. - Equality lookups only. Hash indexes store a 32-bit hash code, so value length does not matter, and the planner uses them for
=. They do not support ranges or sorting, and only B-tree indexes can be declared unique.-- equality lookups only, no uniqueness CREATE INDEX CONCURRENTLY pages_url_hash ON pages USING hash (url); - Prefix searches and sorting. Index the first few hundred characters. Five hundred characters stay under 2000 bytes even in UTF-8 with four-byte characters.
-- an index on the first characters, rechecked against the full value CREATE INDEX CONCURRENTLY pages_url_prefix ON pages (left(url, 500)); SELECT id FROM pages WHERE left(url, 500) = left($1, 500) AND url = $1; - Searching inside documents. Use full text search with a GIN index, the other option the hint mentions, instead of a B-tree on the raw text.
- No real use. If the index exists only because someone indexed every column, drop it.
Whichever you choose, consider a CHECK on the length if the business rules allow it. NOT VALID followed by VALIDATE adds it without holding a long lock on the table.
-- stop new oversized values at the door, without a long lock
ALTER TABLE pages ADD CONSTRAINT pages_url_len
CHECK (octet_length(url) <= 2000) NOT VALID;
ALTER TABLE pages VALIDATE CONSTRAINT pages_url_len;
Larger pages are not the answer. The page size is fixed when PostgreSQL is compiled, so a bigger limit means a custom build and a full dump and reload. Changing the index is always cheaper.
On large tables
On a big, busy table the error usually shows up in the middle of a migration, and the cleanup matters as much as the fix.
- Scan before you build.
CREATE INDEXreads the whole table and fails on the first oversized entry, which can be late in a long build. Run the length query on a replica first and deal with the outliers. - Failed concurrent builds leave debris. If
CREATE INDEX CONCURRENTLYfails, the documentation notes that it leaves anINVALIDindex that is ignored for queries but still adds write overhead. Find and drop it before the next attempt; the same applies to REINDEX CONCURRENTLY.
-- leftovers from failed concurrent builds
SELECT indexrelid::regclass AS index_name, indrelid::regclass AS table_name
FROM pg_index
WHERE NOT indisvalid;
DROP INDEX CONCURRENTLY pages_url_md5_key;
- Swap constraints in two steps. Build the new MD5 unique index concurrently, switch the application queries to the new expression, and only then drop the old constraint. If foreign keys reference the old unique constraint, they have to be recreated against a key that can be unique, which may mean adding a surrogate key first.
- Expression indexes cost CPU on every write. PostgreSQL computes
md5(url)for each insert and update of the column. In our experience that is negligible next to the I/O saved by a much smaller index, but measure it on write-heavy tables. - Replicas and WAL. An index build on the primary generates WAL for the whole new index, and replicas have to replay it. On very large tables schedule the build when replica lag has room to grow.
- Upgrades. After
pg_upgradefrom a release before 12, rebuild old version 3 indexes deliberately, one at a time, rather than with a database-wideREINDEXthat stops at the first failure.
Key takeaways
- A B-tree entry must fit in a third of a page: 2704 bytes for version 4 indexes on 8KB pages, 2712 for older formats.
- The failure depends on the data: compressible values may fit, random or pre-compressed ones may not, and TOAST is never used for index entries.
DETAILgives the row'sctid; scan for other long values before rebuilding.- Use a unique index on
md5(col)for uniqueness, a hash index for equality, aleft()index for prefixes, full text for search. - On large tables pre-scan on a replica, clean up
INVALIDindexes, and rebuild upgraded version 3 indexes one by one.