Skip to main content
← PROBLEMS / SYSTEM-DESIGN
An end-to-end domain learning journey

Design an Idempotent Financial Settlement
DAG Pipeline with Atomic WAP.

Partition settlement runs by (settlement_date, run_id) into Iceberg WAP staging branches, enforce conservation-of-money audits, and atomically fast-forward to production.
Start the journey7 stages· Last modified Nov 22, 2026
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

When a single bottleneck threatens end-to-end availability, key staging branches by deterministic `run_id` and overwrite/replace partitions atomically so Airflow retries never duplicate settlement rows.

TL;DR30-second simplified summary
▾

When a 200-executor Spark settlement job crashes at 80% completion and Airflow retries it, naive INSERT INTO pipelines leave duplicate partial rows in the live settlement table—corrupting merchant payouts.

Using Apache Iceberg Write-Audit-Publish (WAP), each run_id writes deterministically to a staging branch, runs automated Great Expectations / SQL invariant checks (SUM(debit) == SUM(credit), zero duplicate tx_id), and atomically replaces the target partition on main.

Before you begin · Building blocksAlready know these? Jump to Stage 01 ↓
Atomic Stage-Validate-Publish (WAP) for Data DAGs
Write-Audit-Publish (WAP) isolates unvalidated DAG outputs in a staging branch or prefix, runs automated data-quality gates, and promotes to production via an atomic metadata pointer swap.
Data Quality Checks
Data quality checks validate schema, freshness, volume, distribution, and business invariants across ingestion and transformation stages so corrupted data is quarantined before reaching dashboards or ML models.
Data Warehousing, Data Lake & Medallion Architecture
A Data Lakehouse unifies the low-cost, open-format object storage of a Data Lake with the ACID transactions, schema enforcement, and fast SQL performance of a Data Warehouse—typically organized via Medallion (Bronze, Silver, Gold) layers.
Full walkthrough · 7 stages
01
STAGE 01 · CORE INTUITIONfoundation

Scale Envelope & Latency Budget.

Why this matters: Size a 500M-event/day financial settlement DAG across 200 Spark executors with zero partial visibility and safe retries.

Think of Scale Envelope & Latency Budget as the intuition layer for Design an Idempotent Financial Settlement DAG Pipeline with Atomic WAP: Size a 500M-event/day financial settlement DAG across 200 Spark executors with zero partial visibility and safe retries.

Design a daily and hourly financial settlement DAG processing 500M ledger events/day across 200 Spark executors with zero partial-success visibility, deterministic idempotency on Airflow retries, and automated quarantine on balance-conservation failures.

STAGE 01 · CORE INTUITION

Scale Envelope & Latency Budget

500M LedgerEvents/DayData Scale200 Spark ExecutorsCompute FleetIceberg WAP BranchZero Partial ViewZero Duplicate RowsFinancial SLAcommits via

1.Scale Envelope: 500M events/day (~250 GB/day compressed Parquet) settled across hourly and daily DAG runs.

2.Zero Partial State: Downstream treasury reports must never read half-settled partitions during an active run.

3.Deterministic Retries: Airflow task retries must produce bit-identical settlement outputs.

200 Spark executors writing to Iceberg WAP branches guarantee zero partial visibility across 500M daily events.

02
STAGE 02 · CORE MECHANICSfoundation

Core Architecture & Data Flow.

Why this matters: Write deterministically to an Iceberg staging branch, run SQL balance audits, and atomically fast-forward main.

Think of Core Architecture & Data Flow as the intuition layer for Design an Idempotent Financial Settlement DAG Pipeline with Atomic WAP: Write deterministically to an Iceberg staging branch, run SQL balance audits, and atomically fast-forward main.

Using Apache Iceberg Write-Audit-Publish (WAP), each run_id writes deterministically to a staging branch, runs automated Great Expectations / SQL invariant checks (SUM(debit) == SUM(credit), zero duplicate tx_id), and atomically replaces the target partition on main.

STAGE 02 · CORE MECHANICS

Core Architecture & Data Flow

Create/Reset BranchIsolated StageSpark SettlementStaging WriteSQL Balance AuditAudit Checkfast_forward(main)Atomic Publishvalidates

1.Double-Entry Gate: Audit asserts SUM(debit) == SUM(credit), zero null merchant IDs, and zero duplicate tx_ids.

2.O(1) Catalog Swap: Promoting the branch flips main's Iceberg metadata pointer atomically.

3.Quarantine on Fail: Failed runs leave the staging branch intact for forensic SQL inspection.

Iceberg staging branches, SQL double-entry audits, and CAS branch fast-forwards make settlement atomic.

Engineering Decision Framework
Problem
How to implement Design an Idempotent Financial Settlement DAG Pipeline with Atomic WAP without hitting unbounded tail latency, state divergence, or operational fragility.
Naive Solution
Use a single unpartitioned path with unbounded retries and synchronous global coordination.
Why It Fails
Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
Alternatives
Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
Engineering Decision
When a single bottleneck threatens end-to-end availability, key staging branches by deterministic run_id and overwrite/replace partitions atomically so Airflow retries never duplicate settlement rows.
Trade-Offs
Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
Decision Exercise · Make the Call

When Design an Idempotent Financial Settlement DAG Pipeline with Atomic WAP experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

03
STAGE 03 · SAFE IMPLEMENTATIONintermediate

Idempotent Partition Overwrite & Audit Gate.

Why this matters: Implement settle_partition_idempotent to reset the run branch, compute settlement, audit, and promote or quarantine.

Think of Idempotent Partition Overwrite & Audit Gate as the intuition layer for Design an Idempotent Financial Settlement DAG Pipeline with Atomic WAP: Implement settle_partition_idempotent to reset the run branch, compute settlement, audit, and promote or quarantine.

def settle_partition_idempotent(spark, catalog, partition_date: str, run_id: str) -> None:
    branch = f'settle_{partition_date}_{run_id}'
    catalog.create_or_reset_branch(branch)
    spark.compute_settlement(partition_date).write_iceberg(branch=branch, mode='overwrite_partition')
    audit = spark.audit_conservation(branch, partition_date)
    if audit['imbalance_cents'] != 0 or audit['dup_tx_count'] > 0:
        catalog.quarantine(branch)
        raise ValueError(f'Settlement audit failed: {audit}')
    catalog.atomic_publish(branch, target='main')
STAGE 03 · SAFE IMPLEMENTATION

Idempotent Partition Overwrite & Audit Gate

create_or_reset_br…Idempotent Initcompute_settlementSpark Jobaudit_balance == 0Quality Gatepublish_or_quarant…Safe Outcomeaudits

1.Branch Reset on Retry: Resetting settle_<dt>_<run_id> at task start eliminates leftover files from killed executors.

2.Strict Audit Exception: Raise AuditError before catalog publish if any invariant check fails.

3.Zero Side Effects on Main: Main remains untouched throughout retries until the final CAS commit.

Resetting the staging branch per run_id and gating publish on audit assertions makes Airflow retries idempotent.

04
STAGE 04 · SCALING & TRADE-OFFSintermediate

Sharding & Hot-Spot Mitigation.

Why this matters: Mitigate hot merchant skew across 200 Spark executors using salted two-phase aggregation.

Think of Sharding & Hot-Spot Mitigation as the intuition layer for Design an Idempotent Financial Settlement DAG Pipeline with Atomic WAP: Mitigate hot merchant skew across 200 Spark executors using salted two-phase aggregation.

Partition state deterministically and apply bounded-load or sub-bucket sharding for hot keys.

STAGE 04 · SCALING & TRADE-OFFS

Sharding & Hot-Spot Mitigation

Top 1% HotMerchantsStraggler TaskSalted Pre-Agg(0..31)Phase 1 ShuffleFinal RollupPhase 2 ReduceBalanced 200ExecutorsSkew Eliminatedmerges

1.Straggler Elimination: Salting hot merchant_id keys across 32 sub-partitions prevents 199 executors from idling.

2.Adaptive Query Exec: Pair salting with Spark AQE skew-join splitting and target 128 MB Parquet output files.

3.Partition Pruning: Partition output by settlement_date so hourly runs touch only active partitions.

32-way salted two-phase aggregation and Spark AQE eliminate hot-merchant stragglers across 200 executors.

05
STAGE 05 · FAULT ISOLATIONadvanced

Failure Modes & Graceful Degradation.

Why this matters: Quarantine corrupt upstream records into a dead-letter table instead of stalling the entire daily settlement.

Think of Failure Modes & Graceful Degradation as the intuition layer for Design an Idempotent Financial Settlement DAG Pipeline with Atomic WAP: Quarantine corrupt upstream records into a dead-letter table instead of stalling the entire daily settlement.

Apply circuit breakers, fallback caches, and dead-letter quarantine queues.

STAGE 05 · FAULT ISOLATION

Failure Modes & Graceful Degradation

Raw Event PartitionMixed InputSchema & Sig CheckRow FilterQuarantine IcebergTblPoison StoreSettle ValidMerchantsIsolated Blastif corrupt

1.Poison-Pill Isolation: One malformed currency code shouldn't delay payouts for 100,000 valid merchants.

2.Reconciliation Accounting: Log quarantined totals explicitly so finance reconciles Settled + Quarantined == Gross.

3.Bounded Retry Policy: Distinguish transient S3 503s (retry) from permanent schema errors (quarantine).

Row-level schema filtering quarantines poison records while keeping payouts on schedule for valid merchants.

06
STAGE 06 · RECOVERY & CONSISTENCYadvanced

Consistency, Idempotency & Recovery.

Why this matters: Support instant time-travel rollback and deterministic replay via immutable Iceberg snapshots.

Think of Consistency, Idempotency & Recovery as the intuition layer for Design an Idempotent Financial Settlement DAG Pipeline with Atomic WAP: Support instant time-travel rollback and deterministic replay via immutable Iceberg snapshots.

Enforce atomic state transitions, fencing/idempotency keys, and fast snapshot recovery.

STAGE 06 · RECOVERY & CONSISTENCY

Consistency, Idempotency & Recovery

Immutable SnapshotsHistory LogCAS Snapshot CommitSerializabilityrollback_to_snapsh…Instant RecoveryAsync SnapshotExpiryStorage Hygieneenables

1.Sub-Second Rollback: If an upstream rate-table bug slips past audits, rolling back main to snapshot N-1 takes <1s.

2.Concurrent Run Guard: CAS commit fails cleanly if two backfills attempt to update the same partition concurrently.

3.30-Day Audit Trail: Retaining 30 days of snapshots supports regulatory replay and diffing.

Immutable Iceberg snapshots, CAS commits, and sub-second rollbacks ensure crash-safe, auditable settlement.

07
STAGE 07 · OBSERVABILITY & GUARDRAILSadvanced

Telemetry, Circuit Breakers & Failure Modes.

Why this matters: Track settlement SLA lag, per-rule audit failures, Spark straggler skew, and quarantined volume.

Think of Telemetry, Circuit Breakers & Failure Modes as the intuition layer for Design an Idempotent Financial Settlement DAG Pipeline with Atomic WAP: Track settlement SLA lag, per-rule audit failures, Spark straggler skew, and quarantined volume.

Track p99 latency, retry/conflict ratios, and saturation metrics; fail fast with bounded retries and circuit breakers whenever invariants degrade.

STAGE 07 · OBSERVABILITY & GUARDRAILS

Telemetry, Circuit Breakers & Failure Modes

DAG Finish vs.CutoffFreshness KPIAudit Fail BreakdownQuality KPIExecutor Max/MedRatioCompute SignalTreasury Halt GateFinancial Guardpairs with

1.Payout Circuit Breaker: Downstream bank-wire jobs check for a signed WAP_PUBLISHED marker before initiating transfers.

2.Skew Alert: Alert if max Spark task duration exceeds 3x median task duration.

3.Quarantine Threshold: Page on-call if quarantined dollar volume exceeds 0.01% of daily GMV.

Cutoff SLA countdowns, skew ratios, and signed WAP payout gates protect financial settlement integrity.

Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

How do you ensure Airflow task retries do not duplicate settlement rows?

Recommended Learning Flow