Skip to content
Tech Interview Prep
Technical interview guide

Data Modeling Standards

Organization-wide conventions for naming, structuring, and typing data so it's consistent across every pipeline and team.

Minutes to read
4
Practice MCQs
25
Interview Q&A
25
Edition
v5
Editorial status
Reviewed

Scope: PostgreSQL 18, W3C DCAT 3 and CSVW, Apache Avro and Parquet specifications, OpenLineage, and UK Data Standards Authority guidance current 2026-08-31.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-1

Create organization-wide data naming standards.

Answer

What I'd say first

Three questions before writing anything: which warehouses and BI tools have to agree on the names, is there already a catalog holding glossary terms, and who is allowed to break a downstream consumer? Assuming Snowflake or BigQuery, dbt for transformation, and a BI layer that generates its own SQL, I'd ship three things: a short enforced core, a glossary that carries meaning, and a migration path. The core is about fifteen rules. Anything you can't lint gets ignored within a quarter.

The core

elementruleexample
tablesplural snake_case, layer prefixstg_stripe__charges, fct_orders, dim_customers
columnssingular snake_caseorder_id
keys_id business key, _sk surrogatecustomer_id, customer_sk
timestamps_at for timestamptz in UTC, _date for datecreated_at, order_date
booleansis_ / has_ prefixis_active, has_refund
moneydecimal plus currency suffixamount_usd
aggregatessuffix the aggregationrevenue_total_usd, sessions_count

Why lint, not a wiki page

A CI rule fails a pull request in seconds; a document fails nothing. SQLFluff covers the mechanical half: L010 keyword capitalisation, L014 unquoted identifier capitalisation, L029 reserved words used as identifiers, and you add a custom rule for the suffix conventions above. The dbt_project_evaluator package ships naming-convention checks for models, sources and tests, so the dbt side is mostly configuration.

The glossary is a separate artefact because syntax cannot carry semantics. revenue_total_usd tells you the unit and the aggregation; it does not tell you whether refunds are netted or which fiscal calendar applies. That goes in a dbt meta block or a catalog term, and the lint rule asserts every column in a mart has one.

Migration

Never rename in place. Rename the table, then put a view back under the old name:

SQL
ALTER TABLE fct_orders RENAME TO fct_orders_v2;
ALTER TABLE fct_orders_v2 RENAME COLUMN amount TO order_total_usd;
CREATE VIEW fct_orders AS
  SELECT *, order_total_usd AS amount FROM fct_orders_v2;

Readers keep working; writers break loudly, which is how you enumerate them. Drop the view after one deprecation cycle.

Failure modes I've seen

  • Postgres truncates identifiers at 63 bytes. A column named customer_subscription_renewal_effective_timestamp_utc silently becomes something shorter, and two long names can collide at DDL time. Detect it in CI: SELECT column_name FROM information_schema.columns WHERE length(column_name) > 63.
  • Quoted-case traps. Snowflake folds unquoted identifiers to uppercase and treats quoted ones as case-sensitive; BigQuery is case-insensitive for columns but case-sensitive for tables. A model created as "OrderId" breaks the BI tool that emits orderid with invalid identifier. Grep the dbt manifest for quoted identifiers before merge.
  • Renames without aliases. Count column not found errors in the warehouse query history, Snowflake's ACCOUNT_USAGE.QUERY_HISTORY (up to two hours of latency) or BigQuery's INFORMATION_SCHEMA.JOBS_BY_PROJECT, in the seven days after a release. That number, not a style score, is the metric.

Governance

Exceptions go in a naming_exceptions.yml with an owner and an expiry date, reviewed quarterly. Don't retrofit a 4,000-table legacy schema in one pass; apply the standard to new tables and rename on touch. And don't rename anything in a published API contract or a regulatory extract without a versioned alias: the cost there is external, not internal.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5

Define nullability standards for shared data.

Answer

Assumptions. One team owns writes to a shared table, several teams read it, and a partner consumes the same fields over a JSON or Avro contract. So the standard has to hold in the warehouse and on the wire at once. The question is what NULL is allowed to mean, and it can only mean one thing per field.

The answer. Pick one meaning for NULL per field, write it in the column comment, and give every other state an explicit status. My default: NULL means no value present, and a companion *_status enum says why. Fields where the reason never changes a downstream decision get plain NULL, documented as "unknown".

StateEncodingExample
Known valuevaluediscount_pct = 0 (a real zero discount)
Unknown / never observedNULL, status='unknown'source never sent it
Not applicableNULL, status='na'discount on a gift-card order
WithheldNULL, status='redacted'PII stripped before sharing
Not yet observedNULL, status='pending'late-arriving event
InvalidNULL, status='invalid'failed validation, quarantined

Zero, empty string, empty array and false are values, not missingness. discount_pct = 0 and discount_pct IS NULL are different facts and must stay different.

Why not sentinels. The tempting alternative is -1 for unknown, 1900-01-01 for unknown dates, "" for unknown strings. It fails because sentinels are indistinguishable from data: -1 drags AVG and SUM down, 1900-01-01 produces a fake spike in every time-series chart, and "" collides with a genuinely empty string. The second alternative is NULL-only, no status column. Cheaper, but it collapses "not applicable" into "unknown", and a consumer that needs to exclude gift-card orders can't. Deciding criterion: if any downstream decision differs between two states, they need separate encodings; if none does, don't pay for the column.

What breaks without this. SQL is three-valued, so NULLs silently drop out of comparisons rather than erroring. Illustrative table, 100 orders, discount_pct:

SQL
-- 80 rows known, summing to 800; 20 rows NULL (unknown)
SELECT AVG(discount_pct) FROM orders;   -- 800/80 = 10.0
SELECT COUNT(*) FROM orders WHERE discount_pct <> 10;  -- 79, not 99

AVG divides by 80, not 100, so the report says "average discount 10%" while 20% of orders are simply absent from the denominator. If those unknowns were actually 30%, the true mean is (800 + 600)/100 = 14.0: a 4-point error with no warning. COUNT(col) skips NULLs; COUNT(*) doesn't. WHERE x <> 10 excludes NULL rows because NULL <> 10 is UNKNOWN, not TRUE. And WHERE status NOT IN ('cancelled', NULL) returns zero rows, always.

Migration and detection. Adding NOT NULL to a populated column is a rewrite: in PostgreSQL, ALTER TABLE ... SET NOT NULL takes an ACCESS EXCLUSIVE lock and scans the table. Add CHECK (col IS NOT NULL) NOT VALID, backfill, then VALIDATE CONSTRAINT, which takes only a SHARE UPDATE EXCLUSIVE lock. On uniqueness, PostgreSQL allows multiple NULLs in a unique index by default; PostgreSQL 15 added UNIQUE NULLS NOT DISTINCT when you want NULLs to collide.

Detect drift by tracking the NULL rate per field per source per day and alerting on a step change: discount_pct going from 2% to 40% after a partner API change is the signal that a field stopped being sent. Enforce the status enum with a not_null plus accepted_values test so an undocumented state can't be written. Test old readers against new records before promoting a field to required, and never backfill a default that looks observed: a fabricated 0 is worse than a NULL, because it is indistinguishable from a real zero forever.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-3

Standardize timestamps across global systems.

Answer

"Standardize" doesn't mean one representation for every timestamp: it means one rule for picking the representation per field, applied everywhere. I'd sort every temporal field into three buckets before touching storage.

Instants: a point on the timeline: created_at, payment_settled_at. Store as UTC. In Postgres that's timestamptz, an instant held as UTC microseconds (range 4713 BC to 294276 AD, 1 µs resolution); timestamp without time zone is a wall-clock value with no instant semantics and is the wrong type here. In MySQL, TIMESTAMP converts to UTC on write and back on read using the session time_zone, but its range ends at 2038-01-19 03:14:07 UTC, so for anything long-lived use DATETIME with an explicit UTC convention or a BIGINT epoch-micros column.

Civil and date-only: a birthday, a 2024-03-01 invoice date, a store's opening hours. These have no instant. Store DATE or a local-time string plus the IANA zone ID. Converting a birthday to a UTC instant is a bug that surfaces as an off-by-one-day for anyone west of UTC.

Schedules and durations: "every Monday 09:00 local", "30 days". Store the rule plus the zone, not the expanded instants; durations as ISO 8601 (P30D) or a unit plus count, never a bare number.

Why the zone ID and not the offset: an offset like -05:00 is a fact about one instant, while America/New_York is a rule set that changes. Mexico abolished DST in 2022, Egypt reintroduced it in 2023, and tzdata ships several releases a year. Store only the offset and a future event scheduled in that zone renders at the wrong local time after the next tzdata update. Store the instant in UTC and the IANA zone ID in a separate column when local rendering matters.

DST is where naive code breaks. In America/New_York on 2024-11-03 clocks fall back from 02:00 EDT to 01:00 EST, so local 01:30 happens twice. Once at 2024-11-03T01:30:00-04:00 and again at 2024-11-03T01:30:00-05:00. A timestamp column can't tell them apart, so ordering by it is ambiguous. On 2024-03-10 the spring-forward gap means local 02:30 never exists, so a scheduler that adds 24 hours to "yesterday 02:30" lands on a nonexistent time. RFC 3339 offsets disambiguate the overlap; for the gap you must pick a policy: shift forward, reject, or skip.

Event time versus processing time: event_time is when it happened at the source, processing_time is when your pipeline saw it. They diverge under retries, mobile offline queues and backfills. Keep both columns; window on event time with a watermark (Flink, Beam) and use processing time only for operational metrics. Late events past the watermark need an explicit drop-or-update policy.

Trade-offs. UTC-everywhere is simplest and right for instants, but wrong for anything a human reads in local terms. Stored-offset is right when you only ever reproduce the original rendering and never re-derive future local times. Store-zone-plus-UTC costs a column and a tzdata dependency but is the only option that survives rule changes.

Failure modes and how to catch them. Off-by-one-day on date-only fields: test that round-trips a DATE through every service. Ambiguous DST ordering: assert that two events in the overlap sort by their UTC instant, not their local string. Silent truncation: Postgres timestamptz is µs, Java Instant is ns, JS Date is ms; assert precision at the boundary. Clock skew: sync with NTP or chrony, or AWS Time Sync (PTP, µs-level), and record the source. Tests worth writing: RFC 3339 round-trip serialization with offset, a zone-transition case per zone you support, and a late event that crosses a watermark.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

Standardize money and currency fields.

Answer

Core answer

Store money as an exact type and always carry the currency code with the amount: never a float, never a locale-formatted string. Two representations work: fixed-point DECIMAL(19,4), or an integer count of minor units (INT64) plus an explicit scale. Pick one per system, enforce it in the schema, and fix the rounding mode and rounding stage before anyone writes a query.

Assumptions I'd state up front: multi-currency ledger, refunds, and FX conversion in scope; the currency set includes 2-decimal (USD), 0-decimal (JPY) and 3-decimal (KWD) per ISO 4217.

Why float fails

IEEE 754 doubles can't represent 0.1 exactly. In Python 3.12:

Python
0.1 + 0.2            # 0.30000000000000004
sum([0.1] * 10)      # 0.9999999999999999

A ledger summing ten $0.10 lines reports $0.9999999999999999, not $1.00. Integer minor units: 10 * 10 == 100 cents, exact.

Rounding stage compounds

Define the mode (half-up vs banker's) and the stage (per line vs per invoice). Three lines of 1.005, half-up per line → 1.01 each → 3.03. Rounding the total 3.015 → 3.02. One cent per invoice; at 1M invoices/day that's ~$10k/day of reconciliation breakage.

FX

Store original amount+currency, converted amount+currency, rate, rate timestamp, and source. Never re-derive the original from the converted: $100 → €90 at 0.90, back at 1.1111 → $99.999. The round-trip loses a cent.

Trade-offs

DECIMAL(19,4)INT64 minor units
exactyesyes
3-dp currenciesneeds scale 4, padneeds exponent stored
range19 digits±9.2e18 minor units (~$92 quadrillion in cents)
wrong whenengine emulates decimal and is slow at scaleyou need sub-minor precision (per-call pricing, interest accrual)

Failure modes

  • Cent drift on aggregation: detect by reconciling sum-of-lines to invoice total; cost is a delayed finance close.
  • FX applied twice: detect with a round-trip check; cost is restated revenue.
  • Mixed-currency aggregation: summing without grouping by currency; prevent by making currency part of the key.

Constraints: no formatted strings in storage; one sign convention for refunds; explicit range checks.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-14

Standardize Boolean and lifecycle status fields.

Answer

Core answer. First I'd ask whether this is the database schema, the API contract, or both: I'll assume both, and that there's no big-bang cutover.

The rule: a boolean is correct only for a stable two-state proposition with a decided null policy. is_verified qualifies. is_active does not, because "active" is a position in a lifecycle, and lifecycles grow a third state the first time someone asks for "suspended" or "pending review". Once you have is_active, is_deleted, is_pending, you've encoded one status enum across three columns that can contradict each other, and nothing in the schema prevents is_active = true, is_deleted = true.

So: booleans for genuine predicates, one governed status column for lifecycle.

I'd store status as a short string code (pending, active, suspended, closed, cancelled) not a smallint. The integer saves a few bytes and costs a lookup every time you read a log line or a row by hand. Keep the allowed transitions as data:

fromtoguard
pendingactivepayment captured
pendingcancelleduser action or 24h timeout
activesuspendedrisk hold
activecloseduser request
suspendedactivehold released
suspendedcloseduser request
closed—terminal
cancelled—terminal

Separate state from reason: status, status_reason, status_changed_at. Separate when it takes effect from when you learned it: effective_at vs recorded_at. A suspension scheduled for midnight is not the same as one applied at midnight.

Enforce transitions in one place:

Python
# Python 3.12
ALLOWED = {
    "pending":   {"active", "cancelled"},
    "active":    {"suspended", "closed"},
    "suspended": {"active", "closed"},
    "closed":    set(),
    "cancelled": set(),
}

def transition(current: str, target: str) -> str:
    if target not in ALLOWED.get(current, set()):
        raise ValueError(f"illegal transition {current} -> {target}")
    return target

Trace transition("closed", "active"): ALLOWED["closed"] is the empty set, "active" is not in it, so it raises. The illegal move fails at the boundary instead of writing a row a reader has to interpret.

Failure modes. Contradictory flags: detect with SELECT count(*) FROM t WHERE is_active AND is_deleted; if it's nonzero, every reader is already guessing precedence, and different services guess differently. Nullable boolean: WHERE is_active silently drops NULL rows. Compare count(*) against count(is_active) to see how many. Unknown future code: a newer producer writes "paused", an older consumer's switch falls through to default and treats it as active; log unknown codes, alert on a nonzero rate, and make the default branch fail closed. Lost update: two writers both read active and write different targets. Use UPDATE ... WHERE status = 'active' and check that one row changed, or a version column.

Migration. Add status nullable, backfill by deriving from the flags with a documented precedence, and quarantine rows where the flags disagree into a review table rather than picking a winner in code. Dual-read (prefer status, fall back to flags) and dual-write, then add the CHECK constraint and NOT NULL, then drop the flags. Test every transition in the table, plus retries, a retried active -> closed must be idempotent, and one old consumer that still reads the flags.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

You need one logical type standard that maps across Postgres, Snowflake and BigQuery. How do you define it so a model stays portable?

Answer

Start with the layer, not the engine. A canonical type standard is a logical type registry (a versioned, machine-readable list of types with fixed semantics) plus a mapping from each logical type to each engine's physical type. You do not standardize on Postgres numeric or Snowflake NUMBER; you standardize on DECIMAL(p,s) with a fixed (p,s) budget and let codegen emit the engine type. Parquet logical types and Avro logical types are the vocabulary to borrow, because they already define decimal, date, time and timestamp with explicit units and a UTC flag, and they are the interchange formats most pipelines already write.

Assumptions: Postgres 16, Snowflake, BigQuery; interchange is Parquet or Avro; the model is defined once and generated per engine.

The core decision is the numeric budget. BigQuery NUMERIC is fixed at precision 38, scale 9. Snowflake NUMBER maxes at precision 38. Postgres numeric(p,s) is arbitrary precision, so it will accept anything and hide the portability break. Canonical DECIMAL(38,9) is the intersection: 29 integer digits and 9 fractional digits. Anything wider needs BIGNUMERIC (76.76 digits) or a string, and that is an explicit exception, not a default.

CanonicalParquetAvroPostgresSnowflakeBigQuery
DECIMAL(38,9)DECIMAL(38,9)decimal(38,9) bytesnumeric(38,9)NUMBER(38,9)NUMERIC
INT64INT64longbigintNUMBER(38,0)INT64
STRINGBYTE_ARRAY UTF8stringtextVARCHARSTRING
TIMESTAMP_MICROS UTCTIMESTAMP(isAdjustedToUTC=true, MICROS)timestamp-microstimestamptzTIMESTAMP_TZTIMESTAMP
DATEDATEdatedateDATEDATE
BOOLEANBOOLEANbooleanbooleanBOOLEANBOOL

Timestamps are the second trap. Postgres timestamptz is an instant stored as UTC microseconds; timestamp is civil time with no zone. Snowflake splits TIMESTAMP_TZ, TIMESTAMP_NTZ, TIMESTAMP_LTZ. BigQuery TIMESTAMP is an instant, DATETIME is civil. The registry must carry the UTC flag as part of the type, not as a convention: TIMESTAMP_MICROS(isAdjustedToUTC=true) maps to timestamptz/TIMESTAMP_TZ/TIMESTAMP, and civil time maps to timestamp/TIMESTAMP_NTZ/DATETIME. Mapping a civil column to an instant column silently shifts values by the session offset.

Nullability and constraints are declared in the logical model and enforced where the engine can. Postgres enforces NOT NULL, CHECK, UNIQUE and foreign keys. BigQuery enforces NOT NULL but not CHECK, UNIQUE or foreign keys. Snowflake enforces NOT NULL but not UNIQUE or foreign keys by default. So the standard emits engine DDL for what is enforceable and a data-quality test for the rest; otherwise a UNIQUE that holds in Postgres is assumed to hold in BigQuery and does not.

Failure modes and detection:

  • Precision overflow on load: a Postgres numeric(50,10) column loaded into BigQuery NUMERIC fails or rounds. Detect before load with SELECT count(*) FROM t WHERE abs(col) >= 10^29.
  • Timestamp semantic drift: compare min/max and offset distribution between source and target; a constant offset means a civil/instant mismatch.
  • String length loss: Postgres varchar(255) counts characters; BigQuery STRING is 16 MB and Parquet BYTE_ARRAY has no length. If length is a contract, keep it as a declared constraint and test it; do not rely on the physical type.
  • Float for money: double precision, FLOAT, FLOAT64 are all IEEE 754 binary64, so sums differ by order. Detect with reconciliation on a fixed query order.

When not to: if the model only ever runs on one engine, the registry is overhead. If you need more than 38 digits, use BIGNUMERIC or string and record the exception with an owner and expiry.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Create data modeling standards for JSON columns.

Answer

The rule, stated first. Use a JSON column only when the shape is set by someone you don't control: a vendor payload, an event schema you don't own, a sparse set of optional attributes, or when you must keep the source document verbatim for audit. If a field appears in a WHERE, JOIN, ORDER BY, needs a constraint, or is updated independently of the rest of the document, it gets a typed column. Everything below is how you enforce that. Assume Postgres; the reasoning carries to MySQL's JSON and SQL Server's JSON functions, but the numbers are Postgres.

Why jsonb behaves the way it does. Postgres keeps no statistics on the inside of a jsonb value. The planner's selectivity estimate for containment (payload @> '{"status":"active"}') is a fixed default of 0.5%, so it predicts the same row count whether the key matches 3 rows or 3 million. That is the mechanism behind the classic plan regression: the index looks cheap, the estimate is wrong, and the plan flips to a seq scan or a nested loop that runs for minutes. Three more engine facts drive the rest of the standard:

  • Values above roughly 2 KB get TOASTed out of line and compressed, and every read then pays a detoast.
  • There is no partial update. jsonb_set and any UPDATE rewrite the entire value, so a 100 KB document touched once a second writes 100 KB/s of WAL and leaves a dead tuple per update. A jsonb column on a hot row is a bloat generator.
  • A GIN index serves containment and existence only, and the opclasses differ: jsonb_path_ops is smaller and answers @>; jsonb_ops also answers key existence (?, ?|, ?&) at the cost of a larger index. Neither answers range or ordering queries: those need a B-tree on an expression or a generated column.

The standard.

SQL
CREATE TABLE events (
  id             bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  schema_version int   NOT NULL,
  payload        jsonb NOT NULL,
  status         text  GENERATED ALWAYS AS (payload->>'status') STORED,
  CONSTRAINT payload_is_object  CHECK (jsonb_typeof(payload) = 'object'),
  CONSTRAINT payload_has_version CHECK (payload ? 'schema_version'),
  CONSTRAINT payload_size       CHECK (octet_length(payload::text) < 65536)
);
CREATE INDEX events_status_idx  ON events (status);
CREATE INDEX events_payload_idx ON events USING GIN (payload jsonb_path_ops);
  • jsonb, not json, unless you must preserve key order, duplicate keys and whitespace: jsonb collapses {"a":1,"a":2} to {"a": 2} and drops formatting.
  • schema_version is a top-level integer, bumped on every breaking change.
  • Validate with CHECK constraints for the invariants that matter (type, required keys, size) and JSON Schema for the full shape if you need it. A CHECK runs on every write and costs nothing at read time.
  • Cap documents at 64 KB hard, aim for under 2 KB, depth limit 5.
  • Promote with generated columns, not triggers: GENERATED ALWAYS AS (...) STORED cannot drift, because the value is computed on write and cannot be set independently.
  • Evolution is additive only: add keys, never repurpose or remove one. Readers ignore unknown keys; writers never delete.

When not to use JSON. If the field is filtered, joined, constrained, or updated on its own, it is a column. Promoting costs a migration and a backfill; not promoting costs a planner that cannot estimate and a schema that cannot enforce. Promote once a field shows up in more than a couple of queries.

Failure modes and how you see them.

  • Plan regression: EXPLAIN shows estimated rows 200 against actual 400,000. Watch pg_stat_statements mean time per query and alert on a 5x jump after a data-shape change.
  • Bloat: pg_stat_user_tables.n_dead_tup climbing and table size growing faster than row count. Autovacuum cannot keep up with whole-value rewrites.
  • Drift: a promoted column disagrees with the JSON. Detect with a periodic SELECT count(*) FROM events WHERE status IS DISTINCT FROM payload->>'status': it should be zero.
  • Round-trip loss: a producer sends duplicate keys or a number beyond numeric range; jsonb keeps the last key and the oversized number errors on insert. Test with the producer's real payloads, not synthetic ones.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

Choose keys for a multi-tenant customer model.

Answer

Assume a shared-schema multi-tenant SaaS on PostgreSQL 15, tenants identified by a bigint tenant_id, and a customer entity whose business identifiers (email, external customer number) are unique per tenant but not globally.

Core answer: use a composite key (tenant_id, customer_id) with customer_id bigint generated always as identity, and enforce business uniqueness with a partial unique index on the business identifier. The surrogate is for joins; the business key is for uniqueness; a mapping table is for entity resolution.

SQL
CREATE TABLE customer (
  tenant_id       bigint NOT NULL,
  customer_id     bigint GENERATED ALWAYS AS IDENTITY,
  email           text,
  customer_number text,
  PRIMARY KEY (tenant_id, customer_id)
);
CREATE UNIQUE INDEX customer_email_uq
  ON customer (tenant_id, lower(email)) WHERE email IS NOT NULL;

Don't make email the primary key: it changes, gets recycled, and is sensitive. If you need globally unique IDs for offline creation or distributed ingestion, use UUIDv7: PostgreSQL 15 has no built-in uuidv7(), so generate it in the application or via the pg_uuidv7 extension, but keep tenant_id in the PK.

Why doesn't a surrogate solve entity resolution? It's just a unique number. Ingest from CRM and billing and you get two rows with different customer_ids. You need a mapping table: customer_source_map (tenant_id, source_system, source_id, customer_id, valid_from, valid_to) plus a matching process.

Row-level security enforces the boundary:

SQL
ALTER TABLE customer ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON customer
  USING (tenant_id = current_setting('app.tenant_id', true)::bigint)
  WITH CHECK (tenant_id = current_setting('app.tenant_id', true)::bigint);

The app runs SET LOCAL app.tenant_id = '42'; inside the transaction. current_setting(..., true) returns NULL when unset, and NULL = tenant_id is NULL, so a missing setting fails closed (zero rows) instead of erroring. Use SET LOCAL, not SET, because session GUCs leak across pooled connections.

On WITH CHECK: if you omit it, PostgreSQL uses the USING expression for new rows too, so inserts are still filtered. Omitting it is not a hole. Specify it separately only when the write predicate must differ from the read predicate (for example, USING permits reading shared rows while WITH CHECK pins tenant_id to the session value).

Alternatives: database-per-tenant lets you drop tenant_id and use a plain bigint PK. If customers move between tenants often, the composite PK is expensive because every FK must be rewritten; use a global UUIDv7 surrogate plus a separate tenant_id and RLS, accepting that you lose tenant clustering and must carry tenant_id in every query.

StrategyPKBusiness uniquenessProsCons
Composite(tenant_id, customer_id)UNIQUE (tenant_id, lower(email))isolation, no cross-tenant collisionmoves rewrite FKs, wider indexes
Global surrogatecustomer_id (UUIDv7)UNIQUE (tenant_id, lower(email))cheap moves, globally uniqueno tenant clustering, tenant_id in every query
Natural key(tenant_id, lower(email))PK itselfno extra columnmutable, sensitive, recycled

Failure modes and detection:

  • Cross-tenant read: app forgets to set app.tenant_id; with missing_ok the policy returns zero rows. Detection: a tenant that should have data reads empty; alert on unexpected zero-row reads.
  • Business-key join fan-out: JOIN customer c ON c.email = o.email without tenant_id multiplies rows when two tenants share an email. Detection: reconciliation counting orders per email above the expected one.
  • Collision: PK is customer_id alone while each tenant has its own sequence starting at 1. The second tenant's insert fails with a duplicate-key error, not silent corruption. Detection: unique violation on insert. Fix: composite PK or a global sequence/UUID.
  • Merge: update FKs; a missed table leaves orphans. Detection: SELECT ... WHERE NOT EXISTS orphan check.

Merge trace, tenant 42, customer 101 into 202:

SQL
INSERT INTO customer_merge (tenant_id, old_id, new_id, merged_at)
VALUES (42, 101, 202, now());
UPDATE orders SET customer_id = 202
 WHERE tenant_id = 42 AND customer_id = 101;

For millions of orders, batch by customer_id range. Alternative: keep the old row, add merged_into bigint, and resolve with COALESCE(merged_into, customer_id). No FK rewrite, but an extra lookup.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

Govern reference codes shared by many systems.

Answer

Core answer

Assume the codes are a controlled vocabulary (country, currency, product class, diagnosis) that outlives any single service and appears in historical records you cannot rewrite. The job is not to pick codes. It is to make the meaning of a code stable across time and across systems that upgrade on different schedules.

So: one authoritative registry per code system, with a named owner and a stated purpose. Every code is a row, not a string literal in a config file. The row carries the code, the label, the definition, the parent if the vocabulary is hierarchical, effective-from and effective-to dates, a status (active, deprecated, retired), and a replacement code when one exists. Retired codes stay in the table forever as tombstones. Nothing is deleted, nothing is reused.

Then publish it machine-readably and version it. Consumers pin a version; the registry keeps every version it has ever published.

Why it behaves this way

Retired codes must persist because history is written in them. Delete TRL when Turkey redenominated the lira on 1 January 2005 and every 2004 invoice becomes unreadable. ISO 4217 kept TRL, and the mapping is 1,000,000 old lira = 1 new lira (TRY). ISO 3166-3 exists for the same reason: it gives formerly used country codes a permanent four-letter tombstone so a code like CS (Czechoslovakia, later reassigned to Serbia and Montenegro) can be disambiguated by date.

That CS case is the failure mode that decides the design: code reuse. If one code can mean two things, no amount of documentation fixes it, because the consumer reading a 1990 record and the consumer reading a 2005 record both see CS.

Trade-offs

Central registry vs federated ownership. One team owning every code list becomes a bottleneck the moment a domain needs a code on a Friday. Federated (each domain owns its slice, a thin registry indexes them) scales, but you lose one place to answer "is this code live?" Decide on rate of change and blast radius: a currency list changes a few times a decade and is worth centralizing; a product taxonomy changes weekly and is not.

Strict vs lenient validation. Rejecting unknown codes protects your data and breaks ingestion the first time a partner sends a code you have not loaded. Accepting and flagging keeps the pipeline moving and quietly poisons analytics. The deciding question is where the code comes from: reject on your own UI, accept-and-quarantine from external feeds, reconcile the quarantine queue on a schedule.

Mapping vs migration. ICD-9 to ICD-10 GEMs are many-to-many and lossy; treating them as 1:1 is how you get a report that does not add up. Keep the mapping, keep the original code, never overwrite the source value.

Failure modes and detection

  • Code reuse: unique constraint on (system, code), plus a nightly check that no retired code appears in new writes. Cost of missing it: a historical report silently changes meaning.
  • Silent reinterpretation: hash label+definition per version; alert when the hash changes without a version bump.
  • Mapping drift: reconcile counts, records mapped vs records in source, and sample-audit the many-to-many edges.
  • Partial rollout: emit adoption telemetry per consumer per pinned version; alert when a consumer is more than one release behind.

Artefacts

Registry row (Postgres):

SQL
CREATE TABLE code (
  system         text NOT NULL,
  code           text NOT NULL,
  version        text NOT NULL,
  label          text NOT NULL,
  definition     text NOT NULL,
  effective_from date NOT NULL,
  effective_to   date,
  status         text NOT NULL CHECK (status IN ('active','deprecated','retired')),
  replaced_by    text,
  PRIMARY KEY (system, code, version)
);
-- tombstones are rows with status='retired'; no DELETE grant on this table

Lifecycle trace for TRL:

dateeventrow
2004-12-31last day TRL is legalstatus=active, effective_to=2005-01-01
2005-01-01TRY introduced, 1,000,000:1new row, system=ISO4217, code=TRY
2005-01-01TRL retiredstatus=retired, replaced_by=TRY

A consumer reading a 2004 record resolves TRL → retired → TRY with the 1,000,000 factor. A consumer reading a 2006 record sees TRY directly. Neither has to know the other exists.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-2

Model a sales fact table without double counting.

Answer

Let me clarify the scenario: we're designing a star schema for sales analytics. The core risk is double counting when we combine facts at different grains. My approach: pick one atomic grain per fact table, and never join fact tables directly without aggregating to a common grain first.

Assume we have an order management system. The finest grain for revenue is the order line. So I'd create a fact table fact_order_line with one row per order line. Columns: order_line_id (surrogate key), order_id, product_id, order_date (occurrence time), load_timestamp (processing time), quantity, unit_price, extended_amount (quantity * unit_price), currency. Use DECIMAL(18,4) for amounts. For multi-tenant, add tenant_id and include it in the unique key. This table is fully additive across all dimensions.

Now, shipments happen separately. A shipment can cover multiple order lines, and an order line can be shipped in multiple shipments. So I'd have fact_shipment_line with one row per shipment line: shipment_line_id, order_line_id, shipment_date, quantity_shipped. This is also additive.

If I naively join these two on order_line_id and sum extended_amount, I double count. Example:

fact_order_line: | order_line_id | order_id | product_id | quantity | unit_price | extended_amount | | 1 | 100 | A | 2 | 10.00 | 20.00 | | 2 | 100 | B | 1 | 5.00 | 5.00 |

fact_shipment_line: | shipment_line_id | order_line_id | quantity_shipped | | 1 | 1 | 1 | | 2 | 1 | 1 | | 3 | 2 | 1 |

Query: SELECT SUM(extended_amount) FROM fact_order_line o JOIN fact_shipment_line s ON o.order_line_id = s.order_line_id; returns 20*2 + 5 = 45, but true revenue is 25. Double counting.

To avoid this, aggregate shipments to the order line grain before joining, or use a bridge table if you need to allocate shipment quantities to order lines. For most reporting, you don't need to join them in the same query. If you do, use a CTE (PostgreSQL 15):

SQL
WITH shipment_agg AS (
  SELECT order_line_id, SUM(quantity_shipped) AS total_shipped
  FROM fact_shipment_line
  GROUP BY order_line_id
)
SELECT o.order_line_id, o.extended_amount, s.total_shipped
FROM fact_order_line o
LEFT JOIN shipment_agg s ON o.order_line_id = s.order_line_id;

This gives one row per order line, no duplication.

Now, measures: extended_amount is fully additive. quantity is additive. unit_price is non-additive: you must use weighted average. quantity_shipped is additive. Inventory balances are semi-additive: you can sum across products but not across time; you take the last value per period.

Tradeoffs: A single fact table at order line grain is simplest and avoids double counting, but it can't answer questions about shipment delays or payment status. Multiple fact tables give flexibility but require the query tool to handle drill-across correctly. Bridges are necessary for many-to-many relationships (e.g., promotions applied to order lines) but add complexity and can themselves cause double counting if not used with allocation factors. When not to use a bridge: if the relationship is one-to-many and you can aggregate to the many side, or if you never need to combine measures from both facts in the same query.

Failure modes: Double counting is detected by reconciling totals with source systems. For example, run a daily check: SELECT SUM(extended_amount) FROM fact_order_line vs. the order management system's total revenue. If they differ, investigate. Also check row counts: a query that returns more rows than the number of order lines indicates a fan-out. Operational cost: overstated revenue, incorrect commissions, bad inventory decisions. Another failure: late-arriving facts. If a shipment arrives after the order line is loaded, you need to handle it. Use a late-arriving dimension or fact table with effective dates, and reprocess affected partitions. Detection: monitor data freshness and compare daily totals.

In summary, the core answer: one grain per fact table, aggregate before joining, and use bridges only when necessary. That's how you avoid double counting.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-23

How do you standardize the declaration and validation of fact table grain across the enterprise so that every fact table states its grain and double counting is prevented?

Answer

The 60-second answer. Grain is the business definition of one row. Standardize it as a contract with three parts: every fact table declares its grain in machine-readable metadata, the declared columns carry a uniqueness constraint in the database, and CI fails the build when the declaration and the DDL disagree. The declaration is what makes double counting preventable, because every join and every aggregate can be checked against it.

Assumptions: a central metadata registry exists (catalog or a dbt project), the warehouse enforces unique constraints, and fact tables are loaded by scheduled ETL.

Declaration. Register each fact table with its atomic dimension keys, not a prose sentence:

FieldExamplePurpose
fact_tablesales_factidentifies the table
grain_descriptionone row per order line per dayhuman-readable
grain_columnsdate_key, store_key, product_key, promotion_keymachine-readable
uniqueness_constraintsales_fact_grain_uniqueenforcement
ownersales_engaccountability

The same list is emitted into the DDL comment, the dbt model meta, and the Avro/Parquet schema annotation. In the catalog, carry it as an extension property on the dataset (DCAT permits additional properties), and propagate it through lineage with an OpenLineage custom facet so downstream consumers see the grain without reading the DDL.

Validation, three layers.

  1. CI parses the DDL and compares declared grain columns to the registry; a mismatch fails the build. It also checks minimality: for each declared column, run a uniqueness probe on a sample with that column dropped. If the remainder is still unique, the declared grain is not atomic and the check fails.

  2. The database enforces it:

SQL
ALTER TABLE sales_fact
  ADD CONSTRAINT sales_fact_grain_unique
  UNIQUE (date_key, store_key, product_key, promotion_key);

This rejects duplicate rows at insert. On a partitioned table PostgreSQL requires the partition key in any unique constraint, so a global constraint on grain columns alone is not possible; use a unique index on (grain_columns, partition_key) plus a scheduled cross-partition dedup test.

  1. A runtime test catches ETL bugs that bypass constraints: a dbt unique test on the grain columns, or the equivalent scheduled query:
SQL
SELECT date_key, store_key, product_key, promotion_key, count(*)
FROM sales_fact
GROUP BY 1,2,3,4
HAVING count(*) > 1;

Why it prevents double counting: a trace. sales_fact holds one row: order line 4711, product_key 88, amount 120.00. product_dim is SCD2 with three versions of product 88. Joining on product_key alone yields three rows and SUM(amount) = 360.00. The grain declaration says the fact is at product_key level, so the legal join is on the natural key plus the version valid at the fact's date:

SQL
JOIN product_dim d
  ON d.product_key = f.product_key
 AND f.event_date BETWEEN d.valid_from AND d.valid_to

One row, 120.00. The declaration is what tells the query author which join is legal.

Failure modes and detection. Grain drift: a column added that changes the grain but the constraint is not updated; detect with the CI minimality check. Duplicate loads from a retried batch: detect with the runtime uniqueness test and row counts versus source. Fan-out joins: detect by comparing fact row counts before and after each join in the ETL. Partitioned tables where uniqueness is only local: detect with the cross-partition dedup test.

Trade-offs. A unique index on four bigint columns over 1B rows costs roughly 50 GB (estimate: ~48 bytes per index entry before fillfactor) and adds an index probe to every insert. If that write cost is unacceptable, enforce uniqueness in a post-load dedup job and keep the constraint on a smaller aggregate, but never drop the declaration.

Rollout. Seed the registry from existing tables, run the CI check as a warning, then make it blocking. Publish grain in the catalog so consumers can write correct queries.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

Choose a slowly changing dimension strategy.

Answer

Core answer (first 90 seconds)

I'd ask three things before picking: which questions the warehouse has to answer, whether the source can tell a correction from a real change, and how much history the business will actually query. Then I default to Type 2 with half-open validity intervals and a current-row flag, and use Type 1 only for attributes nobody asks history about.

Assumptions I'd state out loud: the source sends a full snapshot each day with an updated_at timestamp, and fact tables arrive with their own event dates that can be backdated.

Why Type 2: it's the only one that lets a fact join the dimension version that was true when the event happened. One row per version, keyed by a surrogate key, with valid_from, valid_to and is_current. The natural key stays the same; the surrogate key is what the fact stores.

The comparison

TypeWhat you storeAnswersWhat it costs
1overwrite in placecurrent state onlyhistory gone, no audit
2new row per tracked changeas-was at any daterow growth, more joins
3previous value in a columncurrent + one step backonly one step back
6Type 1 + 2 + 3 hybridcurrent, as-was, priormost moving parts

Type 3 is rarely worth it: one prior value answers almost no real question. Type 6 is what you get when you bolt a current-value column onto Type 2 rows so BI tools can filter is_current without a subquery.

Worked trace

Customer 42, daily snapshot, half-open intervals [valid_from, valid_to):

skcustomer_idstatevalid_fromvalid_tois_current
100142CA2024-01-012024-06-15false
100242NY2024-06-15NULLtrue

A fact dated 2024-03-10 joins sk 1001 and reports CA. A fact dated 2024-06-15 joins 1002 and reports NY: that's why the interval is half-open, so the boundary belongs to exactly one row.

Now the source restates: the move actually happened 2024-05-01. You must close 1001 at 2024-05-01 and move 1002's valid_from back, not just insert a third row. Insert-only leaves two rows covering May, and every fact in May double-counts.

Failure modes and how I'd catch them

  • Overlapping intervals after a backdated correction. Detect with a self-join:
SQL
SELECT a.customer_id, a.sk, b.sk
FROM dim_customer a
JOIN dim_customer b
  ON a.customer_id = b.customer_id
 AND a.sk < b.sk
 AND a.valid_from < COALESCE(b.valid_to, DATE '9999-12-31')
 AND b.valid_from < COALESCE(a.valid_to, DATE '9999-12-31');
  • Two current rows for one natural key: a failed MERGE. SELECT customer_id FROM dim_customer WHERE is_current GROUP BY 1 HAVING COUNT(*) > 1.
  • Late-arriving facts joining the wrong version because the dimension loaded after the fact. Symptom: a fact's event date is earlier than the valid_from it joined. Fix by re-running the affected partitions.
  • Volume: 5M customers × 2 changes/year × 5 years ≈ 55M rows. Fine in Snowflake or BigQuery, painful in a row-store OLTP database.

What I'd document as unsupported

If the source only sends current state and no change timestamp, you can't distinguish a correction from a real change: say so, and pick Type 1 or accept that history is approximate.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-6

Design a conformed customer dimension.

Answer

I'd clarify three things first: which sources are in scope, whether a customer is a person or an account, and what cross-domain questions the dimension must answer. Assume CRM, Billing, and Support; one master customer per person; facts need point-in-time customer segment and status.

Design: one SCD-2 dimension at grain customer per version, plus an xref table for many source ids to one master. The surrogate key is warehouse-only; the business key is the master customer id. Source ids never become the dimension key.

SQL
CREATE TABLE customer_dim (
  customer_sk      BIGINT PRIMARY KEY,
  customer_bk      STRING NOT NULL,
  email            STRING,
  phone            STRING,
  segment          STRING,
  status           STRING,
  effective_from   TIMESTAMP NOT NULL,
  effective_to     TIMESTAMP NOT NULL,
  is_current       BOOLEAN NOT NULL
);

CREATE TABLE customer_source_xref (
  customer_bk      STRING NOT NULL,
  source_system    STRING NOT NULL,
  source_id        STRING NOT NULL,
  match_confidence DECIMAL(3,2),
  PRIMARY KEY (source_system, source_id)
);

Hypothetical rows after a phone change on 2024-07-01:

customer_skcustomer_bkemailphonesegmenteffective_fromeffective_tois_current
1001C-88a@x.com555-0100Gold2024-01-012024-06-30false
1002C-88a@x.com555-0101Gold2024-07-019999-12-31true
customer_bksource_systemsource_idmatch_confidence
C-88CRMcrm-551.00
C-88Billingbill-770.92
C-88Supportsup-120.85

Matching: deterministic on normalized email or tax id; probabilistic on name plus address. Score above 0.95 auto-merges, 0.85-0.95 queues for review, below 0.85 creates a new customer_bk. Survivorship is per attribute: email from CRM if present else Billing; phone from Billing if present else CRM; segment from CRM. On 2024-07-01 Billing's phone wins, so the current row closes and a new version opens. Point-in-time query: WHERE effective_from <= :as_of AND effective_to > :as_of.

Failure modes I'd watch:

failuredetectioncost
Missed match creates duplicate customer_bkcount(distinct customer_bk) > 1 per source_id, or daily match rate drops more than 5%inflated customer count, split LTV
Bad survivorship overwrites good email with stale CRMattribute-level lineage audit, sample 100 rows where source priority was violatedcampaign bounce rate rises
SCD-2 gap or overlapquery where effective_to < effective_from or overlapping intervals per customer_bkpoint-in-time joins double-count revenue
Late-arriving factfact rows with event_date before customer effective_fromorphan facts, wrong cohort

Trade-off: conform only attributes used in cross-domain joins or filters. Customer_bk, segment, status, effective dates. Keep single-domain, high-churn attributes like support_tier or billing_plan in extension tables keyed by customer_sk. Relax conformance when an attribute is used by one fact table only; if it needs real-time updates, put it in a separate profile store rather than forcing it into the SCD-2 dimension. dbt tests for unique customer_sk, not_null, and relationships catch the first two failures before they reach facts.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

Prevent overlapping effective intervals.

Answer

Core answer (first 90 seconds)

Store valid time as a half-open range [valid_from, valid_to) on the entity, and let the database enforce non-overlap with an exclusion constraint instead of trusting application code.

SQL
CREATE EXTENSION btree_gist;

CREATE TABLE position (
  entity_id bigint    NOT NULL,
  valid     tstzrange NOT NULL,
  state     text      NOT NULL,
  EXCLUDE USING gist (entity_id WITH =, valid WITH &&)
);

btree_gist gives GiST an equality operator for bigint; without it the constraint cannot be built. The constraint is backed by a GiST index, so a conflicting insert is rejected in O(log n) rather than scanning the table, and a concurrent insert of an overlapping range blocks on the index entry and re-checks after the other transaction commits or aborts: the same mechanism a unique index uses.

Half-open matters. [Jan 1, Feb 1) and [Feb 1, Mar 1) do not overlap, so && is false and both rows coexist; closed intervals would falsely conflict at the boundary. Represent open-ended as 'infinity', not NULL: a NULL bound makes the range unbounded in a way that breaks the && comparisons you expect.

Worked trace

SQL
INSERT INTO position VALUES (1, '[2024-01-01, 2024-02-01)', 'A'); -- ok
INSERT INTO position VALUES (1, '[2024-02-01, 2024-03-01)', 'B'); -- ok, adjacent
INSERT INTO position VALUES (1, '[2024-01-15, 2024-01-20)', 'C');
-- ERROR: conflicting key value violates exclusion constraint "position_entity_id_valid_excl"
-- DETAIL: Key (entity_id, valid)=(1, ["2024-01-15","2024-01-20")) conflicts with existing key (1, ["2024-01-01","2024-02-01")).

The third insert overlaps row A, the GiST index finds it, and the statement aborts. Row B never conflicts because adjacency is not overlap.

When you cannot use an exclusion constraint

MySQL and SQL Server have no equivalent. There you serialize writers per entity: take a row lock (SELECT ... FOR UPDATE on a per-entity lock row) or a transaction-scoped advisory lock, then run the overlap SELECT and insert inside the same transaction. The cost is that all writers for one entity queue, and any code path that skips the lock silently reintroduces the race, so the lock has to be the only write path. A trigger that just runs the overlap query does not help; without the lock two transactions both pass the check before either commits.

Failure modes and how you catch them

  • DST. If you store timestamp (no time zone) in a zone with DST, the fall-back hour repeats: two distinct instants map to the same local time, so the constraint either falsely rejects or falsely allows. Store timestamptz. You detect it as a constraint violation at 01:30 on the fall-back date.
  • Backfill. A bulk load out of order fires the constraint mid-batch. Load sorted by valid_from, or into a staging table, then validate before promoting.
  • Corrections and backdating. You cannot update a row in place when the new range overlaps a neighbour; you split: close the old row at the correction point and insert the corrected segment. That split is the real operational cost of the constraint.
  • Current state. Derive it with valid @> now() rather than a boolean is_current flag, which drifts the moment a backdated row lands.

Test same-timestamp inserts, the DST boundary, two parallel writers on one entity, and a retry of a failed insert.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

Model deleted data with retention obligations.

Answer

Core answer. I'd stop treating deletion as a boolean on a row and model it as an event with a retention policy per data class. First I clarify three things: what "deleted" must mean to the user (gone from the product), to legal (retained or erased under a named obligation), and to analytics (usually de-identified, not gone). Those three answers rarely agree, and the disagreement is the design. Then I pick a mechanism per class, not one mechanism for the whole system.

StrategyWhat it doesUse whenWrong when
Hard deleteRow removedNo retention obligation, no replicas to reconcileReplicated/append-only stores; a replica that missed the delete resurrects the row
TombstoneNull-value record for the keyLog-structured stores (Kafka, Cassandra) where deletes must propagateConsumers can be offline longer than the tombstone's lifetime
Status flagdeleted_at columnReversible user action, short grace windowAny legal erasure: the bytes are still there
BitemporalValid-time + transaction-time rowsYou must answer "what did we believe on date X"Storage cost is 2x+ and every query needs an as-of predicate
De-identificationDrop or hash direct identifiersAnalytics, model trainingYou need re-identification for support or fraud

Why tombstones beat hard delete in replicated systems. A hard delete is the absence of a record, and absence doesn't replicate: a replica that never saw the row has nothing to apply. A tombstone is a positive fact ("key K is deleted at offset N") that flows through the same log as writes, so every replica converges. Kafka's log compaction keeps that tombstone for delete.retention.ms, default 86400000 ms (24 hours), then drops it. That default is the whole failure mode: a consumer group that starts from earliest after the tombstone expired replays the original write and never learns of the delete.

Failure modes and how I'd catch them.

  • Soft-delete flag leaks. Every read path must carry WHERE deleted_at IS NULL; one missed join resurrects the row. In Postgres I'd back it with a partial index, CREATE INDEX ON users (id) WHERE deleted_at IS NULL, and detect leaks with a nightly job that counts rows where deleted_at IS NOT NULL still reachable through the API, plus a query audit for scans on the base table.
  • Tombstone expiry. Detect with consumer lag plus a reconciliation job comparing the key set in the source against the key set in the sink; a key present in the sink but absent in the source is a missed delete. Cost: you can't repair it by replay once the tombstone is gone. You need a full re-snapshot.
  • Backups. A hard delete in the primary doesn't touch the backup; a restore resurrects the data. Detect with a scheduled restore drill into an isolated environment. Cost: either expire backups on the same retention clock, or keep a suppression list applied at restore time.
  • Derived copies. Warehouse tables, feature stores and search indexes are separate systems. Detect with lineage (dbt, OpenLineage or a column-level catalog) and treat any downstream table without a lineage edge as unverified.

The retention clock is legal, not engineering. GDPR Article 12(3) gives you one month to answer an erasure request, extendable by two. HIPAA requires six years for documentation; SOX audit workpapers are seven years; PCI DSS wants twelve months of logs with the most recent three immediately available. Those numbers decide which class gets hard delete and which gets de-identification, and they're the reason "just set a flag" fails: the flag satisfies the product, not the obligation.

What I'd say if pushed. The deciding question is whether the data must be gone or merely unlinkable. Gone means hard delete plus a plan for replicas, backups and derived copies. Unlinkable means de-identification, and then the audit trail of who held the identifiers becomes the thing you have to protect.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

Evolve an Avro event with a new field.

Answer

What I'd say first

Adding a field to an Avro record is safe in both directions only when the new field carries a default in the reader schema. Avro resolves field by field: for each field in the reader schema, if the writer's schema has a field of the same name, the writer's value is used; if it doesn't, the reader's default is used. No default, no value: the decoder throws AvroTypeException naming the missing field. That happens at deserialize time in the consumer, not when you register the schema, so a bad change passes CI and takes down consumers at 3am.

State two assumptions out loud: the field really is optional for records already written, and the default is a value you're willing to live with forever.

The schema and the trace

JSON
// v1 (writer)
{"type":"record","name":"Event","namespace":"com.acme","fields":[
  {"name":"id","type":"string"},
  {"name":"amount","type":"long"}]}

// v2 (reader)
{"type":"record","name":"Event","namespace":"com.acme","fields":[
  {"name":"id","type":"string"},
  {"name":"amount","type":"long"},
  {"name":"currency","type":"string","default":"USD"}]}

Checked against Avro 1.11.x with Java GenericDatumReader/SpecificDatumReader:

  • v1 bytes read with the v2 reader → currency is "USD". The default is synthesized during resolution.
  • v2 bytes read with the v1 reader → currency is dropped silently. Unknown writer fields are ignored.
  • Delete "default":"USD" from v2 and read the same v1 bytes → AvroTypeException naming currency. Same bytes, same reader, different outcome.

That third line is the whole risk. The default is not a backfill; it is computed on every read. Change it from "USD" to "UNKNOWN" next quarter and every historical record silently changes meaning. If the value has to be truthful, backfill the topic and only then consider making the field required.

Compatibility levels

LevelMeaningThis change
BACKWARD (registry default)new schema reads data written by the previouspasses
FORWARDprevious schema reads data written by the newpasses: old reader ignores the field
FULLbothpasses
NONEno checkdon't

Gate it in CI with SchemaCompatibility.checkReaderWriterCompatibility(reader, writer) and assert the result is COMPATIBLE; the incompatibility you'll hit is READER_FIELD_MISSING_DEFAULT_VALUE. Against a registry, POST /compatibility/subjects/<subject>/versions/latest?verbose=true runs the same check before you commit.

Failure modes

  1. Missing reader default. AvroTypeException inside the consumer poll loop. With FailFast error handling the app crash-loops; with a skip handler you silently drop events. Detect via consumer error-rate metric and the exception class in logs: lag alone won't tell you.
  2. Default changed later. No error, no metric; historical records just read differently. Detect only with golden fixtures: keep a v1 byte blob in the test suite and assert the decoded currency.
  3. Generated classes. Adding a field changes the SpecificRecord all-args constructor, so downstream services that call it fail to compile. Detect in the CI build, before deploy.
  4. Union default order. {"type":["string","null"],"default":null} is rejected at parse: Avro requires the default to match the first branch. Write ["null","string"] with "default": null. This one fails fast, which is why it's the cheap mistake.
  5. Enum symbols. Adding a symbol to an enum that an old reader consumes throws unless the enum field has a reader default. Same rule, different type.

Rollout

Because the change is FULL, order doesn't strictly matter, but deploy consumers first anyway: they can read both old and new. Then producers. If you ever need FORWARD-only, invert that. Keep the subject at BACKWARD or FULL, never NONE, and pin the level per subject rather than trusting the global default.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-17

Handle a schema change that narrows numeric precision.

Answer

Let me clarify the scenario. I'll assume we're on PostgreSQL 15, and we have a table payments with a column amount NUMERIC(12,4) that we need to narrow to NUMERIC(10,2). The driver is that the upstream system now only sends two decimal places, and we want to save storage and simplify calculations. The key question is: how many rows would actually change value, and can we tolerate that?

First, profile. Run a query to count rows that would round or overflow:

SQL
SELECT
  count(*) AS total,
  count(*) FILTER (WHERE amount <> round(amount, 2)) AS would_round,
  count(*) FILTER (WHERE abs(amount) >= 100000000) AS would_overflow,
  max(abs(amount)) AS max_abs
FROM payments;

Suppose we get:

totalwould_roundwould_overflowmax_abs
10,000,00012,345 (0.12%)3123,456,789.1234

So 0.12% of rows would change value, and 3 rows would overflow the new type. That's the decision point: if would_round is more than, say, 0.1% of rows, I'd push back and widen instead of narrow, or ask upstream to keep four decimals. If it's zero, the change is trivial. Here, 0.12% is borderline, but the 3 overflow rows are a hard blocker: they must be corrected or the migration will fail.

Now, mechanism. Narrowing precision means reducing the scale (decimal places) and/or total digits. In PostgreSQL, NUMERIC(10,2) stores exactly two decimal places. When you cast a value with more decimals, PostgreSQL rounds half away from zero by default. For example, 99999999.9999 rounds to 100000000.00, which exceeds the max of NUMERIC(10,2) (99,999,999.99), causing an overflow error. Truncation would be explicit (trunc(amount, 2)), but that silently drops cents, which is worse for financial data. So we must choose rounding and handle overflow.

Trade-offs: Alternatives are (a) widen the column instead of narrowing. Keep NUMERIC(12,4) and just ignore extra decimals in the app; (b) reject the change and ask upstream to fix their format; (c) store as integer cents (BIGINT) to avoid decimal issues. Deciding criteria: if the column is used in financial calculations, rounding must be approved by finance. If the column is just a display value, narrowing is fine. If more than 0.1% of rows change, the reconciliation cost may outweigh storage savings.

Failure modes: The concrete failure is silent rounding that changes aggregate sums. For example, if we round 12,345 rows, each by up to $0.005, the total error could be up to $61.72. Detection: run a reconciliation query comparing sum(amount) before and after. Operational cost: if we don't catch it, monthly reports are off by cents, causing customer disputes. Another failure: overflow during migration causes the transaction to abort, locking the table and causing downtime. Detection: the migration script fails with numeric field overflow. Cost: rollback and retry.

Migration plan: Add a new column amount_new NUMERIC(10,2). Backfill with explicit rounding, but handle the 3 overflow rows separately: either cap them at 99,999,999.99 or move them to a payments_overflow table for manual review. Then validate: compare counts, sums, and check no data loss beyond rounding. Switch readers first: update the application to read from amount_new via a view or feature flag. Then switch writers: write to both columns, keeping amount in sync. Reconcile daily for a week. Only then drop amount and update constraints. Keep rollback: the old column and old code path remain until reconciliation passes. Finally, update schema documentation and any API contracts that promise four decimal places.

That's the core. The key is to never rely on implicit truncation, and to have a rollback plan.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

Migrate a widely used column name.

Answer

Core answer (first 90 seconds)

Assume Postgres 15+, an orders table around 400M rows, and consumers you don't fully control: application code, a BI tool, a nightly extract, and an ORM. First decide whether the name changes or the meaning changes. If user_id becomes customer_id and it's the same identifier, it's a rename. If it now means "billing account", it's a new field and the old one stays until it's dead: aliasing a changed meaning is how you ship a silent data bug.

For a pure rename, don't ALTER TABLE orders RENAME COLUMN user_id TO customer_id in place and hope. That's metadata-only and takes an ACCESS EXCLUSIVE lock for milliseconds, but it breaks every consumer that names the old column the moment it commits: column "user_id" does not exist, SQLSTATE 42703, in production. Use expand-and-contract so both names exist at once.

The mechanism

  1. Add: ALTER TABLE orders ADD COLUMN customer_id bigint;. Nullable, no table rewrite, fast.
  2. Backfill in batches, then install a trigger so writes that still use the old name keep both columns in sync.
  3. Migrate readers and writers to customer_id.
  4. Contract: drop the trigger, then drop user_id.

Trade-offs

approachconsumer changewindowmain risk
rename in place + compatibility viewmust repoint the FROM clauseshortview must be auto-updatable; breaks positional SELECT * readers
expand-and-contractnone until contractlongtrigger overhead, drift between the two columns
big-bang rename in a maintenance windowall at onceminutesany missed consumer is a hard outage

Deciding criterion: if you can enumerate and redeploy every consumer in one window, big-bang is fine. If any consumer is a BI tool or a partner extract you can't redeploy on demand, expand-and-contract is the only safe path.

Failure modes and how you detect them

  • Stale extract: the nightly job wrote a file before the backfill finished. Detect with SELECT count(*) FROM orders WHERE customer_id IS DISTINCT FROM user_id;: it must be 0 before you contract.
  • Cached prepared statement or ORM model: fails with 42703. Detect with an error-rate alert on that SQLSTATE.
  • Silent default: a writer only sets user_id, leaving customer_id NULL. Same parity query catches it; add NOT NULL only after parity holds.
  • Positional SELECT * binding: column order shifts under drivers that bind by position. Detect with a schema diff in CI.

Artefact: the sync trigger

SQL
CREATE OR REPLACE FUNCTION sync_order_ids() RETURNS trigger AS $$
BEGIN
  IF NEW.customer_id IS NULL THEN NEW.customer_id := NEW.user_id; END IF;
  IF NEW.user_id IS NULL THEN NEW.user_id := NEW.customer_id; END IF;
  RETURN NEW;
END $$ LANGUAGE plpgsql;

CREATE TRIGGER orders_sync_ids BEFORE INSERT OR UPDATE ON orders
  FOR EACH ROW EXECUTE FUNCTION sync_order_ids();

Backfill with UPDATE orders SET customer_id = user_id WHERE customer_id IS NULL; in batches of 10,000 keyed by primary key. 400M rows / 10k = 40,000 batches; at roughly 5 ms per commit that's ~200 s of commit time, realistically 1–2 h once trigger overhead is included (hypothetical figures for this table size). Announce the retirement date, watch pg_stat_statements for any query text still naming user_id, and only then drop the column in a controlled change with a rollback plan and an updated catalogue.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

Review a tabular exchange contract.

Answer

Assumptions I'd state before reviewing anything. Who reads the file, and whether it's a one-shot handoff or an archive. If a human opens it in Excel, you're stuck with CSV and its locale traps. If it's machine-to-machine and read repeatedly, a typed format pays for itself. And: is the producer allowed to add columns after the first delivery? That single answer decides half the review.

The core answer. A tabular exchange contract is a specification of the decode path: bytes → characters → fields → rows → columns → values → meaning. Review it by walking that path in order and asking, at each stage, whether the choice is written down, whether it matches the default the other side will assume, and what happens when the two disagree. A stage left to "whatever the library does" is not a contract.

StagePin it toWhat breaks when it's unstated
bytesUTF-8, explicit BOM policyExcel writes EF BB BF; a parser that doesn't strip it sees the header \ufeffid, and every row["id"] is a KeyError
charactersstrict decode, no replacementLatin-1 é (0xE9) decoded as UTF-8 becomes U+FFFD; the value changes silently
fieldsRFC 4180: comma, " quote, "" escape, CRLFGerman-locale Excel writes ; and comma decimals; a comma-splitting reader shifts every column
rowsquoted fields may contain CR/LFan unquoted newline splits one record into two
columnsorder, names, types, null markerCSV has no null; empty string and missing are the same byte
valuesdecimal as string or scaled integer, ISO 8601 with offset0.1 + 0.2 is 0.30000000000000004 in binary64
meaningunits, code sets, grain, keys"amount" in cents vs dollars

That's the whole review in one pass. The two checks that catch most real breakage, in Python 3.12 stdlib:

Python
import csv, io

raw = open("export.csv", "rb").read()
if raw.startswith(b"\xef\xbb\xbf"):      # UTF-8 BOM
    raw = raw[3:]
text = raw.decode("utf-8")                # strict: raises on bad bytes
rows = csv.reader(io.StringIO(text), delimiter=",", quotechar='"', strict=True)
header = next(rows)
for n, row in enumerate(rows, start=2):
    if len(row) != len(header):
        raise ValueError(f"line {n}: {len(row)} fields, header has {len(header)}")

Strict decode plus the field-count assertion is the highest-yield pair here. Fail the load; never pad a short row.

The format choice, and when not to use CSV. CSV is universal and human-readable, and has no types, no null, no nesting, and no schema: every consumer re-guesses. Parquet is typed and self-describing (schema in the footer), columnar, so reading 2 of 10 columns skips the rest, and compresses well; it's binary, needs a library, and its evolution rules (add with a default, never rename) are the contract. Avro is row-oriented with the writer schema embedded, which suits a stream of whole records whose schema moves. Decide on the consumer: a human or Excel in the loop means CSV and you accept the locale traps; machine-only and read repeatedly means Parquet; record-at-a-time streaming means Avro. If you must stay in CSV but want types and nulls declared, use CSVW (W3C Recommendation, 2015): schema, datatypes and null markers in a sidecar JSON-LD file. That's a decision, not a hedge.

Failure modes and how you'd catch each. A column shift from an unquoted delimiter: assert field count per row against the header, fail the load. A BOM: check the first three bytes. Encoding drift: decode strict and alert on UnicodeDecodeError; treat any U+FFFD count above zero as a defect. Decimal drift: reconcile the sum against the source with zero tolerance on a decimal type. DST: 2024-03-10T02:30:00 in America/New_York does not exist; a naive parser rolls it to 03:30 and you've moved an event an hour. Schema evolution: a positional reader breaks when a column is inserted, so run the pinned old reader against the new file in CI as a contract test.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-18

Design lineage standards across batch and streaming jobs.

Answer

What I'd say first

Before designing anything I'd pin down three things: how many engines actually produce data (one warehouse, or Spark plus Kafka plus a warehouse), whether a catalog already exists, and whether anyone needs column-level lineage or table-level is enough. Those three answers decide how much of a spec you implement.

My default is to emit lineage as immutable events shaped like the OpenLineage spec, from the orchestrator and from each compute engine, and let a collector build the graph. I would not hand-roll a schema, and I would not let each team invent its own.

The event model is the design

Every event is a RunEvent: eventType (START, RUNNING, COMPLETE, FAIL, ABORT), eventTime, a job with namespace and name, a run with a runId, and inputs/outputs as datasets, each with namespace and name. Every event also carries _producer and _schemaURL, so a consumer knows who wrote it and which spec definition to validate against.

Two fields carry the weight. runId is per execution, not per job: a retry gets a fresh runId, so a retry is a new node rather than a duplicate edge. The parent facet links a task run to its DAG run, which is how a batch job's tasks stitch into one logical run.

JSON
{
  "eventType": "COMPLETE",
  "eventTime": "2024-05-01T02:14:07Z",
  "run":     {"runId": "0f3a9c1e-..."},
  "job":     {"namespace": "airflow://prod", "name": "daily_orders"},
  "inputs":  [{"namespace": "snowflake://acct", "name": "RAW.ORDERS"}],
  "outputs": [{"namespace": "snowflake://acct", "name": "MART.ORDERS_DAILY"}],
  "facets": {
    "parent": {
      "run": {"runId": "b71d4a02-..."},
      "job": {"namespace": "airflow://prod", "name": "orders_dag"}
    }
  },
  "_producer": "https://github.com/OpenLineage/OpenLineage"
}

Batch and streaming diverge on three points:

decisionbatchstreaming
run identityone runId per scheduled run; retry = new runId, same nominalTimeone runId per job start, long-lived
completionCOMPLETE or FAIL closes the runno COMPLETE until stop; emit periodic checkpoint events
backfill / replayN runs, one per interval, parent = the original runreplay from a checkpoint offset, new runId, parent = original

Trade-offs

Vendor-native lineage wins when you are single-vendor, need only table- or column-level lineage inside that one warehouse, and want zero emission work: it is free and maintained for you. It stops winning the moment a Spark job writes into that warehouse, because the vendor cannot see upstream of its own boundary. The cost of the spec path is that you own an emitter per engine, you own schema drift when the spec revs, and you own the collector as a production service, and lineage going dark is silent, nothing fails when it stops. Column-level facets carry SQL text and column names, so they need the same access control as the data they describe, plus a retention window long enough to answer "what changed last quarter."

Failure modes and how you catch them

  • Silent emission gap: the job runs, no events arrive. Detect by comparing orchestrator task-instance counts to lineage run counts per hour and alerting below a 0.99 ratio. Cost: impact analysis under-reports, so a schema change ships and breaks a downstream nobody could see.
  • Retry collapse: the same runId reused across retries. Detect two COMPLETE events for one runId. The graph shows one success where there were three attempts.
  • Logical vs physical collision: a view and its backing table share a name in one namespace. Detect two datasets with identical namespace+name and different facets. Downstream impact double-counts.
  • Backfill burst: a 30-day hourly backfill is 720 runs; at START+COMPLETE over ~10 datasets each, that is roughly 14,400 events. If the collector ingests 50 events/s, that is about five minutes of lag: detect on collector ingest lag, not on job failure.
  • Streaming restart: the job resumes from a checkpoint, emits a new runId with no parent, and the chain breaks. Detect runs whose inputs have no producing run.

What would change my answer

Single vendor, table-level only: skip the emitter and use native lineage. Cross-engine, or column-level needed: spec-shaped events, and budget the collector as a production service with its own SLO.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

How do you standardize the classification and tagging of sensitive data (PII/PHI) inside the data model so masking and access rules can be applied consistently?

Answer

A strong candidate opens by saying the classification must live in the model artifact itself (DDL, Avro schema, Parquet metadata) not in a separate wiki or catalog that drifts. Then a policy engine reads those tags at deploy time and generates masking views, column grants, and row-level security policies deterministically.

1. Controlled vocabulary. Define a small, closed set of sensitivity labels. Example:

LabelRegulatoryExample columnMasking ruleAccess role
publicnoneproduct_namenoneall
internalnonecost_centernoneemployees
confidentialnonesalary_bandnonehr
piiGDPR/CCPAemail, ssnhash or redactapp_service
phiHIPAAdiagnosis_coderedactclinical

2. Tagging in the model. In PostgreSQL, attach tags as structured comments on columns. The lexical rules for identifiers (unquoted fold to lower case, 63-byte limit) mean you should use a stable prefix like class:.

sql COMMENT ON COLUMN patients.email IS 'class:pii;mask:sha256'; COMMENT ON COLUMN patients.diagnosis IS 'class:phi;mask:redact';

For Avro, use custom schema properties ("class": "pii"). For Parquet, key-value metadata. For datasets, DCAT 3 dct:accessRights and dcat:theme. OpenLineage facets carry the same tags to downstream jobs.

3. Generate enforcement. A CI step parses the model, reads tags, and emits a masking view plus grants. Example generated view:

sql CREATE VIEW patients_masked AS SELECT patient_id, CASE WHEN current_user IN ('app_service') THEN email ELSE encode(digest(email, 'sha256'), 'hex') END AS email, CASE WHEN current_user IN ('clinical') THEN diagnosis ELSE 'REDACTED' END AS diagnosis FROM patients; REVOKE ALL ON patients FROM PUBLIC; GRANT SELECT ON patients_masked TO app_service, clinical;

Row-level security can filter rows by tenant or consent. Column-level grants (GRANT SELECT (patient_id, email) ON patients TO app_service) are an alternative when views are too costly.

4. Consistency checks. CI fails if any column tagged pii or phi lacks a mask rule, or if a base table still grants SELECT to a role that should see only masked data. A sampling scanner (regex for SSN, email) catches untagged columns. OpenLineage lineage shows where tags propagate to derived tables.

5. Failure modes. Tag drift: a column is added without a tag, so it leaks. Detect by comparing schema to tag registry in CI. Bypass: masking view exists but base table grants remain. Detect by querying information_schema.role_table_grants. Over-masking: hashing email breaks joins; use deterministic hashing with a salt per tenant. PHI requires audit logging of every unmasked access.

When not to use: a single-team, non-regulated dataset with no external consumers can rely on database roles alone. But once data is shared, in-model tagging is the only way to keep masking and access rules consistent across engines.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

How do enterprise semantic layer standards reconcile differences between physical storage schemas and business domain definitions?

Answer

Assume an enterprise environment where downstream consumers query business entities like CustomerOrder and DailyNetRevenue, while upstream teams persist data across PostgreSQL transactional databases and Apache Parquet analytical lakes. The physical tier optimizes for ingestion throughput, write isolation, and compression; the domain model optimizes for consistent business metrics and identity stability.

Reconciliation succeeds by standardizing three translation mechanisms rather than copying data into a single monolithic schema: type coercion, grain-preserving joins, and identifier binding.

1. Primitive Typing vs. Domain-Bounded Types

Physical storage often stores business concepts in generic primitives. A Parquet file might store timestamps as an INT64 number of microseconds without timezone context, or monetary values as FLOAT8 or integer cents. PostgreSQL might store money as raw NUMERIC(12, 2) or untyped strings.

The semantic standard enforces typed logical contracts:

  • Temporal: Mapping integer epoch counts directly to logical UTC timestamps using the Parquet logical type annotation TIMESTAMP(isAdjustedToUTC=true, unit=MICROS), rejecting unanchored wall-clock strings.
  • Money: Defining whether currency is an explicit composite (scale + ISO currency code) or a fixed minor-unit integer. For reporting, NUMERIC types are mandated, but high-throughput streaming systems often negotiate keeping integer minor units in transit to avoid serialization overhead.

2. Grain Mismatch and Fan-Out Prevention

A central failure mode occurs when joining a physical parent entity (an order with total_amount = $100) to child items (three line items) to slice by product category. Summing total_amount naively after the join yields $300.

To prevent this fan-out without breaking query flexibility, the standard enforces one of two architectural patterns:

  • Push-down pre-aggregation: Child tables aggregate to the parent primary key grain in a derived table or common table expression (CTE) before the join occurs.
  • Symmetric aggregation: The query compilation engine tracks primary keys from the parent relation and divides or weights measures by the multiplicity factor of the join, or calculates the measure over an analytical window partitioned by the parent primary key (AVG(o.total_amount) OVER (PARTITION BY o.order_id)).

SUM(DISTINCT amount) is explicitly forbidden because two distinct valid orders of $100 would be collapsed into one $100 sum.

3. Trade-offs and Alternatives

ApproachLatency / ComputeGovernance / FlexibilityTrade-off / Deciding Factor
Declarative Semantic Layer EngineCompiles on-demand SQL with push-down logicCentralized metric definitions; isolates consumers from DDL changesHigh query generation complexity; requires rigorous join path graphs
Physical Conformed Marts (ELT / dbt)Pre-computed, materialized tables with fixed grainsPredictable scan performance; simple consumer SQLHigh storage duplication; schema changes force full backfills
Strict RDBMS ViewsComputed at read time via database catalogMinimal moving parts; uses native DB constraintsPoor cross-system portability; degrades under high-cardinality joins

Failure Modes

  • Silent Fan-out: Cross joins or unconstrained dimension joins inflate metrics. Detection: Automated semantic reconciliation tests that compare domain metric aggregations against parent-table source totals. If SUM(metric) across an unjoined table diverges from the joined semantic model, CI blocks the mapping change.
  • Missing Dimension Keys (NULL vs. Sentinel): Physical outer joins leave missing dimension keys as NULL. If consumers run COUNT(customer_id), they miss unassigned orders. The standard decides whether the semantic compiler injects a COALESCE with an explicit sentinel key (-1 or 'UNKNOWN') or surfaces genuine NULL semantics, balancing referential integrity against standard SQL NULL propagation rules.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

How do automated linters and CI/CD validation rules verify naming conventions and surrogate key standards in data models?

Answer

The 90-second version. Validation runs in three layers, and the layer decides what can be proven. A static linter parses model source (SQL DDL, dbt model SQL, contract YAML) into an AST and asserts naming rules without executing anything. A contract validator checks the declared schema: exactly one surrogate key, right name, right type. Neither proves a constraint exists in the database, because DDL text and the resulting schema diverge: a later migration adds the column without the constraint, or a Jinja macro emits it at compile time. Only applying migrations to a throwaway database and querying pg_catalog proves NOT NULL and PRIMARY KEY. Uniqueness across rows is a fourth check, run as a data test.

Naming. The linter walks the parse tree instead of grepping text, so identifiers inside string literals and comments don't produce false positives. Rules worth enforcing:

  • ^[a-z][a-z0-9_]*$. Not cosmetic in PostgreSQL: unquoted identifiers fold to lower case, so Customer_ID in DDL becomes customer_id, and a later query written as "Customer_ID" fails. CREATE TABLE t (customer_id int, Customer_ID int) errors with column "customer_id" specified more than once: the fold happens before the duplicate check.
  • Byte length ≤ 63 (NAMEDATALEN - 1). PostgreSQL truncates silently, so two columns differing only past byte 63 collide at creation and fail at query time. Count bytes, not characters.
  • Reserved words (order, group, user) rejected as unquoted identifiers: SQLFluff L029.
  • Taxonomy: layer prefixes (stg_, dim_, fct_), temporal suffixes (_at for a UTC instant, _date for a calendar day), boolean predicates (is_, has_).

Surrogate keys. Exactly one per entity model, named <entity>_sk matching the table basename (dim_customer → customer_sk); fixed-width type (BIGINT identity, or UUID/CHAR(32) for deterministic hashes); declared NOT NULL plus PRIMARY KEY or UNIQUE; and a uniqueness test that actually runs.

Python
import re, sqlglot
from sqlglot import exp

SNAKE = re.compile(r"^[a-z][a-z0-9_]*$")
RESERVED = {"order", "group", "user", "select", "from", "where", "table"}

def check(sql: str, table: str) -> list[str]:
    tree = sqlglot.parse_one(sql, read="postgres")
    out = []
    for col in tree.find_all(exp.ColumnDef):
        n = col.name
        if not SNAKE.match(n):
            out.append(f"{table}.{n}: not snake_case")
        if len(n.encode()) > 63:
            out.append(f"{table}.{n}: {len(n.encode())} bytes > 63")
        if n in RESERVED:
            out.append(f"{table}.{n}: reserved word")
        if col.kind and col.kind.this == exp.DataType.Type.BOOLEAN \
           and not n.startswith(("is_", "has_")):
            out.append(f"{table}.{n}: boolean needs is_/has_ prefix")
    return out

Trace it on:

SQL
CREATE TABLE dim_customer (
  Customer_ID BIGINT NOT NULL PRIMARY KEY,
  is_active   BOOLEAN,
  created_at  TIMESTAMPTZ
);

parse_one returns a Create node; find_all(exp.ColumnDef) yields three ColumnDefs in source order. Customer_ID fails SNAKE (uppercase C, I): 11 bytes, not reserved, BIGINT so no boolean check. is_active matches and starts with is_. created_at matches, TIMESTAMPTZ is not boolean. Output: ['dim_customer.Customer_ID: not snake_case']. sqlglot preserves the identifier's source text rather than folding it, which is what you want: the linter's job is to catch the fold before Postgres does.

For the constraint itself, run this against the ephemeral database after applying migrations:

SQL
SELECT count(*) AS ok
FROM pg_index i
JOIN pg_class c ON c.oid = i.indrelid
JOIN pg_attribute a ON a.attrelid = c.oid AND a.attnum = ANY (i.indkey)
WHERE c.relname = 'dim_customer'
  AND i.indisprimary
  AND a.attname = 'customer_sk'
  AND a.attnotnull;

It returns 1 when customer_sk is the primary key and NOT NULL; the job fails on anything else.

LayerReadsProvesCost (illustrative)
AST lintermodel sourcenaming, reserved words, byte length< 5 s
Contract validatordbt contract YAML / JSON Schemakey declared, name, type5–15 s
Ephemeral DB + catalog queryapplied migrationsNOT NULL, PRIMARY KEY, stored type30–90 s
Data testsrowsuniqueness and non-null in practiceminutes

Where it breaks. Linting the Jinja source instead of compiled SQL: a {% for %} loop that emits columns is invisible. Lint target/compiled/. Declaring dbt tests in YAML but running only dbt parse in CI: the tests exist and never execute (model contracts landed in dbt-core 1.5). CREATE TABLE ... (LIKE other) and ALTER TABLE ... ADD COLUMN bypass CREATE-time checks; the catalog query catches them, the AST linter does not. Waivers without expiry: one allowlist entry for a legacy table becomes permanent. Require an owner and a date.

Trade-off. Strictness costs merge velocity, and a rule that fires on 200 legacy columns gets disabled wholesale. Scope new rules to changed files (git diff against the base branch) rather than the whole repo.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

Evaluate whether to mandate one enterprise data model.

Answer

Position. No: don't mandate one physical enterprise data model. Mandate a thin conformance layer: shared identifiers, reference codes, and versioned exchange contracts. Let each domain own its physical tables. Assumptions: more than one domain with its own release cadence, no regulator dictating a single reporting schema, and a catalog already in place.

Why a single canonical model bottlenecks. The cost isn't the modelling, it's the change path. In a mandated model every schema change is a cross-domain change, so it enters one review queue owned by one team. If that team ships monthly and 12 requests are open, a domain that needs one nullable column waits a quarter. Coupling also drags toward the lowest common denominator: the canonical customer entity keeps only attributes every domain agrees on, so domain-specific fields get dropped and re-added as local extensions. The shadow model you were trying to prevent.

What to mandate instead.

  • Identifiers and codes: ISO 3166-1 alpha-2 for country, ISO 4217 for currency, ISO 8601 for timestamps, and one surrogate key per core entity issued by a registry.
  • Exchange contracts: Avro or Protobuf schemas in a registry (Confluent Schema Registry's default compatibility level is BACKWARD), with Protobuf field numbers reserved on removal so they can't be reused.
  • Conformed dimensions only where a join actually crosses domains (Kimball), not everywhere.
  • Governance: domain ownership, a published mapping per interface, and exceptions carrying an owner and an expiry date.

Artefact 1: mapping arithmetic. Without a hub, N domains need N(N−1)/2 pairwise mappings. With a conformed hub, N. At 30 domains that's 435 versus 30. That is the argument for conformed identifiers, and equally the argument against making the hub carry every attribute.

Artefact 2: change trace. A domain needs customer.loyalty_tier.

  • Mandated canonical: request → central review → canonical schema change → 29 downstream consumers re-validated → release. Lead time in weeks; blast radius 30 teams.
  • Conformance layer: domain adds the column to its own table, publishes a new Avro schema version (BACKWARD-compatible, so existing consumers keep reading), updates the mapping. Lead time in days; blast radius 1 team.

Failure modes and detection.

  • Central change queue: track lead time from change request to production and the age of the oldest open request. If p50 exceeds one release cycle, the model is the bottleneck.
  • Shadow mappings: search the catalog (DataHub, OpenMetadata) for tables matching the canonical entity name. More than one writer per entity means the canonical model isn't canonical.
  • Silent drift: run dbt relationships and accepted_values tests, or Great Expectations suites, against the exchange contracts on every publish.

What would change my decision. A regulator requiring one reporting schema (BCBS 239-style risk aggregation, IFRS 17) or a single team owning all data flips it: then one physical model is cheaper than the mapping layer.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

Evaluate whether a data model is standard-ready.

Answer

Core answer (first 90 seconds). "Standard-ready" isn't a formal term, so I'd pin it down before answering: the model is fit to be the organization's canonical definition. Other teams build on it, and its guarantees hold without a human checking. I'd assume a warehouse or lakehouse target (Snowflake, BigQuery, Iceberg) and at least two downstream consumers. My answer: a model is standard-ready when its guarantees are enforced by the platform or by automated tests, not written in a wiki. Three gates decide it (identity and grain, semantics, evolution) and failing any one makes it a draft, not a standard.

Gate 1: identity and grain. Every row is uniquely identifiable and the grain fits in one sentence. Check it mechanically: a uniqueness test on the declared key over full history, not a sample. In dbt that's unique + not_null on the key (dbt-core 1.8 also runs unit tests against the model). If the key is natural, ask what happens when the source reuses it. Surrogate bigint keys are the safer standard: they don't change and don't leak PII.

Gate 2: semantics. Types, units, precision, time. Money is never a float. IEEE-754 doubles hold ~15–17 significant decimal digits, and 0.1 + 0.2 = 0.3 evaluates to false; 3 * 0.1 is 0.30000000000000004. Rounding each line item then summing gives a different invoice total than summing then rounding, and that difference is cents per invoice. Use integer minor units or NUMERIC(38,9). Timestamps are UTC, timestamptz in Postgres (1 µs resolution) or an explicit _utc suffix, with the source zone in its own column when it matters. Nulls are a state, not an absence.

Gate 3: evolution. Declare a compatibility mode. Confluent Schema Registry defaults to BACKWARD (new schema reads old data); FULL is the right bar for a shared standard. In Protobuf, field numbers 1–15 cost one tag byte and 16–2047 cost two, and 19000–19999 are reserved, so reserve low numbers for hot fields and never renumber. Deprecate columns with a window; don't drop them.

Trade-offs. 3NF vs star: 3NF minimizes update anomalies, but every analytical query pays joins; a star with conformed dimensions wins for a shared analytical standard. Enforced FKs vs informational: Postgres enforces them and pays write cost plus load-ordering pain; BigQuery and Snowflake declare primary and foreign keys but do not enforce them, so the guarantee has to come from tests. Soft delete vs hard delete: soft delete preserves history but every consumer must filter, and GDPR erasure needs hard delete or crypto-shredding. Decide by consumer count and regulatory scope, not taste.

Failure modes. Join fan-out on a non-unique key double-counts revenue: detect by reconciling SUM(amount) and row counts before and after the join. Timezone drift shifts a daily aggregate by hours: assert min/max timestamps are UTC and monotonic. A dropped column breaks consumers silently: catch it with a contract test in CI.

Worked check: the NOT IN null trap.

SQL
SELECT count(*) FROM orders o
WHERE o.customer_id NOT IN (SELECT c.id FROM customers c);

Trace: NOT IN expands to o.customer_id <> c.id for every customer row. If any c.id is NULL, that comparison is UNKNOWN; TRUE AND UNKNOWN is UNKNOWN, never TRUE, so no order qualifies and the query returns 0: a silent empty result, not an error. The correct count is the orders with a non-null customer_id that match no customer. Fix: NOT EXISTS, or filter NULLs in the subquery.

CheckMechanismFailure it catches
Grainunique + not_null on the declared key, full historyDuplicate rows inflating counts
MoneyAssert NUMERIC/integer minor units, never floatCent drift, order-dependent sums
TimeAssert UTC, timestamptz or _utc suffixDaily aggregates shifted by hours
NullsNOT EXISTS over NOT IN; null-rate test per columnSilent empty result sets
EvolutionRegistry FULL compatibility; reserved field numbersConsumer breakage on deploy
ConstraintsContract test in CI; PK/FK unenforced in BigQuery/SnowflakeOrphan rows, broken joins

Approval means those guarantees are enforced and testable, not that the diagram looks normalized.

Curated: · Written: · Reviewed:

Difficulty: Hard