NewsCrawler.org

Migrating primary keys of about 200 production tables from integer IDs to UUIDv7

本番DBの約200テーブルの主キーを整数からUUIDv7に移行した話(マルチテナント化連載 第5回・UUID移行編)
Image: zenn.dev

The author, shim, a tech lead at Counterworks, describes changing the primary keys of about 200 tables in the production database of the SCE system, a B2B SaaS for commercial facilities, from BIGINT to UUIDv7[1]. The change was needed for tenant consolidation, because the separate databases of client companies all use the same integer IDs, which would collide once merged. UUIDs stay unique across environments, and the author chose v7 over v4 because its timestamp prefix keeps index inserts near the end and sorts rows by creation time.

The work was staged: a new_id UUID column was added to every table and filled with UUIDv7 values, an old_id backup column was kept, and the primary key was then switched in one migration by copying new_id into id. The views, foreign keys and Row Level Security[2] policies were removed for that switch, and the migration runs as one transaction thanks to PostgreSQL transactional DDL[3]. The new IDs take their timestamp from each record's created_at, so sorting by id matches creation order.

PostgreSQL has no built-in UUIDv7 function, so the author wrote custom_gen_random_uuid_v7, while the application side uses SecureRandom.uuid_v7 from Ruby 3.3. Releases were made during planned maintenance windows, when users were stopped in each client environment, and the text also covers a three-stage release procedure and an assign_sequential_id method for restoring sequential order.

Read the original zenn.dev

Sources

  • Zenn JA

    本番DBの約200テーブルの主キーを整数からUUIDv7に移行した話(マルチテナント化連載 第5回・UUID移行編)

    7 likes1 bookmark0 comments

Published: First seen: Читать по-русски

Open as a page