download

Upstream sent 40% NULL currencies. How do you block bad loads?

Data engineering~11 minReviewed 3 Dec 2026Free · No sign-in

Question

Your daily daily_orders job exited 0 and published 2026-12-02 straight to prod. Normally each day loads 10,000 rows within 120 minutes of event time. Today an upstream bug slipped past schema checks with four problems:

  • Volume dropped 65% to 3,500 rows (allowed band: 7,000 to 13,000).
  • ccy (currency) is NULL on 40% of rows (1,400 of 3,500; max allowed 1%).
  • 1 duplicate order ID (oid=1) appeared twice.
  • Newest row lag is 300 minutes (max allowed 120).
  1. Why did schema checks and a zero exit code miss these bugs?
  2. Implement a Write-Audit-Publish (WAP) gate on stg that blocks all four failures before touching prod.
"CODE · PYTHON"
def publish_day(db, day):
    # Bug: promotes staging rows straight to prod with zero audits
    with db:
        db.execute("DELETE FROM prod WHERE day = ?", (day,))
        db.execute("INSERT INTO prod SELECT day, oid, ccy FROM stg")
Show hints (3)
  1. "SCHEMA VERSUS DATA"

    If ccy is nullable and oid has no unique index in staging, a 65% row drop and 40% NULLs are still valid SQL types, so the job exits 0.

  2. "AUDIT BEFORE SWAP"

    Run one aggregate query over stg for COUNT(*), COUNT(DISTINCT oid), SUM(ccy IS NULL), and MIN(lag_m) before touching prod.

  3. "PROTECT LIVE READERS"

    When any check fails, skip the swap, keep yesterday's prod intact, alert on-call, and keep stg around for debugging.

Show checked explanation

Type checks pass because NULL strings, missing rows, stale timestamps, and duplicate IDs in an unindexed staging table are valid SQL values. Use Write-Audit-Publish (WAP): load 2026-12-02 into stg, audit volume, NULL share, key uniqueness, and freshness, and swap into prod inside one transaction only if every gate passes.

"SOLUTION · PYTHON"
import sqlite3

db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE prod (day TEXT, oid INT PRIMARY KEY, ccy TEXT)")
db.execute("CREATE TABLE stg (day TEXT, oid INT, ccy TEXT, lag_m INT)")
rows = [(i or 1, None if i < 1400 else "USD", 300) for i in range(3500)]
db.executemany("INSERT INTO stg VALUES ('2026-12-02', ?, ?, ?)", rows)
n, u, nl, lag = db.execute(
    "SELECT COUNT(*), COUNT(DISTINCT oid), COALESCE(SUM(ccy IS NULL), 0),"
    " MIN(lag_m) FROM stg").fetchone()
bad = [m for fail, m in [
    (not 7000 <= n <= 13000, f"vol={n}"),
    (n > 0 and nl / max(n, 1) > 0.01, f"null={nl / max(n, 1):.0%}"),
    (u != n, f"dups={n - u}"), (lag is None or lag > 120, f"lag={lag}m")
] if fail]
if not bad:
    with db:
        db.execute("DELETE FROM prod WHERE day = ?", ("2026-12-02",))
        db.execute("INSERT INTO prod SELECT day, oid, ccy FROM stg")
print("BLOCKED: " + ", ".join(bad) if bad else f"PUBLISHED: {n}")
"OUTPUT"
BLOCKED: vol=3500, null=40%, dups=1, lag=300m

Author-checked on CPython 3.12.10 and SQLite 3.49.1: ran the WAP gate against the 3,500-row broken batch (40% NULL currency, 65% drop, duplicate key, 300m lag), confirmed prod stayed untouched, and tested promotion of a clean 10,000-row batch. Checked by an editor other than the author.

Walkthrough

A green pipeline run only proves your SQL parsed and did not crash. It does not prove the upstream data is complete, fresh, or unique. If ccy is nullable, 40% NULLs still satisfy the column type, and dashboards quietly drop 40% of revenue from currency groupings.

Write-Audit-Publish (WAP) isolates bad loads before anyone queries them:

  1. Write: Load the candidate partition into an isolated staging table (or an Apache Iceberg audit branch via spark.wap.branch) invisible to production readers.
  2. Audit: Run automated quality gates against the staged data in one pass:
GateRule for daily_ordersToday's batchResult
Volume7,000 to 13,000 (+/-30% of 10k)3,500 (-65%)Fail
Null rateccy IS NULL <= 1%1,400 / 3,500 (40%)Fail
UniquenessCOUNT(DISTINCT oid) = COUNT(*)3,499 vs 3,500 (1 dup)Fail
FreshnessMIN(lag_m) <= 120 min300 minFail
  1. Publish (or Hold): Only when bad is empty do you swap the staged partition into prod atomically (one SQL transaction or fast_forward in Iceberg). When any hard gate fails, prod stays untouched, on-call receives an alert naming every failed check, and stg stays available for inspection.

Notice lag is None or lag > 120 instead of not lag: a completely fresh batch with lag = 0 minutes must pass, while an empty table (MIN(lag_m) = NULL) must fail.

Common mistakes

  • Running data quality checks after publishing to prod. Finance dashboards and downstream ML jobs already consumed the 40% NULL partition before alerts fired.
  • Hardcoding one fixed volume threshold forever without accounting for weekends or holidays, which causes noisy false pages that teams start ignoring.
  • Adding NOT NULL only in docs instead of enforcing NOT NULL and PRIMARY KEY constraints in the database alongside pipeline checks.
  • Dropping or truncating stg on failure, erasing the exact broken rows engineers need to diagnose the upstream regression.

Follow-up questions

  • "Which quality checks should block publishing versus only send a warning?" Block publishing (hard gates) on severe defects: duplicate primary keys, broken freshness, extreme volume drops, or NULL spikes on key money fields. Use warning-only alerts (soft gates) for softer distribution drift, like a 12% shift in average order size.
  • "How do you implement WAP on a large lakehouse table without copying terabytes twice?" Use Apache Iceberg branches (CREATE BRANCH audit and spark.wap.branch). You write Parquet files once to the audit branch, run your SQL checks against that branch, and run a metadata-only fast_forward to publish onto main atomically.
  • "What if only 5 rows out of 10,000 have a NULL currency while 9,995 are clean?" Five rows is 0.05%, inside the 1% threshold. Route those 5 defective rows to a quarantine table with a warning alert so the clean 9,995 rows publish on time, while still blocking any mass break like 40% NULLs.

What a strong answer covers

Explains why valid SQL types still allow silent corruption. Uses Write-Audit-Publish to check volume bounds, NULL thresholds, primary-key uniqueness, and freshness in staging before an atomic swap, keeping prod clean and stg intact on failure.

Open in interactive practice deck →

Original OfferVibe question. Apache Iceberg: Branching and Tagging · Apache Iceberg: Spark Branching DDL · PostgreSQL: Constraints · SQLite: CREATE TABLE.
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.