Surrogate Keys in a Lakehouse: Identity, Hashes or Sequences
Identity columns, hash keys and ROW_NUMBER sequences all produce surrogate keys on Delta Lake. They differ on concurrency, collisions, reproducibility and join cost. Here's how to choose.
TL;DR
- A surrogate key is a warehouse-owned key that's independent of the source system's ID. You need one for Type 2 dimensions, multi-source entities and "unknown" members.
- Identity columns (
GENERATED BY DEFAULT AS IDENTITY) give compactBIGINTkeys with no collision risk, but the table can't take concurrent writes. - Hash keys (
xxhash64,sha2) are deterministic, so any job can compute them in parallel and get the same answer. 64-bit hashes have a real collision risk past a few hundred million keys; 256-bit hashes don't, but they're wide strings. - ROW_NUMBER + max(key) sequences work for a single batch writer and break the moment two jobs overlap.
- Never use
monotonically_increasing_id()as a persistent key.
The problem
NorthBridge's first gold layer used monotonically_increasing_id() to key the product dimension. It looked fine: unique numbers, generated in Spark, no extra infrastructure.
Then someone rebuilt the dimension after a schema change. The same products came back with completely different IDs, because the function's values depend on partition layout, not on the data. Eighteen months of fact_sales rows now pointed at the wrong products. Nobody noticed for two days, because the joins still worked. They just joined to the wrong rows.
Surrogate keys are the glue in a dimensional model. If they aren't stable, nothing above them is trustworthy.
Key concepts
| Concept | What it means | Why it matters here |
|---|---|---|
| Natural (business) key | The source's identifier, like SKU-88412 |
Can be reused, reformatted or clash across systems |
| Surrogate key | A key the warehouse generates and owns | Isolates the model from source quirks; one per SCD2 version |
| Deterministic key | Same input always gives the same key | Rebuilds and parallel jobs produce matching keys |
| Collision | Two different inputs producing the same hash | Silent corruption: two products merged into one |
| Unknown member | A reserved row such as -1 = Unknown |
Keeps fact foreign keys NOT NULL |
Three ways to make a key. The trade-off is mostly concurrency against size and collision risk.
Step-by-step implementation
Option 1 — Identity columns
-- Databricks Runtime 16.4 LTS
CREATE TABLE IF NOT EXISTS northbridge.gold.dim_store (
store_key BIGINT GENERATED BY DEFAULT AS IDENTITY (START WITH 1 INCREMENT BY 1),
store_id STRING NOT NULL,
store_name STRING,
region STRING,
opened_on DATE
);
-- BY DEFAULT lets you reserve explicit keys for special members
INSERT INTO northbridge.gold.dim_store (store_key, store_id, store_name, region)
VALUES (-1, 'UNKNOWN', 'Unknown store', 'Unknown'),
(-2, 'N/A', 'Online / not applicable', 'Online');
-- Normal loads omit the column and get generated values
INSERT INTO northbridge.gold.dim_store (store_id, store_name, region, opened_on)
SELECT store_id, store_name, region, opened_on FROM northbridge.silver.store;Delta guarantees identity values are unique and increase in the direction of the increment. It does not guarantee they're consecutive. Expect gaps, especially after failed or parallel tasks. If anyone builds logic around "key 1000 is the 1000th product", stop them early.
Choose BY DEFAULT over ALWAYS for dimensions. ALWAYS refuses explicit values, which makes reserving -1 and -2 awkward and makes migrating existing keys from an old warehouse impossible. If you do insert explicit positive values, run ALTER TABLE ... ALTER COLUMN store_key SYNC IDENTITY afterwards so the generator doesn't hand out a key you already used.
Two limits to know before choosing this. You can only define an identity column when you create the table, not add one later with ALTER TABLE. And declaring an identity column turns off concurrent write transactions on that table. One writer at a time.
For most dimensions that last limit doesn't matter. Dimensions are usually loaded by one task in one job. It matters a lot for anything written by several streams.
Option 2 — Hash keys
SELECT
xxhash64('POS', upper(trim(product_id))) AS product_key, -- BIGINT
sha2(concat_ws('|', 'POS', upper(trim(product_id))), 256) AS product_hk, -- STRING(64)
product_id, product_name, category
FROM northbridge.silver.product;A hash key is a pure function of the business key. Rebuild the table from scratch and every product gets the same key back. Two jobs loading two different sources at the same time can't conflict, because neither needs to ask the other what the next key is. This is why Data Vault relies on hash keys.
Normalise before hashing. ' sku-88412' and 'SKU-88412' are the same product to a human and different hashes to Spark. Include a source system code too, so that customer 1042 from the POS system and customer 1042 from the e-commerce platform don't collide by design.
Now the part people skip: collision maths. For a 64-bit hash like xxhash64, the chance of at least one collision among n keys is roughly n² / 2⁶⁵.
| Distinct keys | Approx. chance of any collision (64-bit) |
|---|---|
| 1 million | 0.000003% |
| 100 million | 0.03% |
| 1 billion | 2.7% |
| 4 billion | ~35% |
A product or store dimension will never get near the danger zone. A clickstream session dimension or a device dimension for IoT might. For anything that could reach hundreds of millions of distinct keys, use sha2(..., 256) and accept that a 64-character string key makes joins and storage heavier than a BIGINT.
One more limit: for a Type 2 dimension, hashing the natural key alone gives every version the same key, which is wrong. You'd hash natural_key + valid_from instead. That means the fact load still has to look up which version was valid at the event time, so the "no lookup needed" advantage of hash keys only fully applies to Type 1 dimensions.
Option 3 — ROW_NUMBER sequences
INSERT INTO northbridge.gold.dim_promotion
SELECT
(SELECT coalesce(max(promotion_key), 0) FROM northbridge.gold.dim_promotion)
+ ROW_NUMBER() OVER (ORDER BY s.promotion_id) AS promotion_key,
s.promotion_id, s.promotion_name, s.start_date, s.end_date
FROM northbridge.silver.promotion s
LEFT ANTI JOIN northbridge.gold.dim_promotion d
ON s.promotion_id = d.promotion_id;This is how people generated keys before identity columns existed in Delta, and you'll still see it in older code. It produces contiguous, compact keys. The catch is the race: if two jobs read max(promotion_key) at the same time, they generate the same keys. Nothing in Delta stops that, because the two inserts don't conflict at the file level. Use it only when one scheduled job owns the table and you'd rather have no gaps than use an identity column. Otherwise, use an identity column.
What not to do
# Don't persist this. Values depend on partitioning and change between runs.
df.withColumn("product_key", F.monotonically_increasing_id())monotonically_increasing_id() is fine for a temporary row number inside one job. As a stored key it's the bug from "The problem".
From production: gotchas and lessons
-
Symptom: Two different products started showing combined sales in the category report. Cause: A 32-bit
hash()used as the key on a dimension with 40 million SKU-store combinations. At that size, collisions are practically guaranteed. Fix: Switched toxxhash64with a source prefix, added a uniqueness test on the key that fails the job, and backfilled. Spark'shash()returns a 32-bitINT; it's built for partitioning, not identity. -
Symptom: A streaming job and a nightly batch job both writing
dim_devicekept failing with concurrent modification errors. Cause: The table had an identity column. Fix: Moveddim_deviceto hash keys. The two writers became independent, and the failures stopped. -
Symptom: After a warehouse migration, the new dimension's identity keys collided with keys copied from the old system. Cause: Old keys were inserted explicitly, but the identity high-water mark wasn't moved. Fix:
ALTER TABLE ... ALTER COLUMN product_key SYNC IDENTITYafter the migration insert. Add it to the migration runbook. -
Symptom: Fact rows with hash keys that didn't exist in the dimension. Cause: The fact load hashed
product_idas-is; the dimension hashedupper(trim(product_id)). Fix: One shared SQL function,northbridge.util.product_hk(product_id), used by every job. Hash logic copied into two places will drift.
Performance and cost notes
A BIGINT join key is 8 bytes. A sha2 hex string is 64. On a fact table with five foreign keys and two billion rows, that difference shows up in storage, shuffle size and join speed. Use BIGINT keys (identity or xxhash64) wherever the collision risk is acceptable, and keep 256-bit hashes for very high-cardinality or regulated entities where you need the guarantee.
When not to use this
Not every table needs a surrogate key. Raw and silver tables are fine with natural keys. Date dimensions work well with readable yyyymmdd integers. Surrogate keys earn their keep in gold dimensions, especially Type 2 ones and ones fed by multiple sources.
Frequently asked questions
Are Delta identity columns guaranteed to be sequential? No. They're unique and increasing, but there can be gaps.
xxhash64 or sha2 for surrogate keys?
xxhash64 for compact keys on dimensions well under a few hundred million distinct values. sha2 with 256 bits when collisions must be practically impossible.
Can I add an identity column to an existing Delta table? No. Create a new table with the identity column and insert the data into it.
Checklist
- Every gold dimension has reserved unknown (
-1) and not-applicable (-2) members - Identity tables have exactly one writer
- Hash inputs normalised and prefixed with a source code, via one shared function
- Hash width chosen from the expected distinct-key count, not habit
- A uniqueness test on every surrogate key runs after every load
- No
monotonically_increasing_id()or 32-bithash()in persisted keys
Practice
- Try: Data Modeling Interview Questions: 20 Design Problems
- Build it yourself: generate 50 million random strings, hash them with
hash()andxxhash64(), and count duplicates for each. The difference makes the collision table above very concrete.
Further reading
Keep going
Star Schema in the Lakehouse: Facts, Dimensions and Grain
Delta tables didn't make dimensional modeling obsolete. Here's how to pick the grain, split facts from dimensions, and build a star schema on Databricks that analysts can trust.
SCD Type 2 with Delta MERGE: One Atomic Statement, SQL and PySpark
Expire the old version and insert the new one in a single Delta MERGE. The staged-union pattern, a PySpark version, the tests that catch broken history, and when to hand it to AUTO CDC.
Kimball vs Data Vault vs One Big Table: How to Choose
Three modeling styles, three different problems they solve. A decision framework based on source count, audit needs, team size and consumers, plus the hybrid most lakehouses end up with.
One practical note a week
Get new articles, problems and guides in your inbox.
Thanks! You're on the list. (Local demo — no email provider is wired up yet.)