Medallion Quarantine and Replay: Failed-Row Recovery Without Duplicates
Quarantine poison rows with source identity and deterministic batch IDs, then replay corrected data with exactly-one target outcome checks per batch.
Author: jackey.ye | Updated: 2026-11-26
Quarantine retains every rejected row with its source identity, failed rule and batch lineage so a corrected replay can restore it exactly once per business key. This tutorial covers poison-row handling at the silver boundary: deterministic batch IDs, deduplicated replay, and per-batch outcome checks. It does not claim universal exactly-once delivery.
What Is Quarantine in a Medallion Pipeline, and How Is It Different From Dropping Data?
Quarantine is durable retention of a row that failed validation, stored with its source identity, failure reason and batch lineage so it can be corrected and replayed. Dropping discards the row and destroys the evidence recovery depends on. The distinction matters at the silver boundary, where cleansing, deduplication and validation happen; bronze should land data as received rather than coerce it, because a bad cast at ingest removes the original value that replay would need.
Silent coercion is the third behavior and the most dangerous, because it looks like success. A narrowed type, a nullability change or an unrecognized enum symbol gets cast to a default, the pipeline reports green, and the wrong value enters silver with no record that anything failed. The table below compares the three responses on the properties that determine whether recovery is possible.
Property | Quarantine | Drop | Silent coercion |
|---|---|---|---|
What is retained | The rejected row, verbatim, plus failure metadata | Nothing | The coerced value only |
Traceability to source | Source object and row locator preserved | Lost | Lost; original value overwritten |
Replayability | Yes, after the rule is corrected | No | No; nothing marks the row as suspect |
Audit evidence | Failed rule ID, reason, batch ID and rule version | None | None, and the pipeline reports success |
Typical failure mode | A queue nobody drains | Silent data loss | Wrong values that pass every check |
Quarantine is not free: it adds a table, an owner and a replay obligation. The failure mode to watch is a quarantine table nobody drains. Treat unresolved quarantine volume as an operational metric with a threshold, not a graveyard. For how layer boundaries and promotion gates fit together, the medallion implementation checklist hub covers the surrounding acceptance checks.
What Must a Quarantine Record Contain to Make Replay Traceable?
A quarantine record must carry enough to find the original row, reproduce the failure and link the eventual replay to the batch that produced it. Ten fields do that work:
Source system and source object — the connector and the table, topic or file path. Without them, a replay cannot be scoped to one producer.
Source row locator — file path plus byte offset, or the source primary key. This is what lets you re-read the exact row rather than the whole partition.
Ingestion timestamp in UTC — the instant the row landed, not the instant it failed. Local timestamps make cross-region incidents hard to order.
Raw payload, verbatim — the value as received, before any cast. A coerced value cannot be re-validated against a corrected rule.
Failed rule ID and human-readable reason — the machine key for aggregation and the sentence an on-call engineer reads at 02:00.
Contract or schema version — which version of the source contract the row claimed to satisfy. During a migration window several versions arrive at once.
Deterministic batch ID — the join key between the quarantine row and the replay commit.
Rule version applied — so a later reader knows which logic rejected the row.
Replay status and replay batch ID — null until replayed, then populated.
Numeric transform version — a monotonic number, not a label. The merge compares it alongside the source version so a logic-only fix isn't skipped as a no-op.
Omitting the raw payload is the costliest mistake. If bronze coerces types on ingest, a bad cast destroys the evidence replay depends on, and no downstream fix recovers it. Omitting the contract version is the second costliest: a row rejected under version 3 may be perfectly valid under version 4, and without the version you cannot tell whether the fix belongs in the data or the contract.
The failure-reason taxonomy should map to schema-change classes rather than free text. Narrowed types, nullable-to-required changes, dropped fields, renamed fields and changed enum symbols each imply a different correction path and a different owner. The schema evolution guide on versioned contracts and replay sets out which of these are additive and which require a coordinated release, and it makes the same point about quarantine: a silent drop is indistinguishable from data that never arrived.
How Do You Build a Deterministic Batch ID for Replay?
Derive the batch ID from stable inputs — source identity, the logical partition or business date, the cutoff time zone, and a content or manifest hash — so the same logical batch yields the same ID on every retry, in every time zone, on every engine. A wall-clock timestamp or a random UUID breaks idempotency: the retry looks like a new batch, and the merge inserts a second copy.
Two hashing strategies trade cost against stability. Content hashing reads every byte of the batch, so it identifies the bytes themselves and is stable against file renames and re-listing, but it costs a full scan. Manifest hashing reads only the file list and sizes, which is cheap but weaker: file names and sizes are metadata, not proof of content. Identical-sized rewrites of the same file produce the same manifest hash while the data underneath has changed, so a manifest hash confirms the batch shape, not the batch content. Pick content hashing for small, high-value batches and for anything where correctness of the replay depends on comparing actual values; reserve manifest hashing for large append-only feeds whose listing is immutable and whose producer you trust not to rewrite in place.
-- Example configuration — validate in your target environment.
SELECT sha2(concat_ws('|',
'orders_cdc', -- source identity
'2026-11-25', -- logical business date
'Asia/Singapore', -- cutoff zone, IANA name
cast(content_sha256 AS string) -- content or manifest hash
), 256) AS batch_id
FROM batch_manifest
WHERE business_date = DATE '2026-11-25';
The limitation is real: determinism holds only while the inputs are genuinely stable. If a producer backfills a file into yesterday's partition, the content hash changes and the ID changes with it. That is why a corrected replay must reuse the original batch ID, or a child ID derived from it, rather than minting a fresh one. The replay is the same logical batch with better logic, not a new batch, and the lineage has to say so.
What Are the Prerequisites Before You Replay a Corrected Batch?
You need five things in place before a replay is safe: a table format with transactional commits, a quarantine table holding the full record contract, a pinned corrected rule version with a bumped numeric transform_version, the original batch ID retrievable, and a target table with a defined merge key.
Transactional commits. Delta Lake maintains table state through a file-based transaction log that provides ACID transactions, and the Delta transaction log protocol is documented as an open specification any system can read. Apache Iceberg maintains state in metadata files and replaces them with an atomic swap; its optimistic concurrency rule requires a writer whose base snapshot is stale to retry against the new current version. Either format gives you a commit boundary that a replay can be attributed to. Note the storage caveat: Delta's storage configuration guidance states that multi-cluster writes on S3 are experimental and require extra configuration with DynamoDB, while single-cluster writes work out of the box.
Engine and version. For Delta MERGE, only a single row from the source may match a given target row. Databricks documents that in Runtime 16.0 and above MERGE evaluates conditions in both the WHEN MATCHED and ON clauses to determine duplicate matches, whereas in 15.4 LTS and below it considers only the ON clause. A replay that deduplicates on a WHEN MATCHED predicate therefore behaves differently across those versions. For Iceberg, SQL MERGE INTO requires the Iceberg Spark extensions, and DataFrame merge requires the DSv2 API in Spark 4.0 and later.
The rest. The corrected rule must be versioned and pinned so the replay is reproducible; the original batch ID must be queryable from the quarantine table; and the target needs a stable business key. Example configuration — validate in your target environment.
What Key and Tie-Breaker Does a Deduplicated Replay Need?
A single business key such as order_id is not enough on its own. The merge needs a key that is stable across source systems, a version column that tells you which copy of a source record is newer, and a deterministic tie-breaker when two rows claim the same version. Without all three, deduplication is a coin flip that happens to look green.
Use an event or business key that the producer owns — order_id plus the source system, not a surrogate that the ingestion job generates. A generated key is re-minted on re-ingest, so the replay produces a new key and the merge cannot find the row it was supposed to fix. Pair that key with a source version: a monotonically increasing revision from the change stream (source_lsn, updated_at from the producer, or a CDC sequence). The version answers "which of these two rows is later," and it does so without reference to when your job happened to read them.
The source version is only half of the comparison. A corrected replay often leaves the source untouched and changes only the transformation logic, so source_version is identical on both sides while the row still needs to be rewritten. That's why the replay set and the target both carry a numeric transform_version, and the merge treats a higher number at equal source version as an update. Without it, s.source_version > t.source_version is the only condition, the corrected row is silently skipped, and the job still reports success over a target that never received the fix.
Two rows can still tie on both versions — two replay candidates from the same source revision processed by the same transform. Resolve that deterministically with an explicit tie-breaker in the row_number() window, such as ORDER BY source_version DESC, transform_version DESC, ingested_at_utc DESC, source_locator DESC. Sorting on an arbitrary column, or leaving the order unstated, makes the replay non-deterministic: two runs of the same batch can pick different rows and both report success.
Under concurrency, the merge is not the only writer. Another job can commit to the same target between your read and your write, and the table format's conflict resolution decides what happens. Delta and Iceberg both use optimistic concurrency, so a stale writer retries against the new snapshot. The retry is safe only because the merge is keyed and already deduplicated — run the same merge twice and the second run finds the rows and updates them rather than inserting twins.
The final piece is commit structure. The target merge and the quarantine status update are separate commits: the merge lands, then a second transaction marks the quarantined rows as replayed with the replay batch ID. If the process fails between them, the target is correct and the quarantine still reads open, which is a detectable, re-runnable state rather than silent double-counting. Do not try to make both writes one atomic unit unless your format supports multi-table transactions, and most lakehouse formats do not.
How Do You Run a Corrected Replay Without Creating Duplicates? (Numbered Workflow)
Run the replay as seven ordered steps, each with a checkpoint you can assert before moving on.
Freeze the failed batch and record its ID. Stop the pipeline from retrying, and read the deterministic batch ID from the quarantine rows. Expected result: one batch ID, and no new quarantine rows arriving for that batch.
Correct the rule and version it. Change the validation or transformation, and assign a new numeric
transform_versionon top of the rule version. The number is what the merge compares; the label is what humans read. Expected result: a rule version identifier and an incrementedtransform_versionrecorded against the batch.Re-validate in a staging pass. Apply the corrected rule to the quarantined raw payloads without writing to the target. Expected result: a count of rows that now pass and a count that still fail, with reasons.
Deduplicate the replay set to one row per target key. This is not optional. Delta
MERGEfails withDELTA_MULTIPLE_SOURCE_ROW_MATCHING_TARGET_ROW_IN_MERGEwhen more than one source row matches the same target row, and the documented remedy is to preprocess the source to eliminate multiple matches. Iceberg states the same rule: only one record in the source may update a given target row, or an error is thrown. Expected result: the replay set has exactly one row per business key.Merge into the target on the business key, carrying the batch ID as lineage. The merge is the idempotent replay step: it updates the row that already exists for a key and inserts it only if the key is absent. It commits in its own transaction, separate from the later quarantine update, so the target is either fully updated for the batch or not at all. Expected result: rows inserted or updated, with the batch ID written to the lineage column.
Run the exactly-one outcome check before touching quarantine status.
LEFT JOINthe replay set for the batch to the target and count matches per key. This must run first: after status is flipped, an unmerged key can no longer be told apart from a merged one. Expected result: every expected key returns a count of exactly one — no missing keys, no duplicates. A non-empty result blocks the next step. The implementation checklist hub frames these as binary acceptance checks, which is the right shape: each step either passes or blocks the next.Mark the quarantined rows as replayed. Only after the check passes, write the replay batch ID and status back to the quarantine table. Expected result: zero quarantined rows for the batch remain in an open state.
How Do You Verify Exactly-One Target Outcome After Replay?
Assert that every expected replay key has exactly one target row, then reconcile source-to-target counts and confirm no orphaned lineage. This is a per-batch, per-key check — not a claim of universal exactly-once delivery. The guarantee is scoped to the merge key and the transactional commit, and it depends on the engine's concurrency behavior under contention.
Here is the trap in the obvious query. Counting rows in the target and grouping by key only finds duplicates; it finds nothing at all for a key that never landed. A row that silently didn't merge returns no row from that GROUP BY, so HAVING count(*) <> 1 reports zero problems while the batch is incomplete. The check has to start from the expected set and join outward.
Take the list of keys you intended to replay — the deduplicated replay set for the batch — as the driving side of a LEFT JOIN against the target. Then assert that every driven row has exactly one match. A missing key shows up as a null joined row, a duplicate shows up as a row count above one, and both fail the same assertion. That single query shape catches the two ways a replay goes wrong, instead of only one.
The quarantine table is the wrong source for those keys, for a structural reason: it stores source_object and source_locator, not order_id and source_system, because the rejected row may never have had a usable business key. Selecting join keys from quarantine is both a schema error and a detection blind spot — a row that failed key extraction would fall out of the expected set rather than being reported missing. Drive from the replay set, and run the check before the status update, not after.
The mechanisms that make the check meaningful have boundaries worth stating. Delta uses optimistic concurrency control over its transaction log, so two writers racing on the same target may conflict and one retries; the retry is safe only because the merge is keyed and deduplicated. Iceberg's optimistic concurrency requires a writer whose base snapshot is no longer current to retry against the new version, and only some operations support retry by re-applying metadata changes. Neither mechanism promises that a row is processed once across the whole pipeline; both promise that a commit either lands or does not, and that a landed commit is attributable.
Three queries close the loop: the expected-key LEFT JOIN described above, a source-to-target row reconciliation for the batch, and a lineage check for target rows whose batch ID has no matching quarantine or manifest record. A non-empty result on any of them blocks closure of the replay.
How Do Time Zones Affect Batch Cutoffs for Singapore and US Teams?
Define every batch cutoff in a named IANA time zone and store the resulting instant in UTC. A Singapore team cutting on Asia/Singapore (UTC+8, no daylight saving) and a US team cutting on America/New_York (which observes daylight saving) mean different instants by the same phrase "daily batch," and the gap shifts by an hour twice a year.
Use IANA identifiers rather than abbreviations. The tz database documentation is explicit that timezone boundaries are not part of the stable interface, and that abbreviations are ambiguous across regions. A batch ID keyed only on a local date therefore has two failure modes: collision, where two regions produce the same date string for different instants, and split, where one region's day spans two UTC dates. Encoding the zone name and the UTC instant alongside the business date removes both.
to_timestamp parses a bare string using the session time zone, so the value inside to_utc_timestamp must be pinned to UTC before the conversion runs. Do that explicitly in the session rather than trusting the cluster default:
-- Illustrative Spark SQL — not executed. Pin the session zone first.
SET TIME ZONE 'UTC';
SELECT business_date,
time_zone,
to_utc_timestamp(
to_timestamp(concat(business_date, ' 00:00:00')), -- midnight, read as UTC
time_zone -- zone to interpret it in
) AS cutoff_utc
FROM batch_calendar
WHERE time_zone IN ('Asia/Singapore', 'America/New_York', 'America/Los_Angeles');
With the session at UTC, concat(business_date, ' 00:00:00') parses to midnight UTC, and to_utc_timestamp(..., time_zone) then reinterprets that wall-clock value as local time in the cutoff zone and returns the corresponding instant. Leaving the session zone at the cluster default is what produces two different cutoffs for the same business date on two different clusters.
This is a technical boundary problem, not a compliance statement. The practical rule: the batch calendar is a table, not a constant in code, and it records the zone and the UTC cutoff for every business date.
Reusable Asset: Quarantine, Replay, and Exactly-One Check SQL
The SQL below is illustrative and was not executed for this article. Treat it as a template to adapt, not a tested script; validate against your engine, catalog and table format before running it on production data.
The schema it assumes is minimal and coherent. The replay staging table holds one row per candidate plus the helper columns needed for deduplication; the target holds the resolved row per key and carries the batch lineage.
-- Illustrative Spark SQL — not executed. Adapt paths, types and format clauses.
-- 0a. Staging set for the replay
CREATE TABLE IF NOT EXISTS staging.orders_replay (
source_system STRING,
order_id STRING,
source_version BIGINT, -- producer revision (LSN / updated_at)
transform_version INT, -- numeric logic revision applied by the replay
ingested_at_utc TIMESTAMP,
source_locator STRING,
order_total DECIMAL(18,2),
currency STRING,
status STRING,
batch_id STRING
) USING DELTA;
-- 0b. Target table
CREATE TABLE IF NOT EXISTS silver.orders (
source_system STRING,
order_id STRING,
source_version BIGINT,
transform_version INT, -- logic revision that last wrote the row
ingested_at_utc TIMESTAMP,
source_locator STRING,
order_total DECIMAL(18,2),
currency STRING,
status STRING,
batch_id STRING, -- lineage of the commit that last wrote the row
replayed_at_utc TIMESTAMP
) USING DELTA;
-- 1. Quarantine table: the record contract
CREATE TABLE IF NOT EXISTS silver.quarantine_orders (
quarantine_id STRING NOT NULL,
source_system STRING NOT NULL,
source_object STRING NOT NULL,
source_locator STRING NOT NULL, -- file path + offset, or source PK
ingested_at_utc TIMESTAMP NOT NULL,
raw_payload STRING NOT NULL, -- verbatim, never coerced
failed_rule_id STRING NOT NULL,
failure_reason STRING NOT NULL,
contract_version STRING NOT NULL,
rule_version STRING NOT NULL,
batch_id STRING NOT NULL,
replay_status STRING NOT NULL DEFAULT 'open',
replay_batch_id STRING
) USING DELTA;
-- 2. Record a failed row (nulls fail the check too)
INSERT INTO silver.quarantine_orders
SELECT uuid(), 'orders_cdc', 'dbo.orders',
concat(source_file, '#', cast(byte_offset AS STRING)),
current_timestamp(), raw_payload,
'R042', 'order_total missing or negative',
'v3', 'rule-2026.11.1', 'b7f1c9e0a4d2', 'open', NULL
FROM bronze.orders_raw
WHERE order_total IS NULL OR order_total < 0;
Note that quarantine deliberately does not store order_id or source_system; it stores the source locator instead, because the failed row may not have had a usable business key at all. The replay set is where those keys become available, which is why the exactly-one check reads from staging rather than from quarantine.
Three things in that insert are easy to get wrong. The predicate WHERE order_total IS NULL OR order_total < 0 is deliberate: NOT (order_total >= 0) silently evaluates to null for a null order_total, so the row is filtered out of the quarantine set and disappears. A null amount, a missing value or a failed cast is exactly the failure class you want captured. Second, the rule is written as order_total missing or negative so the reason string matches the predicate rather than the older non-negative check. Third, raw_payload is carried through untouched.
-- 3. Deduplicated replay merge — explicit columns, rn excluded
MERGE INTO silver.orders AS t
USING (
SELECT source_system, order_id, source_version, transform_version, ingested_at_utc,
source_locator, order_total, currency, status, batch_id
FROM (
SELECT r.*,
row_number() OVER (
PARTITION BY source_system, order_id
ORDER BY source_version DESC,
transform_version DESC,
ingested_at_utc DESC,
source_locator DESC
) AS rn
FROM staging.orders_replay r
WHERE r.batch_id = 'b7f1c9e0a4d2'
) d
WHERE d.rn = 1
) AS s
ON t.source_system = s.source_system
AND t.order_id = s.order_id
WHEN MATCHED AND (
s.source_version > t.source_version
OR (s.source_version = t.source_version
AND s.transform_version > t.transform_version)
) THEN UPDATE SET
t.source_version = s.source_version,
t.transform_version = s.transform_version,
t.ingested_at_utc = s.ingested_at_utc,
t.source_locator = s.source_locator,
t.order_total = s.order_total,
t.currency = s.currency,
t.status = s.status,
t.batch_id = s.batch_id,
t.replayed_at_utc = current_timestamp()
WHEN NOT MATCHED THEN INSERT (
source_system, order_id, source_version, transform_version, ingested_at_utc,
source_locator, order_total, currency, status, batch_id, replayed_at_utc
) VALUES (
s.source_system, s.order_id, s.source_version, s.transform_version, s.ingested_at_utc,
s.source_locator, s.order_total, s.currency, s.status, s.batch_id, current_timestamp()
);
Two details carry the correctness. The SELECT inside the subquery names every column it wants, which drops the helper rn before the merge sees it; UPDATE SET * would copy rn into the target and fail, and INSERT * would misalign columns the moment staging gains a field. The WHEN MATCHED guard compares a tuple, not a single column: a replay that fixes transformation logic without the source data changing keeps the same source_version, so testing source_version alone would silently skip the very correction you are replaying. Newer source data wins; equal source data with a higher transform_version also wins; equal source_version and equal transform_version matches the guard's false branch and touches nothing, which is what makes a repeated replay a no-op.
-- 4. Exactly-one check: drive from the replay set, join to target
-- Run BEFORE the quarantine status update, so an unmerged key is still visible.
WITH expected AS (
SELECT DISTINCT source_system, order_id
FROM staging.orders_replay
WHERE batch_id = 'b7f1c9e0a4d2'
)
SELECT e.source_system,
e.order_id,
count(t.order_id) AS target_rows
FROM expected e
LEFT JOIN silver.orders t
ON t.source_system = e.source_system
AND t.order_id = e.order_id
GROUP BY e.source_system, e.order_id
HAVING count(t.order_id) <> 1; -- 0 = key never landed, >1 = duplicate
The driving side is staging.orders_replay, not the quarantine table, and that choice is load-bearing. Quarantine holds the failed original — source_object, source_locator, raw_payload — and never carried order_id or source_system, so a SELECT of those columns from it does not resolve. The replay set does have them, one deduplicated row per key. Run this check before the quarantine status update: once the status flips, an unmerged key is indistinguishable from a merged one, and you lose the ability to detect it.
Read the result: no rows returned means every expected key landed exactly once. A row with target_rows = 0 is a key that never made it into the target — the case the old target-only GROUP BY could not see. A row with target_rows > 1 is a duplicate. Both block closure of the replay.
Swapping the driving side matters if the source version is part of the key. When a source can legitimately hold more than one live version of an order_id, partition and join on (source_system, order_id) and compare versions explicitly rather than assuming one row per key; otherwise the check reports duplicates that are actually correct history.
Caveats: Iceberg requires the Spark extensions for MERGE INTO; Delta's duplicate-match evaluation differs between Runtime 16.0 and 15.4 LTS and below, so test the deduplication predicate on your runtime. The WHEN MATCHED tuple guard is a filter against re-applying an older or identical replay — a guard, not a replacement for deduplicating the source. Never embed credentials in the script; use your platform's secret management.
Acceptance Checklist for Quarantine and Replay
Close a replay only when every item below is true. These are acceptance criteria, not guarantees.
Every quarantined row for the batch has a source locator, a failed rule ID, a reason and a batch ID.
The raw payload is stored verbatim, with no cast applied at ingest.
The corrected rule is versioned and that version, plus a higher numeric
transform_version, is recorded against the batch.The merge updated rows where the source version was newer or the source version was equal and the
transform_versionwas newer; an identical replay left the target untouched.The exactly-one check ran before the quarantine status update, driven from the replay set rather than the quarantine table.
The replay reused the original deterministic batch ID or a derived child ID.
The replay set was deduplicated to exactly one row per business key before the merge.
The exactly-one check, driven from the replay set for the batch, returned zero rows.
The SQL in this article is treated as illustrative and has been adapted and validated against the real engine before use.
Source-to-target counts reconcile for the batch.
Quarantined rows are marked replayed with the replay batch ID.
No target row carries a batch ID with no matching manifest or quarantine record.
The quarantine table has an owner and a replay SLA.
Frequently Asked Questions
How do I keep a failed row's source identity and failure reason so a corrected replay is traceable?
Store the source locator (file path plus offset, or the source primary key), the verbatim payload, the failed rule ID and reason, and the deterministic batch ID in the quarantine table. Traceability comes from the batch ID, which links each quarantined row to the replay commit that eventually resolved it.
How is a deterministic batch id constructed and why does it matter for replay?
Derive it from stable inputs — source identity, the logical partition or business date, the cutoff time zone, and a content or manifest hash — so retries and time-zone differences yield the same ID. It matters because idempotent replay depends on recognizing the same logical batch rather than treating a retry as new data.
How is quarantine different from dropping data, and what must a discard record contain?
Quarantine retains the rejected row with its source identity, failure reason and batch lineage so it can be corrected and replayed; dropping removes the row and the evidence recovery depends on. If a row must be discarded, the discard record still needs source identity, reason, batch id and the decision owner so the loss is auditable.
How do I verify exactly-one target outcome after replay without claiming universal exactly-once?
Take the expected replay keys as the driving side of a LEFT JOIN against the target and assert each key has exactly one matching row. A missing key returns a count of zero and a duplicate returns a count above one, so both fail the same check. Then reconcile source-to-target counts for that batch. The guarantee is scoped to the merge key and the transactional commit, so state it as a per-batch check rather than universal exactly-once.
What changes for Singapore and US teams because of time zones in batch cutoffs?
Define cutoffs in a named IANA zone and store the instant in UTC: Asia/Singapore is UTC+8 with no DST, while US zones observe DST, so a "daily" batch means different instants. Encode the zone and the UTC instant in the batch id so the boundary is unambiguous across teams.