Chargeback Webhook Pipeline and Daily SFTP Export
Easy · System Design · Software Engineer · Onsite
Prompt
Architect a payment-dispute (chargeback) intake and daily accounting export service for a digital banking platform. External card networks push asynchronous dispute notifications over HTTPS webhooks (for example, event dp_9041c reversing 84.50 USD on transaction tx_78410 for merchant m_408), and once every 24 hours the platform must package newly processed disputes into a batch CSV file delivered to an internal accounting server over SFTP.
Your design should meet these functional, reliability, and scale requirements:
- Asynchronous webhook intake: Accept incoming webhook payloads carrying transaction identifier, disputed amount, currency code, merchant identifier, and event timestamp.
- Zero silent loss: Never drop accepted dispute events despite network timeouts, service restarts, or downstream outages.
- Idempotent deduplication: Card networks retry unacknowledged webhooks, so repeated deliveries of the same dispute event must never produce duplicate ledger entries.
- Daily SFTP CSV delivery: Once every 24 hours, compile a CSV containing all unexported dispute records from the prior day and upload it to accounting over SFTP.
- Explicit lifecycle tracking: Maintain clear per-record state transitions (such as
RECEIVED,QUEUED, andEXPORTED) for end-to-end data integrity and auditability. - Volume and data protection: Sustain roughly
50,000dispute events per day with sudden5xtraffic surges during peak retail periods, and encrypt all personally identifiable information (PII) at rest.
Scope & Expectations
- System architecture: Proposing the end-to-end components spanning webhook intake, durable buffering, storage, and scheduled batch export.
- Schema and state model: Defining database tables, uniqueness guarantees, and lifecycle state transitions for dispute records and daily batches.
- Retry and recovery strategy: Handling failed webhook deliveries, transient worker failures, and interrupted SFTP transfers safely.
- Consistent batch generation: Ensuring no records are skipped, double-exported, or prematurely marked exported while live webhooks keep arriving during CSV creation.
Step-by-step walkthrough
Clarify requirements and frame the problem
A chargeback is a forced payment reversal initiated by a cardholder's bank through a card network (such as Visa or Mastercard) when a customer disputes a card charge. Because every lost or duplicated chargeback directly corrupts financial ledgers and merchant balances, at 50,000 events per day (~0.6 events/second), this is a correctness, durability, and auditability problem — not a massive database-sharding problem.
Four invariants must hold simultaneously:
- Zero silent data loss: we must never lose an event after acknowledging it, and we must detect any event a card network failed to deliver.
- Strict idempotency: idempotency means processing the exact same webhook delivery two or ten times produces the exact same single stored record as processing it once, with zero duplicate ledger entries.
- Exact, non-overlapping daily export: every validated chargeback must appear in exactly one daily CSV uploaded via SFTP (SSH File Transfer Protocol, an encrypted file-transfer channel over SSH standard in enterprise accounting), even while new webhooks keep arriving during file generation.
- Encrypted PII and full auditability: PII (Personally Identifiable Information, such as cardholder names or card digits) must be encrypted at rest, and every state change must leave an immutable audit trail.
Functional & non-functional assumptions to state out loud
- Deduplication key: each card network assigns a unique
event_idand reuses it across webhook retries, so uniqueness is scoped per sender:(network, provider_event_id). - Subsequent adjustments: if a chargeback is later reversed or its amount adjusted, the network sends a new event with a new
event_idthat exports as a new row on a later day; already-exported rows are immutable. - Business-day boundary: daily batches cut on our server's UTC
received_attimestamp ([D 00:00Z, D+1 00:00Z)), never the sender's clock (which could be backdated or skewed across delayed retries), while including both timestamps in the CSV for accounting. - Daily SLA: day
D's CSV must land on the accounting SFTP server by 06:00 UTC on dayD+1. - Downstream enrichment: before export, an internal
Transactions Servicematchestransaction_idto attach internal ledger/account metadata (RECEIVED -> QUEUED), and that service may experience brief outages.
Back-of-the-envelope numbers
Webhook ingestion Normal volume 50,000 events/day / 86,400 s = ~0.58 events/s average 5x seasonal peak 250,000 events/day / 86,400 s = ~2.9 events/s average Backlog replay burst network flushes 5-min outage = ~500 events/s for 5 min (150,000 events) Inbound bandwidth ~2 KB JSON payload = ~100 MB/day normal, ~500 MB/day peak Database storage Per chargeback ~1 KB structured row + ~2 KB encrypted raw payload = ~3 KB Annual growth 50,000 x 365 = ~18.25M rows = ~55 GB/year 7-year retention standard financial audit window = ~128M rows, ~385-400 GB total Daily CSV export File size 50,000 rows x ~200 B/row = ~10 MB normal (~50 MB at 5x peak) SFTP transfer time over conservative 10 Mbit/s = ~8 s for 10 MB (~40 s for 50 MB) Database batch claim 1 SQL UPDATE of 50k-250k rows = ~0.5-3 seconds on one PostgreSQL primaryWhat the numbers tell us: a single PostgreSQL primary (with synchronous cross-zone standbys) and a modest replicated message queue have more than 100x throughput headroom. Over-engineering with distributed database sharding would only add failure modes; keep components few and make every state transition airtight.
Webhook and internal API design
The webhook endpoint contract defines the exact boundary of responsibility between the card network and us:
POST /v1/webhooks/{network}/chargebacks network in {"visa", "mastercard"} Headers: X-Signature: <hex HMAC-SHA256 of raw request bytes> (or mutual TLS client cert) Content-Type: application/json (max body 64 KB) Body: {"event_id": "dp_9041c", "transaction_id": "tx_78410", "amount": "84.50", "currency": "USD", "merchant_id": "m_408", "timestamp": "2026-10-14T18:22:09Z", "cardholder": {"name": "...", "pan_last4": "8193"}} -> 200 OK {"status": "accepted"} (durable in queue; ALSO returned on duplicates!) -> 401 Unauthorized invalid or missing HMAC signature (alert; do not store) -> 404 Not Found unknown network slug -> 413 Payload Too Large body > 64 KB -> 503 Service Unavailable + Retry-After: 30 (queue unreachable; tells network to hold & retry)Why each status code is chosen deliberately:
- Return
200 OKonly after durable persistence (replicated across queue brokers), and respond in < 100 ms so slow downstream validation never triggers network timeouts. - Return
200 OKon duplicates, never409 Conflict: the sender's webhook delivery engine treats200as"delivered, stop retrying", whereas409can trigger endless retry storms or false alerts on the network's side. - Verify authenticity first (
401), but never return400 Bad Requestfor schema mismatches on authentic webhooks: if Visa adds or changes a field format, returning400tells Visa to drop the event permanently. Instead, store the raw signed payload durably, return200 OK, and quarantine it internally for replay!
Audited internal operations API:
GET /internal/chargebacks/{id} PII-masked record + state history GET /internal/exports/{business_date} batch state, row_count, currency totals, SHA-256 POST /internal/exports/{business_date}/resume safely continue an interrupted export batch POST /internal/inbound/{id}/replay re-parse a quarantined raw payload after deploying a fix- Return
Data model and state machine
We use PostgreSQL with two synchronous standbys in separate availability zones. Monetary values are stored as exact 64-bit integers in the currency's minor unit (per ISO 4217:
2decimal places -> cents/centavos forUSD/BRL,0forJPY,3forBHD) — never floating-point numbers, because binary floats cannot represent0.10or84.50exact to the cent.CREATE TABLE inbound_events ( -- immutable vault of every authentic raw webhook id bigserial PRIMARY KEY, network text NOT NULL, provider_event_id text NOT NULL, payload_sha256 bytea NOT NULL, payload_enc bytea NOT NULL, -- raw JSON bytes encrypted with per-row data key dek_enc bytea NOT NULL, -- data key wrapped by KMS master key received_at timestamptz NOT NULL, -- our UTC clock when accepted parse_status text NOT NULL, -- 'PENDING', 'PARSED', 'QUARANTINED' UNIQUE (network, provider_event_id) ); CREATE TABLE export_batches ( id bigserial PRIMARY KEY, business_date date NOT NULL UNIQUE, -- guarantees at most 1 batch per day cutoff timestamptz NOT NULL, -- exclusive upper bound (e.g. D+1 00:00:00Z) state text NOT NULL, -- 'STAGED', 'GENERATED', 'EXPORTED' row_count int, totals jsonb, -- e.g. {"BRL": 1234500, "USD": 99000} in minor units file_name text, file_uri text, -- immutable object-store URI (S3/GCS) file_sha256 bytea, upload_attempts int NOT NULL DEFAULT 0, last_error text, created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now() ); CREATE TABLE chargebacks ( id bigserial PRIMARY KEY, inbound_event_id bigint NOT NULL UNIQUE REFERENCES inbound_events (id), network text NOT NULL, provider_event_id text NOT NULL, transaction_id text NOT NULL, merchant_id text NOT NULL, amount_minor bigint NOT NULL CHECK (amount_minor > 0), currency char(3) NOT NULL, event_ts timestamptz NOT NULL, -- payment network's timestamp received_at timestamptz NOT NULL, -- our receive timestamp (determines export cutoff) cardholder_enc bytea, -- envelope-encrypted PII state text NOT NULL, -- 'RECEIVED', 'QUEUED', 'STAGED', 'EXPORTED', 'NEEDS_REVIEW' batch_id bigint REFERENCES export_batches (id), updated_at timestamptz NOT NULL DEFAULT now(), UNIQUE (network, provider_event_id) ); -- Partial index keeps daily claim fast (~50k rows) even when the table reaches 130M historical rows CREATE INDEX chargebacks_ready_idx ON chargebacks (received_at) WHERE state = 'QUEUED'; CREATE INDEX ON chargebacks (batch_id); CREATE TABLE chargeback_transitions ( -- append-only audit log (no UPDATE/DELETE privileges) chargeback_id bigint NOT NULL, from_state text, to_state text NOT NULL, batch_id bigint, actor text NOT NULL, reason text, at timestamptz NOT NULL DEFAULT now() );Record lifecycle state machine:
RECEIVED --(matched to internal txn)--> QUEUED --(claimed by batch_id)--> STAGED --(SFTP confirmed)--> EXPORTED | +--(unmatched after retries or invalid)--> NEEDS_REVIEW --(operator resolves)--> QUEUED- Every state step uses an atomic compare-and-set (
UPDATE chargebacks SET state = 'QUEUED' WHERE id = $1 AND state = 'RECEIVED') paired with anINSERT INTO chargeback_transitionsin the same transaction, preventing double-transitions. - Once a row enters
STAGEDorEXPORTED, a PostgreSQLBEFORE UPDATEtrigger rejects any modification to(amount_minor, currency, merchant_id, transaction_id)so the database and CSV file can never diverge. - Strict decimal-to-minor-unit parsing ensures malformed amounts raise
ValueError(triggering clean quarantine) rather than silently rounding cents or crashing the worker process:
from decimal import Decimal, InvalidOperation MINOR_UNIT_DIGITS = {"BRL": 2, "USD": 2, "EUR": 2, "JPY": 0, "BHD": 3} def to_minor_units(amount_text: str, currency: str) -> int: """Convert '84.50' USD -> 8450 exact minor units; raise ValueError on any precision mismatch.""" if currency not in MINOR_UNIT_DIGITS: raise ValueError(f"Unsupported currency: {currency!r}") try: amount = Decimal(amount_text) except (InvalidOperation, TypeError): raise ValueError(f"Invalid decimal string: {amount_text!r}") if not amount.is_finite(): raise ValueError(f"Non-finite amount: {amount_text!r}") scaled = amount.scaleb(MINOR_UNIT_DIGITS[currency]) if scaled != scaled.to_integral_value() or scaled <= 0: raise ValueError(f"Amount {amount_text!r} invalid for {currency}") return int(scaled)- Every state step uses an atomic compare-and-set (
High-level architecture
Card Networks (Visa, Mastercard) | HTTPS POST + HMAC-SHA256 signature v [Load Balancer] --> [Webhook Receivers x3 (stateless, 1 per AZ)] 1. Verify HMAC 2. Encrypt body 3. Enqueue (acks=all) 4. Return 200 | v [Replicated Queue: chargeback-events (3 AZs, 7-day retention)] ---> [Dead-Letter Queue] | v [Ingest Workers x2] dedupe insert, parse, encrypt PII -> state='RECEIVED' [Validator Workers] match txn via Transactions API -> state='QUEUED' | v [PostgreSQL Primary + 2 Sync Standbys] <---> [KMS (Key Management Service)] ^ | 1. Claim 2. Stream CSV 4. Confirm [Daily Scheduler 00:30 UTC] -> [Export Job (advisory-locked)] ---> [Object Storage (versioned CSV + manifest)] | | 3. SFTP put '.part' + '.sha256', then atomic rename v [Accounting SFTP Server] [Daily Reconciliation Job] compares network settlement reports against inbound_eventsWhy put an asynchronous message queue in front of PostgreSQL? At 0.6 events/s, receivers could insert straight into PostgreSQL, and saying so shows good engineering judgment. Adding a managed replicated queue (Kafka with
acks=allor AWS SQS) buys three concrete protections for minimal cost:- Zero
503s during database maintenance or failover: when PostgreSQL promotes a standby (~30–60 s), webhook receivers keep returning200 OKinto the queue seamlessly. - Shock absorber for 500/s replay bursts: workers drain bursts into PostgreSQL at a steady, predictable connection count.
- 7-day raw replay buffer: allows re-draining traffic even after severe worker bugs.
- Zero
Deep dive 1: zero-loss, idempotent ingestion
Zero data loss comes from a strict 4-link chain of custody, where no stage releases an event until the next stage confirms durable multi-zone storage:
Card Network ---(holds until HTTP 200)---> Webhook Receiver Webhook Receiver ---(waits for 3-AZ queue ack)---> Replicated Queue Replicated Queue ---(holds until DB commit ack)---> Ingest Worker Ingest Worker ---(waits for sync standby WAL ack)---> PostgreSQL (Primary + Sync Standby)If any machine crashes mid-step, the previous owner retries. Because retries create duplicates, both the receiver and worker are completely idempotent:
import hashlib import hmac import json def verify_signature(network: str, headers: dict, raw_body: bytes) -> bool: """Verify HMAC-SHA256 in constant time so timing attacks cannot leak signature bytes.""" secret = SECRETS.get(network) if secret is None: return False expected_hex = hmac.new(secret, raw_body, hashlib.sha256).hexdigest() provided_hex = headers.get("X-Signature", "") return hmac.compare_digest(expected_hex, provided_hex) def extract_event_id_or_hash(raw_body: bytes) -> str: """Read event_id safely; fall back to SHA-256 if JSON is malformed so we still quarantine it.""" try: parsed = json.loads(raw_body.decode("utf-8")) if isinstance(parsed, dict) and parsed.get("event_id"): return str(parsed["event_id"]) except (UnicodeDecodeError, ValueError): pass return hashlib.sha256(raw_body).hexdigest() def handle_webhook(network: str, headers: dict, raw_body: bytes) -> int: if network not in SECRETS: return 404 if len(raw_body) > MAX_BODY_BYTES: return 413 if not verify_signature(network, headers, raw_body): return 401 event_id = extract_event_id_or_hash(raw_body) # Encrypt raw body BEFORE enqueuing so plaintext PII never touches queue disks envelope = { "network": network, "event_id": event_id, "received_at": utc_now_iso(), "ciphertext": encrypt_for_queue(raw_body), } try: queue.send(key=f"{network}:{event_id}", value=envelope, timeout_s=3.0) except QueueUnavailableError: return 503 # Network keeps event and retries after Retry-After return 200Inside the Ingest Worker, a single PostgreSQL
UNIQUE (network, provider_event_id)constraint deduplicates both external webhook retries and internal queue redeliveries atomically without race conditions:INSERT INTO inbound_events ( network, provider_event_id, payload_sha256, payload_enc, dek_enc, received_at, parse_status ) VALUES ($1, $2, $3, $4, $5, $6, 'PENDING') ON CONFLICT (network, provider_event_id) DO NOTHING RETURNING id; -- returns NULL if this (network, provider_event_id) was already stored!- If
RETURNING idcomes back empty, the worker verifies thatpayload_sha256matches the stored hash (alerting on-call if a buggy sender ever reused anevent_idwith different bytes) and acknowledges the queue message cleanly. - If
parse_chargebackraisesValueError, the worker marksinbound_events.parse_status = 'QUARANTINED'inside the same transaction and alerts engineers — zero lost bytes. - Matching against the internal
Transactions Serviceruns asynchronously in the Validator Worker (RECEIVED -> QUEUED), so a slow internal microservice never blocks ingestion.
- If
Deep dive 2: atomic daily export without race conditions
Suppose we exported yesterday's records naively by running
SELECT * FROM chargebacks WHERE state = 'QUEUED'to write a CSV, and then runningUPDATE chargebacks SET state = 'EXPORTED' WHERE state = 'QUEUED'. Any chargeback moving intoQUEUEDduring those 10 seconds would be markedEXPORTEDwithout ever appearing in the CSV — silently dropping real money!We solve this with a 4-step Claim -> Generate -> Upload -> Confirm protocol around a frozen
batch_id:Timeline around 00:00 UTC cutoff for business_date = 2026-10-14: ... 23:59:58Z [dp_9041c arrives] | 00:00:02Z [dp_9042d arrives] ... 00:30:00Z [Export Job runs] |<--- cutoff = 2026-10-15T00:00:00Z --->| dp_9041c claimed into batch 19 dp_9042d has received_at >= cutoff -> stays QUEUED for Oct 15!Pre-check (Watermark wait): At
00:30 UTC, the Export Job acquires a PostgreSQL advisory lock (pg_try_advisory_lock) so two schedulers never collide, waits until the oldest message in the ingestion queue is newer thancutoff(D+1 00:00:00Z), and waits (up to a03:00 UTCdeadline) for pre-cutoffRECEIVEDrows to finish validation intoQUEUED.Step 1 — Atomic Claim (
QUEUED -> STAGED) in one SQL transaction:- Insert the batch row with
INSERT INTO export_batches (business_date, cutoff, state) VALUES (:date, :cutoff, 'STAGED') ON CONFLICT (business_date) DO NOTHING RETURNING id. If noidis returned, a previous run already claimed this date — commit immediately and jump to the Resume table below! - Otherwise, inside the exact same SQL transaction, claim all eligible rows and freeze control totals:
WITH claimed AS ( UPDATE chargebacks SET state = 'STAGED', batch_id = :batch_id, updated_at = now() WHERE state = 'QUEUED' AND received_at < :cutoff -- NO lower bound: late stragglers from prior days are swept in, never lost! RETURNING id ) INSERT INTO chargeback_transitions (chargeback_id, from_state, to_state, batch_id, actor) SELECT id, 'QUEUED', 'STAGED', :batch_id, 'export-job' FROM claimed; UPDATE export_batches b SET row_count = stats.row_count, totals = stats.totals, updated_at = now() FROM ( SELECT coalesce(sum(cnt), 0) AS row_count, coalesce(jsonb_object_agg(currency, sum_minor), '{}'::jsonb) AS totals FROM ( SELECT currency, sum(amount_minor) AS sum_minor, count(*) AS cnt FROM chargebacks WHERE batch_id = :batch_id GROUP BY currency ) by_curr ) stats WHERE b.id = :batch_id;Notice
received_at < :cutoffhas no lower timestamp bound: if a record from October 13 was stuck inNEEDS_REVIEWorRECEIVEDuntil October 14, it is automatically picked up in the October 14 batch instead of falling into a permanent crack! Even a 0-row holiday produces an explicit 0-row CSV (row_count = 0, totals = '{}') so accounting knows the job ran.Step 2 — Deterministic CSV generation (
STAGED -> GENERATED): StreamSELECT ... FROM chargebacks WHERE batch_id = :batch_id ORDER BY idvia a server-side cursor. Format integer minor units back into exact decimal strings without floats, omit any wall-clock"generated_at"header so re-running Step 2 produces byte-for-byte identical CSV output and the exact same SHA-256, verify row counts and currency sums againstexport_batches.totals, upload the CSV + JSON manifest to versioned object storage, and setexport_batches.state = 'GENERATED'.def format_minor_units(amount_minor: int, currency: str) -> str: """Format 8450 USD -> '84.50' deterministically using integer arithmetic only.""" digits = MINOR_UNIT_DIGITS[currency] if digits == 0: return str(amount_minor) whole, fraction = divmod(amount_minor, 10 ** digits) return f"{whole}.{fraction:0{digits}d}"Step 3 — Atomic SFTP upload (detailed next).
Step 4 — Confirm (
STAGED -> EXPORTED): In one transaction, markexport_batches.state = 'EXPORTED', movechargebacks WHERE batch_id = :batch_idfrom'STAGED'to'EXPORTED', and appendchargeback_transitionsrows.If the export job crashes right after... export_batches.stateSafe automatic resume action Step 1 (Claim committed) STAGEDStream WHERE batch_id = :id ORDER BY idto build the exact same CSVStep 2 (CSV saved in object storage) GENERATEDUpload saved CSV from object storage to SFTP Step 3 (SFTP rename succeeded, DB died) GENERATEDVerify remote .csvsize &.sha256match, skip re-upload, run Step 4Step 4 (Confirmed) EXPORTEDNo-op - Insert the batch row with
Deep dive 3: retry strategies for webhooks, workers, and SFTP
1. Inbound webhooks + daily network reconciliation
- Webhook providers retry on network timeouts and
5xxresponses using their own schedules, then eventually give up. Therefore, webhooks alone cannot guarantee 100% capture if our edge was unreachable for hours. - Every morning, a Daily Reconciliation Job fetches Visa's and Mastercard's daily dispute/settlement reports (or query APIs), diffs them against
inbound_events, and injects any missing event through the standard ingestion pipeline (ON CONFLICT DO NOTHINGmakes overlaps harmless).
2. Internal worker retries without false Dead-Letter Queue (DLQ) floods
- Transient errors retry with exponential backoff and full jitter (doubling wait times
100 ms -> 200 ms -> ... -> 30 srandomized so workers do not slam a recovering service in lockstep). - Critical distinction: if PostgreSQL itself is unreachable during a 45-second primary failover, workers pause queue polling and retry the DB connection without incrementing message delivery attempts! Otherwise, 10 fast retries would dump thousands of healthy messages into the dead-letter queue (a holding queue for poison messages that repeatedly fail while healthy messages succeed). Only genuine per-message poison failures enter the DLQ after 10 attempts and page on-call.
3. Crash-safe, atomic SFTP uploads
Uploading directly to
incoming/chargebacks_2026-10-14.csvlets the accounting cron job read a half-written file mid-transfer! Instead, we upload to a.partsuffix, write a.sha256checksum file, and finish with an atomic POSIXrename:def upload_csv_atomically(batch, sftp_client): """Deliver CSV idempotently using check-before-put, '.part' staging, and atomic rename.""" final_path = f"incoming/{batch.file_name}" temp_path = final_path + ".part" checksum_path = final_path + ".sha256" # 1. Idempotency check: did a prior attempt upload & rename right before crashing? existing = sftp_client.stat_or_none(final_path) if existing is not None: if existing.size == batch.size_bytes and sftp_client.read_text(checksum_path) == batch.sha256_hex: return # Already delivered intact; proceed straight to Step 4 DB confirmation! raise RuntimeError(f"Conflicting remote file already exists at {final_path}") # 2. Upload under '.part' (ignored by accounting's '*.csv' file watcher) sftp_client.put(batch.local_csv_path, temp_path) if sftp_client.stat(temp_path).size != batch.size_bytes: raise RuntimeError("Truncated SFTP upload detected") # 3. Publish checksum, then atomically rename '.part' -> '.csv' sftp_client.put_text(checksum_path, batch.sha256_hex) sftp_client.rename(temp_path, final_path)SFTP connection failures retry with backoff (
1, 2, 4, 8, 16, then every30minutes), paging on-call after 3 consecutive failures or at 04:00 UTC (2 hours before the06:00 UTCSLA), using pinned SSH host keys and rotated private keys from a secrets manager.- Webhook providers retry on network timeouts and
PII encryption at rest, scaling, and failure modes
Layered PII protection
- Never store full card numbers (PANs): store only a vault token and last 4 digits (
pan_last4), keeping this service largely out of full PCI-DSS cardholder-data scope. Exclude all PII columns from the accounting CSV. - Disk encryption + application-level envelope encryption: cloud disk encryption only protects against physical disk theft — any engineer or compromised SQL session can still read plaintext columns! We use envelope encryption on
inbound_events.payload_encandchargebacks.cardholder_enc: the app encrypts each record with a unique random Data Encryption Key (DEK), encrypts that DEK using a Master Key inside KMS (Key Management Service), and stores the wrapped DEK alongside the ciphertext. - Blind indexes & crypto-shredding: if support needs exact-match lookup by cardholder email or tax ID, store
HMAC(secret_pepper, normalized_value)in a separate column. Wrap DEKs under a monthly KMS Master Key so after legal retention expires, deleting that month's KMS key (crypto-shredding) permanently renders historical PII unreadable — even inside immutable cold database backups — while keeping plaintext integer ledger columns intact.
Failure modes & synchronous standby resilience
Failure scenario System behavior & recovery PostgreSQL primary crashes Automatic failover promotes one synchronous standby with zero lost commits; queue buffers incoming webhooks while workers reconnect. One synchronous standby crashes Configure synchronous_standby_names = 'ANY 1 (standby_az2, standby_az3)'across two standbys so losing one standby never stalls primary commits!Transactions Service outage Records accumulate safely in RECEIVED; validator retries with backoff; if still down at03:00 UTC, export runs cleanly and delayed rows export tomorrow.Scheduler fails to trigger External dead man's switch alerts at 04:00 UTCwheneverexport_batcheshas no'EXPORTED'row for yesterday.- Never store full card numbers (PANs): store only a vault token and last 4 digits (
Summary of key trade-offs
- Managed replicated queue ahead of PostgreSQL: adds one infrastructure component in exchange for surviving DB failovers with zero
503s, absorbing 500/s replay bursts, and retaining 7 days of raw traffic. - At-least-once delivery + unique
(network, provider_event_id)constraint: achieves exact-once ledger state without fragile distributed two-phase commits. - Server
received_at < cutoffwith no lower bound: guarantees delayed or previously quarantined records never fall through date cracks, trading that late arrivals appear on the day received (with originalevent_tspreserved in a column). - Freeze
batch_id(STAGED) before streaming deterministic CSV bytes: eliminates read/write race conditions and makes crash recovery byte-for-byte reproducible. - Immutability trigger after
STAGED: guarantees database totals and accounting CSV files never drift apart; subsequent network adjustments flow as separate rows. - Envelope encryption + monthly KMS keys: adds KMS calls (mitigated by short-lived DEK caching for batches) in exchange for protecting PII from database read access and enabling backup-wide crypto-shredding.
- Managed replicated queue ahead of PostgreSQL: adds one infrastructure component in exchange for surviving DB failovers with zero
Intuition & how it works
Think of this system like an armored bank night-drop chute paired with serially numbered deposit envelopes and one sealed daily courier bag. When a card network courier drops a chargeback notice down the chute (an incoming webhook), the chute stamps a receipt (200 OK) only after the envelope lands inside a fireproof triple-locked drop box (a 3-zone replicated message queue). Inside the vault, a clerk checks the envelope's serial number against a master ledger (UNIQUE (network, provider_event_id) — duplicate slips from nervous couriers are politely ignored), verifies the customer's original transaction (RECEIVED -> QUEUED), and at midnight locks every verified envelope received before 00:00 UTC into a numbered canvas bag (STAGED with batch_id = 19). Only the envelopes inside Bag #19 are tallied onto the manifest sheet and handed to the accounting truck (EXPORTED), while new envelopes still dropping down the chute at 00:01 UTC sit untouched on the table for tomorrow's bag.
A naive implementation loses or double-counts money at every seam. Returning HTTP 200 before persisting to replicated disk drops chargebacks forever whenever a web container restarts, and checking "does event_id exist? If not, insert" in application code creates duplicate financial entries whenever two webhook retries arrive in the same millisecond. Worse, generating the daily CSV via SELECT * WHERE state = 'QUEUED' followed by a separate UPDATE ... SET state = 'EXPORTED' either marks newly arrived records as exported without putting them in the file, double-exports rows after a mid-upload crash, or lets the accounting server ingest a half-uploaded CSV file.
Trace a single chargeback (event_id = "dp_9041c", "84.50" USD on tx_78410) through the 4 stages:
- Authenticated, durable webhook intake: Visa POSTs
dp_9041csigned with HMAC-SHA256 (a cryptographic hash using a shared secret proving authenticity). The receiver verifies the signature in constant time, encrypts the raw JSON so plaintext PII (Personally Identifiable Information, like cardholder name) never touches queue disks, waits for a 3-zone queue acknowledgment, and returns200 OK. Five seconds later Visa retries due to a client timeout; the receiver enqueues it again and returns200 OKso Visa stops retrying. - Idempotent storage & async validation: An ingest worker inserts
("visa", "dp_9041c")intoinbound_events(ON CONFLICT DO NOTHING RETURNING id), converts"84.50" USDto integer minor units8450(cents, avoiding binary float rounding), and commitschargebacks(state = 'RECEIVED')across a synchronous PostgreSQL standby. When the duplicate queue message arrives next,ON CONFLICT DO NOTHINGreturns empty and the worker skips it cleanly. A validator worker matchestx_78410and advancesRECEIVED -> QUEUED. - Atomic batch claim & deterministic CSV: At
00:30 UTC, after the queue watermark passes00:00:00Z, one SQL transaction createsexport_batches(business_date = '2026-10-14', id = 19)and flips allQUEUEDrows withreceived_at < 2026-10-15T00:00Ztostate = 'STAGED', batch_id = 19, freezingrow_countand currencytotals. The job streamsWHERE batch_id = 19 ORDER BY idintochargebacks_2026-10-14.csv(with no wall-clock header, so re-runs produce the exact same bytes and SHA-256) and archives it to object storage (GENERATED). - Atomic SFTP delivery: Over SFTP (SSH File Transfer Protocol), the uploader writes
incoming/chargebacks_2026-10-14.csv.part, verifies remote byte size, writes.sha256, atomically renames.part->.csvso accounting never sees a partial file, and flipsSTAGED -> EXPORTED.
Key trade-offs
- Replicated message queue ahead of PostgreSQL vs. direct database inserts. At ~0.6 events/s average (~2.9/s seasonal peak), inserting directly from webhook receivers into PostgreSQL works and removes one moving part. Adding a replicated queue costs one managed component, but keeps webhook uptime at
200 OKduring 30–60 second PostgreSQL failovers, absorbs 500/s backlog replay bursts effortlessly, and retains 7 days of raw messages. - At-least-once delivery + unique database key vs. distributed exactly-once transactions. Allowing every network hop to retry freely and collapsing duplicates via
UNIQUE (network, provider_event_id)is vastly simpler and more reliable than two-phase commit protocols across HTTP, queues, and SQL, and makes manual replays and daily reconciliation completely safe. - Cutting batches by server
received_atvs. payment-networkevent_ts. Slicing byevent_ts BETWEEN day_start AND day_endpermanently misses delayed webhooks arriving after midnight! Cutting byreceived_at < cutoffwith no lower bound guarantees zero dropped stragglers, with the minor trade-off that a delayed network delivery lands in the next day's file (with bothevent_tsandreceived_atcolumns visible to accounting). - Two-phase Claim (
STAGEDwithbatch_id) then Generate vs. single-passSELECTexport. Stampingbatch_idin an atomic transaction before writing bytes guarantees concurrent arrivals never slip into or out of the set, and makes crash recovery at any step 100% deterministic. - Freezing staged/exported rows vs. mutating rows on adjustments. Blocking edits once
state IN ('STAGED', 'EXPORTED')ensures the database and historical CSVs never disagree; reversals or fee changes arrive as new events and export as adjustment rows on later days. - Application-level envelope encryption vs. disk-only encryption. Full-disk encryption is transparent and zero-latency, but leaves PII readable to any SQL client or leaked backup snapshot. Envelope encryption (per-row data key wrapped by a KMS master key) protects PII even from database readers and enables crypto-shredding (destroying an expired month's KMS key to erase PII across old backups), at the cost of KMS key management and needing HMAC blind indexes for exact-match lookups.
Common mistakes
- Returning HTTP
200 OKbefore the payload is durably replicated (for instance, buffering in process RAM or local disk), permanently losing chargebacks if the pod crashes. - Returning
400 Bad Requeston authentic webhooks that fail JSON schema validation, which instructs Visa/Mastercard to abandon retries instead of storing the raw payload ininbound_eventsasQUARANTINED. - Deduplicating with
SELECTfollowed byINSERTin application code rather thanINSERT ... ON CONFLICT DO NOTHING, losing races when parallel retries hit two workers at once. - Partitioning
chargebacksby month without keeping an unpartitioned dedupe table: PostgreSQL forces unique indexes on partitioned tables to include the partition key, which weakens uniqueness to(network, provider_event_id, month)and lets a late retry on the 1st of next month duplicate a row from the 31st! - Exporting with
WHERE event_ts BETWEEN yesterday_00 AND yesterday_24, dropping late-arriving chargebacks into a permanent black hole, or updatingstate = 'EXPORTED'in a separate un-staged query that sweeps up newly arrived rows. - Including a
"Generated at: <now>"timestamp inside the CSV, changing the file's SHA-256 on retry so SFTP recovery cannot verify whether a prior attempt already uploaded identical content. - Uploading directly to the final
.csvfilename on SFTP instead of uploading.partand atomically renaming, causing accounting's file watcher to ingest truncated files. - Storing money as
float/DOUBLE PRECISION(causing cent-rounding drift) or hardcoding 2 decimal places (JPYhas 0;BHDhas 3). - Counting "PostgreSQL unreachable" connection errors toward the 10-retry Dead-Letter Queue (DLQ) limit, dumping every in-flight message into the DLQ during an ordinary 45-second database failover instead of pausing consumer polling.
- Configuring a single synchronous PostgreSQL standby, which halts all primary writes when that one standby restarts — always run at least 2 standbys with
ANY 1 (s1, s2).
Follow-up questions
- What happens if the accounting SFTP server stays unreachable for multiple days? Decouple batch cutting and CSV generation from SFTP transport so internal state never backs up into a giant multi-day blob. Every night at
00:30 UTC, the Export Job still claims that day's records (STAGED), writeschargebacks_YYYY-MM-DD.csvplus its checksum manifest into immutable object storage, and marks the batchGENERATED. Meanwhile, the uploader retries SFTP every 30 minutes with jitter, pages on-call after 3 consecutive failures, and automatically emails dayD's control totals (row_countand per-currencytotals) to accounting so finance can post provisional ledger entries. Once SFTP recovers — even days later — the uploader delivers waitingGENERATEDbatches strictly in chronological order, one separate daily file per batch (never merged), and if an outage threatens month-end financial close, provides accounting an audited, short-lived pre-signed download URL straight from object storage with the exact same SHA-256 checksums. - Which metrics, health checks, and alerts would you put in place to protect the daily CSV delivery SLA? Define the explicit SLO (Service Level Objective): day
D's CSV is confirmed on SFTP (state = 'EXPORTED') before06:00 UTConD+1with zero un-reconciled discrepancies, then alert on early leading indicators hours before06:00 UTC:- Ingestion health: webhook
5xxand401spikes, silent zero-traffic drops per network compared against the same hour last week, queue consumer lag age,DLQ > 0(immediate page), anyQUARANTINEDraw event, and any record stuck inRECEIVED> 2 hours. - Export milestone gates: page on-call if yesterday's batch is not
STAGEDby03:15 UTC, notGENERATEDby03:30 UTC, or notEXPORTEDby04:00 UTC(leaving 2 full hours for human intervention before the06:00 UTCSLA), backed by an external dead man's switch that pages if the scheduled job never started at all. - Financial integrity: automated checks that CSV sum/count equals
export_batches.totals, plus alerts on any discrepancy found by the morning network settlement reconciliation job.
- Ingestion health: webhook
- How would you prevent sensitive cardholder PII from leaking into application logs or distributed traces? Combine allow-list structured logging at the source with automated regex + Luhn scrubbing as a defense-in-depth safety net. Application code emits structured JSON logs limited to an explicit schema allow-list (
inbound_event_id,chargeback_id,network,state,batch_id, latency), never logging raw HTTP request bodies, headers, or SQL bind parameters (and disabling body/query-param capture in OpenTelemetry/APM tracing agents); when debugging a parse failure, engineers look upinbound_event_idthrough an access-logged break-glass tool. Second, attach a processor filter to the logging pipeline that redacts sensitive dictionary keys (name,cardholder,pan,email,tax_id) and scans free-text exception strings to mask 13-to-19-digit sequences passing the Luhn check (the standard modulus-10 checksum formula used to validate payment card numbers), verified continuously by CI unit tests that log synthetic card fixtures and fail the build if unmasked digits appear.
```python import re
# Matches 13-to-19 digit card candidates separated by optional spaces or hyphens PAN_CANDIDATE_RE = re.compile(r"\b\d(?:[ -]?\d){12,18}\b")
def passes_luhn(digits: str) -> bool: """Return True if a string of ASCII digits satisfies the ISO/IEC 7812 Luhn checksum.""" total = 0 # Walk from rightmost check digit leftward, doubling every second digit for idx, ch in enumerate(reversed(digits)): val = int(ch) if idx % 2 == 1: val *= 2 if val > 9: val -= 9 total += val return total % 10 == 0
def redact_card_numbers(log_text: str) -> str: """Replace any Luhn-valid card number in a log message with its masked last-4 form.""" def _mask_if_pan(match): digits = re.sub(r"[ -]", "", match.group(0)) if passes_luhn(digits): return f"[PAN ****{digits[-4:]}]" return match.group(0)
return PAN_CANDIDATE_RE.sub(_mask_if_pan, log_text)
```
Follow-up questions
- What happens if the accounting SFTP server stays unreachable for multiple days?
- Which metrics, health checks, and alerts would you put in place to protect the daily CSV delivery SLA?
- How would you prevent sensitive cardholder PII from leaking into application logs or distributed traces?
Similar questions
- Live Competitive Programming Contest Backend
- Chargeback Lifecycle Ingestion and SFTP Batch Delivery
- Global Live Video Streaming Platform
- Multi-User Collaborative Document Editor
- Burst-Resilient Multi-Channel Notification Platform
- Prior Authorization Status Engine, Clinical Worklists, and Digests