Scrivio Interview library
DesignAdvanced7 min read · updated 12 November 2026

You are merging two companies' order databases that both use bigint sequences starting at 1, and planning a move to multiple active regions. What identifier strategy would you choose for new systems and how would you migrate the existing keys?

For new systems that will write in several regions, I would use identifiers that need no coordination: time-ordered UUIDv7 values, or Snowflake-style 64-bit ids if storage size matters and we can manage node numbers. For the merge, I would keep each company's old ids and either make the key composite with a source column or remap one side through a mapping table that preserves the old ids for external references. Customer-facing numbers should be separate from internal keys, and we must test index size, insert speed and every system that assumes numeric ids.

Why this question is asked

Two bigint sequences that both start at 1 are fine until two databases have to become one. Then order 1001 exists twice, and every foreign key, report and integration that uses it becomes ambiguous. Add a plan to write in several regions at once, and a single sequence is no longer enough even for new data, because two regions cannot share one counter without a network round trip on every insert. Interviewers ask this at senior level because the answer touches storage internals, data migration and organisation-wide contracts. In this answer, we will compare the identifier options, see what each one costs in bytes and index behaviour, design the merge of the existing keys, and finish with how we would roll this out safely.

1Why Plain Sequences Stop Working

A sequence guarantees uniqueness only inside one database. Company A's orders table and company B's orders table both contain ids 1 to 40 million, so a simple union produces 40 million collisions. With several active regions, each region could have its own sequence, but then the regions collide in the same way unless we split the number space between them.

So we need ids that are unique across sources and regions without a central counter. There are three common families: random or time-ordered UUIDs, sequence ranges reserved per region, and Snowflake-style ids that pack a timestamp, a node number and a counter into 64 bits.

2Comparing the Options

A UUID is a 128-bit value, written as 36 characters of hex text but stored in PostgreSQL's uuid type as 16 bytes. Version 4 is entirely random. Version 7 starts with a 48-bit millisecond timestamp followed by random bits, so values created later sort later. Neither needs any coordination: any service in any region can create one.

The difference between them shows up in indexes. A B-tree index keeps keys in order, so random v4 keys land on random leaf pages and every insert touches a page that may not be in memory. UUIDv7 keys arrive roughly in order and go to the rightmost pages, which stay cached, much like a sequence. Snowflake-style ids keep the bigint size, 8 bytes, but require that every generator has a unique node number and a sane clock. Sequence ranges per region, for example region 1 starts at 1 and region 2 at 10 to the power 15, or interleaved increments, are simple but must be planned for every new region.

Identifier options for multi-region writes
OptionSizeCoordinationIndex localityRisks
bigint sequence8 bytesone counter per databaseexcellentcollides across sources
sequence range per region8 bytesplan ranges up frontgood within a regionrange exhaustion, new regions
UUIDv416 bytesnonepoor, random pageslarge, slow inserts at scale
UUIDv716 bytesnonegood, time-orderedreveals creation time
Snowflake-style8 bytesunique node idsgood, time-orderedclock drift, node registry
For a new multi-region system, UUIDv7 is usually the simplest safe default.

3What I Would Choose for New Systems

For the new systems I would choose UUIDv7. It needs no registry of node numbers and no range planning, so a new region or a new service can start generating ids on day one. Its time ordering keeps insert performance close to a sequence. The cost is size: 16 bytes instead of 8 in the primary key and in every foreign key and secondary index that refers to it. For an orders table with five indexes and a few referencing tables, that might add a few gigabytes per hundred million rows, which is usually acceptable. If a profile shows that the extra size matters, for example in a very large event table, a Snowflake-style 64-bit id is the alternative, at the price of operating the node registry.

A UUIDv7 also reveals roughly when the record was created. For internal keys this is harmless, but it is one more reason to keep keys away from customers, as we will see.

Java
// Java: generate in the service so the id exists before the insert (useful for events and outbox rows)
UUID id = UuidCreator.getTimeOrderedEpoch(); // a UUIDv7 from a library such as uuid-creator
// PostgreSQL 18 and later (check your version) can also generate it:
// CREATE TABLE orders (id uuid PRIMARY KEY DEFAULT uuidv7(), ...);

4Migrating the Existing Keys

For the merge itself there are two sound approaches. The first keeps every old id and makes the source part of the key: the merged table has (source, legacy_id) as a unique pair, for example ('A', 1001) and ('B', 1001), and new rows get a UUIDv7 id. Old foreign keys are migrated as pairs. This is the least risky, because no existing number changes, but every query and join must carry the source column.

The second gives every merged row a new key and keeps a mapping table from (source, old_id) to new_id. Child tables are rewritten through the mapping in the migration, and the old ids stay in a legacy column so external systems, emails and support tickets that mention order 1001 of company B can still be resolved. This produces a clean schema, at the cost of a bigger migration that must be rehearsed on a copy of production. I would usually remap the smaller company into the new scheme and keep its old ids in the mapping table for years.

SQL
CREATE TABLE order_id_map (source text, old_id bigint, new_id uuid NOT NULL,
PRIMARY KEY (source, old_id));
INSERT INTO order_id_map SELECT 'B', id, uuidv7() FROM b.orders; -- one row per old order
INSERT INTO orders (id, legacy_source, legacy_id, total)
SELECT m.new_id, 'B', o.id, o.total FROM b.orders o
JOIN order_id_map m ON m.source = 'B' AND m.old_id = o.id; -- children are rewritten the same way
Step throughRemapping one company's keys
  1. Freeze or dual-write Bstop new ids appearing during the copy
  2. Build order_id_map(source, old_id) -> new_id
  3. Copy parents with new idskeep legacy_source and legacy_id
  4. Rewrite child foreign keysjoin through the map
  5. Verify counts and sumsper table, per source
  6. Switch readers and writersold ids resolved via the map

6 steps in order. Play them, or step through them one at a time.

5Separate External Identifiers and Test the Change

Customers, partners and support staff should see a business identifier, such as ORD-7K4P-2026, not the internal primary key. Then the internal key can change from bigint to UUID during a merge like this one without changing anything a customer has written down, and the external format can change without touching foreign keys. The external id is its own column with a unique index.

Before rolling out, we measure. We load a realistic volume into a test database and compare index sizes, insert throughput and buffer cache hit ratios for bigint, UUIDv7 and, as a warning, UUIDv4. Then we search every consumer for numeric assumptions: Java fields typed as long, JSON schemas with integer ids, analytics jobs, caches keyed by number and URL patterns that only accept digits. These are where migrations usually break, not in the database.

6Follow-up questions

Where would you generate UUIDv7 values, in Java or in the database?

I prefer generating them in the application. The service then knows the id before the insert, so it can write the row, an outbox event and a log entry with the same id in one go, and Hibernate can batch the inserts because no database round trip is needed for the key. A database default such as uuidv7() in PostgreSQL 18 is useful as a fallback for scripts and other writers. Either way, the clocks should be synchronised; UUIDv7 tolerates small drift because the random part keeps values unique.

Why not keep bigint and give each region its own range?

It works and keeps keys small, but someone must plan and record the ranges, every new region needs a decision, and a mistake causes silent collisions that only appear later. For a company that expects to add regions and services over years, removing that coordination is usually worth 8 extra bytes per key.

Is UUIDv4 really a problem?

At small scale, no. Once the index is larger than memory, random inserts touch random pages, cause page splits and leave pages half full, so inserts slow down and indexes grow. Time-ordered values avoid this, which is why v7 is the better default for primary keys.

7Conclusion

In this answer, we saw that sequences guarantee uniqueness only inside one database, so merging and multi-region writes need ids that require no coordination. UUIDv7 gives that with good index locality at 16 bytes, while Snowflake-style ids stay at 8 bytes but need node management. For the merge we either keep old ids with a source column or remap one side through a mapping table that preserves old ids for external references. Customer-facing identifiers stay separate, and we test index size, insert speed and every consumer's assumptions before switching.

What to say in the interviewAbout 90 seconds aloud

Open with

I would separate the decision into new ids and the existing ids. For new systems in several active regions I want ids that need no coordination, so a plain sequence is out.

Then, if they want more

My default would be UUIDv7: any service in any region can generate it, and because it starts with a millisecond timestamp, inserts go to the right edge of the B-tree like a sequence, unlike random UUIDv4 which scatters inserts across pages once the index is bigger than memory.

The cost is 16 bytes instead of 8 in every key and foreign key, which I would measure; if it really mattered I would consider Snowflake-style 64-bit ids, accepting that we must run a node registry and watch clocks. I would generate the ids in the service so they exist before the insert.

For the merge, both companies have ids starting at 1, so I either keep the old ids with a source column as part of a composite key, or, cleaner, remap the smaller company: build a mapping table from source and old id to new id, rewrite child foreign keys through it, verify counts and sums, and keep the old ids so external references still resolve.

I would also introduce a customer-facing order number that is separate from internal keys. Before rollout I would load-test index size and insert speed and audit every consumer that assumes numeric ids, because that is where migrations usually fail.

About this answer

Last updated
12 November 2026
Versions it names
PostgreSQL 18
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "You are merging two companies' order databases that both use bigint sequences starting...": https://scrivio-interview-library.netlify.app/databases/stored-code/69358baea5/