Daily Ledger Reconciliation with FX Rates and Late Postings
SQL & DataModel answerLast updated
Build SQL reconciliation across two ledgers with as-of FX conversion, 48h late-arrival classification, an idempotent backfilling pipeline, and honest discrepancy reporting.
You own a daily job that reconciles a raw payment stream against two downstream ledgers. Postings routinely land late — up to 48 hours is normal, and anything later is an exception that still needs to be reported. Given these tables:
payments_raw(payment_id INT, user_id INT, amount DECIMAL(10,2), currency CHAR(3), created_at TIMESTAMP)ledger_a(txn_id STRING, user_id INT, amount_usd DECIMAL(10,2), posted_at TIMESTAMP)ledger_b(txn_id STRING, user_id INT, amount_usd DECIMAL(10,2), posted_at TIMESTAMP)fx_rates(rate_date DATE, currency CHAR(3), usd_rate DECIMAL(10,6))— USD per one unit of the currency
Sample data:
payments_raw
1 | 101 | 100.00 | USD | 2025-08-30 10:05:00
2 | 102 | 90.00 | EUR | 2025-08-30 16:40:00
3 | 101 | 50.00 | USD | 2025-08-31 23:30:00
4 | 103 | 100.00 | EUR | 2025-09-01 01:20:00
fx_rates
2025-08-30 | USD | 1.000000
2025-08-30 | EUR | 1.100000
2025-08-31 | USD | 1.000000
2025-08-31 | EUR | 1.120000
2025-09-01 | USD | 1.000000
2025-09-01 | EUR | 1.150000
ledger_a: A-1(101, 100.00, 08-30 10:06), A-2(102, 99.00, 08-30 18:00), A-3(103, 115.00, 09-01 08:00)
ledger_b: B-1(101, 100.00, 09-02 11:00), B-2(101, 50.00, 09-01 00:10), B-3(102, 99.01, 08-30 18:02)
Deliver four things:
-
One SQL query producing a per-payment report with columns
payment_id,user_id,amount_usd_from_fx,a_txn_id,b_txn_id,match_status,late_by_hours,abs_amount_diff. Rules: (a) convertamountto USD using the most recent FX rate on or beforecreated_at's date, rounded to cents; (b) each payment matches at most one txn per ledger, requiring sameuser_id, amount within $0.01, and a posting lag within 48 hours; a lag beyond 48 hours (but otherwise matching) becomeslate_beyond_48hwithlate_by_hourspopulated; if only one ledger matches, emitmissing_in_a/missing_in_bfor the other; if both ledgers have candidates but amounts differ by more than $0.01, emitamount_mismatch. Break ties by smallest absolute time difference fromcreated_at, deterministically.late_by_hoursis NULL when not late. -
A Python ETL design outline that partitions by
created_at::date, keeps a rolling 72-hour backfill window, writes a snapshot table keyed deterministically, and delivers exactly-once downstream effects — including how late-beyond-48h corrections get merged without duplicate rows. -
A discrepancy chart. Produce a pie chart of counts by
match_status, then argue why a bar chart with percentages and 95% confidence intervals is the better visual, and sketch how you'd build it. -
Justify Python over R (or vice versa) for this pipeline, naming concrete libraries, runtime/deployment concerns, and interoperability with the broader data stack.
State your assumptions about ambiguous rules before writing code.
Hints
Hint 1
The FX lookup is an as-of join: pick the latest rate_date <= the payment date per currency, not an equality join.
Hint 2
Do the ledger candidate generation as a UNION ALL of both ledgers, then a ROW_NUMBER per (payment_id, source) so each payment gets at most one txn per side — order by amount-tolerance first, then |time delta|, then txn_id so reruns are stable.
Hint 3
Rows in one ledger must never satisfy the match for the other ledger; keep the per-source flag through to the final CASE, and make the classification order explicit (missing vs mismatch vs late vs matched).
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Framing
The interviewer is not testing whether you can guess the exact business rule — the rules contain deliberate gaps. They want to see you state assumptions, write SQL that is deterministic under reruns, and design a pipeline that survives late data without double-counting.
Assumptions I'd state up front:
- A row only competes for a match against its own ledger.
ledger_arows never satisfy thebside, and vice versa. - Candidate window per ledger: same
user_id,posted_atwithin[created_at - 1h, created_at + 7d]. The −1h absorbs clock skew; the 7-day horizon lets us detect postings past 48h instead of silently dropping them. late_by_hours= the worst (largest) lag across whichever ledgers matched, rounded to 2 decimals; NULL if no lag exceeds the timely threshold.- Within each ledger, preference order is: amount within $0.01 first, then smallest
|posted_at − created_at|, thentxn_idascending as a final deterministic tiebreak. - Classification precedence:
missing_in_a/missing_in_b(no candidate at all on that side, or candidate outside tolerance on one side while the other side is fine) beforeamount_mismatch, which before late classes, which beforematched. If neither ledger produces any candidate I emitmissing_in_aand note in the interview that amissing_in_bothstatus should be added. - USD is rounded to cents after conversion so the $0.01 tolerance is meaningful.
matched vs late_within_48h is the one genuinely underspecified split; I'd say "matched means both postings landed within a 1-hour SLA of created_at, otherwise late_within_48h" and flag it as configurable.
Task 1: The query (Postgres / DuckDB dialect)
WITH fx AS (
SELECT p.payment_id, p.user_id, p.created_at,
ROUND(p.amount * r.usd_rate, 2) AS amount_usd_from_fx,
ROW_NUMBER() OVER (PARTITION BY p.payment_id
ORDER BY r.rate_date DESC) AS rn
FROM payments_raw p
JOIN fx_rates r
ON r.currency = p.currency
AND r.rate_date <= CAST(p.created_at AS DATE)
),
pay AS (SELECT * FROM fx WHERE rn = 1),
ledgers AS (
SELECT 'A' AS src, txn_id, user_id, amount_usd, posted_at FROM ledger_a
UNION ALL
SELECT 'B', txn_id, user_id, amount_usd, posted_at FROM ledger_b
),
cand AS (
SELECT p.payment_id, l.src, l.txn_id,
ABS(p.amount_usd_from_fx - l.amount_usd) AS amt_diff,
EXTRACT(EPOCH FROM l.posted_at - p.created_at) / 3600.0 AS lag_h,
ROW_NUMBER() OVER (
PARTITION BY p.payment_id, l.src
ORDER BY CASE WHEN ABS(p.amount_usd_from_fx - l.amount_usd) <= 0.01 THEN 0 ELSE 1 END,
ABS(EXTRACT(EPOCH FROM l.posted_at - p.created_at)),
l.txn_id) AS rn
FROM pay p
JOIN ledgers l
ON l.user_id = p.user_id
AND l.posted_at BETWEEN p.created_at - INTERVAL '1 hour'
AND p.created_at + INTERVAL '7 days'
),
best AS (
SELECT payment_id,
MAX(CASE WHEN src = 'A' THEN txn_id END) AS a_txn_id,
MAX(CASE WHEN src = 'A' THEN amt_diff END) AS a_diff,
MAX(CASE WHEN src = 'A' THEN lag_h END) AS a_lag,
MAX(CASE WHEN src = 'B' THEN txn_id END) AS b_txn_id,
MAX(CASE WHEN src = 'B' THEN amt_diff END) AS b_diff,
MAX(CASE WHEN src = 'B' THEN lag_h END) AS b_lag
FROM cand WHERE rn = 1
GROUP BY payment_id
)
SELECT p.payment_id, p.user_id, p.amount_usd_from_fx,
b.a_txn_id, b.b_txn_id,
CASE
WHEN b.a_txn_id IS NULL AND b.b_txn_id IS NULL THEN 'missing_in_a'
WHEN b.a_txn_id IS NULL THEN 'missing_in_a'
WHEN b.b_txn_id IS NULL THEN 'missing_in_b'
WHEN b.a_diff > 0.01 AND b.b_diff > 0.01 THEN 'amount_mismatch'
WHEN GREATEST(b.a_lag, b.b_lag) > 48 THEN 'late_beyond_48h'
WHEN GREATEST(b.a_lag, b.b_lag) > 1 THEN 'late_within_48h'
ELSE 'matched'
END AS match_status,
CASE WHEN GREATEST(b.a_lag, b.b_lag) > 1
THEN ROUND(GREATEST(b.a_lag, b.b_lag)::numeric, 2) END AS late_by_hours,
ROUND(COALESCE(GREATEST(b.a_diff, b.b_diff), 0), 2) AS abs_amount_diff
FROM pay p LEFT JOIN best b USING (payment_id)
ORDER BY p.payment_id;
Sanity check on the sample: payment 1 → matched against A-1 (1 minute lag, exact amount). Payment 2 → 90 EUR × 1.10 = 99.00 USD, A-2 matches at 99.00, B-3 is 99.01 — both within tolerance, so matched. Payment 3 → B-2 at 00:10 on 09-01, ~40 min later, matched/late_within_48h depending on the SLA you chose. Payment 4 → A-3 posted 6.7 hours later at $115.00 vs 100 × 1.15 = $115.00, matched; no B row, so it would grade as missing_in_b if B never arrives.
Task 2: Idempotent daily ETL
- Partition by
created_at::date, plus storepipeline_run_date. A payment lands in exactly one partition forever; the reconciliation result for it can be rewritten any number of times. - Rolling 72h reprocess. Each run recomputes
event_date IN [run_date - 3d, run_date]. The 48h late allowance plus a day of slack means anything late-but-acceptable is picked up. Everything older is frozen and only touched by an explicit repair job. - Snapshot table
recon_snapshot(payment_id, event_date, ... )with primary key(payment_id, event_date)— deterministic because it derives from source data, not from run time. Write withMERGE/upsert or insert-overwrite of the partition (Iceberg/DeltareplaceWhere), never blindINSERT. - Exactly-once downstream. Two-stage: land the run into a staging table keyed by
(run_id, payment_id), thenMERGE ... WHEN MATCHED AND snapshot_hash <> new_hash THEN UPDATE. Downstream consumers read a table/view that deduplicates on(payment_id, event_date)withQUALIFY ROW_NUMBER() OVER (PARTITION BY payment_id ORDER BY updated_at DESC) = 1. Add a content hash column so reruns with identical data are no-ops. - Late-beyond-48h fixes. When a posting finally arrives, the candidate window catches it only if it's within 7 days; otherwise an "exception repair" job re-runs a wider window for
payment_ids flaggedlate_beyond_48hormissing_in_*. Because the snapshot key is(payment_id, event_date), the correction replaces the old row rather than adding one;abs_amount_diffshrinks,match_statusflips, and the change is recorded in an audit table (payment_id, old_status, new_status, detected_at). Alert on the rate of such flips, not just their existence.
Task 3: Charts
import matplotlib.pyplot as plt
counts = df["match_status"].value_counts()
counts.plot.pie(autopct="%1.1f%%", ylabel="")
plt.savefig("status_pie.png")
Pie charts are wrong here: nine-ish small categories with wildly unequal counts are unreadable, arc length is a poor perceptual channel, and no CIs can be attached. A horizontal bar chart with percentage on the x-axis, category on the y-axis, sorted descending, plus statsmodels.stats.proportion.proportion_confint (Wilson interval) error bars, and n annotated on each bar, is the honest version:
from statsmodels.stats.proportion import proportion_confint
p = counts / counts.sum()
lo, hi = proportion_confint(counts, counts.sum(), method="wilson")
ax.barh(p.index, p.values, xerr=[p - lo, hi - p])
Wilson rather than normal-approximation because the rare statuses have tiny counts. Use matplotlib + seaborn for the chart, pandas/pyarrow for the data, and plotly if it needs to be interactive.
Task 4: Python vs R
Python wins for the pipeline layer, not for the analysis layer. pandas (or polars for speed), pyarrow for Parquet, duckdb for local SQL over Parquet, and SQLAlchemy/warehouse connectors — all directly supported by Airflow/Dagster, Docker, and cloud functions. The orchestration, testing (pytest, pandera/great_expectations for data contracts), and CI story is far more mature. R's counterparts (data.table, arrow, dbplyr, dbt with R for modeling, targets for orchestration) are excellent, and R remains better for statistical modeling and publishing (R Markdown/Quarto). The pragmatic answer: SQL does the reconciliation, Python does the orchestration and tables, and either language can do the exploratory statistics — choose Python for operational surface area and use R where the team already has statistical depth. Mention the real cost either way: getting the same code running deterministically in a scheduler with pinned environments.