Chargeback Lifecycle Ingestion and SFTP Batch Delivery
Medium · System Design · Software Engineer · Onsite
Prompt
A digital bank handles customer card-purchase disputes (chargebacks) emitted by internal payment microservices. Architect an end-to-end backend pipeline that accepts incoming dispute claims, enforces business and duplicate checks, tracks each claim across its lifecycle, bundles eligible claims on a recurring schedule into standardized CSV exports, and delivers those files over SFTP to external card schemes (such as Visa and Mastercard) ahead of strict settlement cutoffs.
Your design must satisfy these functional rules, guarantees, and operating constraints:
- Claim ingestion & rule checks: Accept incoming dispute payloads, check structural validity and domain constraints (such as permitted reason codes and filing-window age limits), and filter out duplicate submissions.
- Explicit state tracking: Transition every claim cleanly through well-defined lifecycle stages (
RECEIVED,VALIDATED,BATCHED,TRANSMITTED,ACKNOWLEDGED, andREJECTED). - Scheduled batching & immutable CSV creation: On fixed 2-hour cutoff boundaries (12 runs per day, averaging roughly 40,000 records per file), claim all validated, un-exported disputes and build immutable CSV files conforming to each card network's specification.
- Resilient SFTP delivery: Upload batch files to partner SFTP endpoints with automated retries, cryptographic digest verification, and safe recovery or re-transmission when connections drop.
- Financial safety & isolation: Guarantee zero lost monetary claims, strict end-to-end idempotency across upstream retries, immutable archive storage of exported files for dispute audits, and clean decoupling so upstream traffic bursts (
~500,000claims/day;50/ssustained baseline up to500/speak) or flaky, connection-rate-limited partner SFTP servers never stall ingestion.
Scope & Expectations
- Map out the full ingestion-to-SFTP architecture so synchronous/asynchronous intake, validation, file creation, and network delivery remain fault-isolated.
- Design multi-layer idempotency and deduplication across API/queue intake and persistent storage so neither network retries nor duplicate upstream events file twice.
- Define the relational schema, state-transition guards, and concurrency-safe batch-claiming query so concurrent or retried export runs never double-batch or skip records.
- Specify how CSV files are frozen, checksummed, staged, and uploaded over SFTP under flaky links and strict session/connection caps without exposing half-written files.
Step-by-step walkthrough
Clarify requirements and domain rules
A chargeback happens when a cardholder disputes a card purchase (for example, an item never arrived or a card was stolen) and their bank files a formal claim through a card network such as Visa or Mastercard to recover the money. Before drawing boxes, clarify three domain rules that shape the entire design: what counts as a duplicate dispute, how files are organized per card network, and how strict the delivery cutoff is.
Functional requirements
- Ingest and validate: Accept dispute requests over both a synchronous HTTPS API and an asynchronous message topic. Reject malformed payloads immediately, deduplicate repeated submissions, and verify business rules (allowed reason code, transaction age within the network's filing window, and disputed amount not exceeding the original charge).
- Track lifecycle states: Move every chargeback explicitly through
RECEIVED -> VALIDATED -> BATCHED -> TRANSMITTED -> ACKNOWLEDGED, withREJECTED(failed validation or rejected by the card network) andWITHDRAWN(cancelled by the customer before batching). - Batch and export CSVs: Every 2 hours, gather all
VALIDATEDdisputes not yet placed in a file, format one standardized CSV per card network, and store the exact file immutably for audits. - Deliver reliably over SFTP: Upload stored CSVs over SFTP (SSH File Transfer Protocol, an encrypted protocol for transferring files over SSH) with checksum verification, safe retries, and response-file reconciliation.
Non-functional requirements and assumed answers
- Zero data loss: Once our API returns "accepted" (or our consumer commits its queue offset), that dispute is durably recorded and cannot silently disappear.
- Strict idempotency: Idempotency means performing the same operation multiple times has the exact same effect as performing it once. Upstream retries, worker crashes, or mid-file SFTP disconnects must never file the same dispute twice.
- What uniquely identifies one dispute?: The composite key
(card_txn_id, dispute_phase), wheredispute_phaseisFIRST_CHARGEBACK,PRE_ARBITRATION, orARBITRATION. One card purchase can legitimately move to a later phase months later, socard_txn_idalone is too broad, while twoFIRST_CHARGEBACKrequests for the same transaction are duplicates. - Cutoffs and SFTP limits: Assume 2 card networks (Visa and Mastercard). Cutoff windows close every 2 hours (12 windows per day), and each window's file must arrive within 60 minutes of window close to make that processing cycle. Assume each partner SFTP server caps us at 2 concurrent sessions and 20 new connections per hour.
- Audit retention: Keep every transmitted file byte-for-byte, along with its checksum and state history, for 7 years.
Back-of-the-envelope numbers
Before picking databases or queues, translate the daily volume into per-second write rates and file sizes. Notice right away that 500,000 daily claims average ~5.8/s across 24 hours even when 50/s is budgeted as daytime sustained load—calling out that distinction calmly in an interview shows strong engineering judgment.
Ingestion load Daily volume 500,000 events / day True 24-hour average 500,000 / 86,400 s = ~5.8 events/s Daytime sustained budget 50 x 86,400 = 4.32M / day (treat 50/s as sustained headroom) Stated peak 500 events/s -> size the API and database for this peak DB rows written per new event 4 rows (chargeback + idempotency key + audit event + outbox) Peak database row writes 500 x 4 = 2,000 row writes/s Batching and SFTP transfer Cutoff windows per day 12 (every 2 hours) Rows per 2-hour window 500,000 / 12 = ~41,700 rows total (~20,800 rows/file if split across 2 networks, ~40,000 if 1 network) CSV row size ~400 bytes (~25 formatted columns) Typical CSV file size 40,000 x 400 B = ~16 MB (a 5x busy window = ~80 MB) Upload time on a 10 Mbit/s link 16 MB x 8 bits / 10 Mbit/s = ~13 seconds (~64 seconds at 80 MB) 7-year storage footprint Database rows + audit events ~2 KB / dispute x 500,000 = ~1 GB/day -> ~365 GB/year -> ~2.5 TB / 7 yrs Immutable CSV archives 16 MB x 12 = ~192 MB/day -> ~70 GB/year -> ~0.5 TB / 7 yrsThree design conclusions fall straight out of this math:
- One relational primary easily handles the write load. 2,000 small row writes per second at peak is modest for a single PostgreSQL primary on modern NVMe SSDs. We should choose a relational database for its ACID transactions (atomic, consistent, isolated, durable multi-row writes) and unique constraints rather than sharding prematurely.
- Network bandwidth is not the bottleneck. Uploading 16–80 MB takes 13–64 seconds. The real threat to the 60-minute cutoff is burning through the 20-connections-per-hour limit or leaving half-written files after a dropped connection.
- 7 years of audit files (~0.5 TB) is tiny in object storage, so keeping immutable copies of every outbound and inbound CSV is dirt cheap.
API and event contract
Upstream dispute services can either call a synchronous HTTPS endpoint or publish an event to a message topic. Both paths feed into the exact same database transaction.
An idempotency key is a unique string (such as a UUID) generated by the caller before sending a request and reused verbatim on every retry of that request, allowing the server to recognize retries safely.
Synchronous ingestion POST /v1/chargebacks Headers: Idempotency-Key: "d491c2a0-7b18-4f29-9a14-51820c9e4102" Body: { "card_txn_id": "txn_51904822", "dispute_phase": "FIRST_CHARGEBACK", "network": "VISA", "reason_code": "13.1", "amount_minor": 24500, "currency": "USD", "txn_date": "2026-10-14", "customer_id": "cust_41905" } Responses: 202 Accepted { "chargeback_id": "cb_01JF...", "state": "RECEIVED" } (Replayed retries also add header Idempotent-Replay: true) 400 Bad Request Malformed JSON or missing required fields (nothing stored) 409 Conflict { "chargeback_id": "cb_01JE...", "error": "DUPLICATE_DISPUTE" } (Different Idempotency-Key, but same card_txn_id + dispute_phase) 422 Unprocessable Same Idempotency-Key reused with a different request payload Lifecycle and operator endpoints GET /v1/chargebacks/{chargeback_id} -> current state, audit history, batch & file info POST /v1/chargebacks/{chargeback_id}/withdraw -> allowed only in RECEIVED or VALIDATED GET /v1/batches?network=VISA&date=2026-10-20 -> batch status, row count, SHA-256, SFTP attempts POST /v1/batches/{batch_id}/retransmit -> re-queues the already-stored CSV bytes Asynchronous topics Inbound: chargeback.requested (uses event_id as the idempotency key) Outbound: chargeback.state_changed { chargeback_id, from_state, to_state, reason, occurred_at }Why return
202 Acceptedin stateRECEIVEDinstead of running all business checks synchronously? Checking transaction age and original charge amounts requires calling the bank's core transaction ledger. If that ledger is temporarily slow or down, storingRECEIVEDfirst lets us accept disputes without interruption and publish achargeback.state_changedevent (VALIDATEDorREJECTED) seconds later.Data model and lifecycle state machine
To satisfy both fast state queries and strict auditability, separate mutable current-state tables (
chargebacks,batches) from append-only history tables (chargeback_events,batch_items,transfer_attempts).Current-state and coordination tables (PostgreSQL, primary + synchronous standby) chargebacks chargeback_id PK (time-sortable ID) card_txn_id TEXT NOT NULL dispute_phase TEXT NOT NULL UNIQUE (card_txn_id, dispute_phase) -- enforces one record per transaction + phase network, reason_code, amount_minor, currency, txn_date, customer_id state RECEIVED | VALIDATED | BATCHED | TRANSMITTED | ACKNOWLEDGED | REJECTED | WITHDRAWN reject_source NULL | VALIDATION | NETWORK reject_reason TEXT filing_attempt INT NOT NULL DEFAULT 1 -- incremented only if a correctable network reject is re-filed batch_id UUID NULL -- latest batch holding this filing attempt created_at, updated_at PARTIAL INDEX idx_validated ON chargebacks (network, chargeback_id) WHERE state = 'VALIDATED' idempotency_keys (source, idem_key) PK, payload_hash, chargeback_id, response_status, response_body, created_at network_counters network PK, last_file_seq BIGINT NOT NULL uploader_leases network PK, worker_id, expires_at batches batch_id PK, network, window_start, file_seq UNIQUE (network, window_start), UNIQUE (network, file_seq) state OPEN | SEALED | GENERATED | TRANSMITTED | ACKNOWLEDGED | FAILED row_count, total_amount_minor, sealed_at, file_name, object_uri, sha256, size_bytes Append-only audit and frozen-membership tables batch_items (batch_id, line_no) PK chargeback_id, filing_attempt UNIQUE (chargeback_id, filing_attempt) -- makes double-batching the same attempt impossible row_data JSONB NOT NULL -- frozen snapshot of CSV fields at seal time chargeback_events (event_id, occurred_at) PK, chargeback_id, from_state, to_state, actor, details -- partitioned by month on occurred_at outbox outbox_id PK, topic, key, payload, created_at, published_at transfer_attempts (batch_id, attempt_no) PK, worker_id, started_at, ended_at, bytes_sent, outcome, error inbound_files file_name PK, sha256, object_uri, received_at, state network_responses (inbound_file, line_no) PK, chargeback_id, filing_attempt, status, reason_codeNotice why
batch_itemsstores a frozenrow_datasnapshot alongsideUNIQUE (chargeback_id, filing_attempt): if Visa later rejectsfiling_attempt = 1for a fixable data typo and an agent corrects the dispute forfiling_attempt = 2,batch_itemsstill preserves the exact field values that were sent infiling_attempt = 1, and regenerating an old batch's CSV always produces identical bytes.+---> REJECTED (validation) | RECEIVED ---------+---> WITHDRAWN <---------+ | | v | VALIDATED ----------------------------------+ | v (batch sealer claims row) BATCHED | v (SFTP upload + rename verified) TRANSMITTED ------+---> ACKNOWLEDGED (network accepted) | +---> REJECTED (network) ---> [if correctable: fix + filing_attempt + 1] ---> VALIDATEDEvery state transition uses a guarded conditional update—an
UPDATEwhoseWHEREclause demands the expected previous state—paired with an audit-event insert in the same transaction:BEGIN; UPDATE chargebacks SET state = 'VALIDATED', updated_at = now() WHERE chargeback_id = :id AND state = 'RECEIVED'; -- If 0 rows are updated, another worker already transitioned or withdrew this row; roll back safely. INSERT INTO chargeback_events (event_id, chargeback_id, from_state, to_state, actor, occurred_at) VALUES (:event_id, :id, 'RECEIVED', 'VALIDATED', 'validator-worker', now()); COMMIT;End-to-end architecture
Two building blocks keep our pipeline decoupled and auditable:
- The transactional outbox pattern writes outgoing events into an
outboxdatabase table inside the exact same transaction as the state change; a lightweight relay process then publishes those rows to the message broker, preventing the bug where a database commit succeeds but publishing the event crashes. - WORM object storage (Write-Once-Read-Many storage, such as S3 with Object Lock in compliance mode) lets a worker create a file once and blocks everyone—including administrators—from modifying or deleting it until the 7-year retention timer expires.
Upstream microservices | | | HTTPS + Idempotency-Key | Topic: chargeback.requested v v +---------------+ +--------------------+ | Ingestion API | | Ingestion Consumer | (both execute the same idempotent DB transaction) +-------+-------+ +---------+----------+ | | +------------+------------+ v +------------------------------------------------------------------+ | PostgreSQL (Primary + Synchronous Standby) | | chargebacks, idempotency_keys, batches, batch_items, | | chargeback_events, outbox, uploader_leases, transfer_attempts | +----+---------------+------------------+---------------+----------+ | | | | v v v v Validator Batch Sealer CSV Generator Outbox Relay ---> Topic: chargeback.state_changed Workers (every 2h per (reads frozen (ledger check: network: locks batch_items, RECEIVED -> VALIDATED -> computes VALIDATED / BATCHED) SHA-256) REJECTED) | v create-only write +------------------------+ +--------------------------+ | WORM Object Storage | ------> | Leased SFTP Uploader | | (7-yr Object Lock) | | (1 active worker/network,| | .csv + .sha256 | | 20 conn/hr budget) | +------------------------+ +------------+-------------+ ^ | upload .part -> stat -> rename | archive inbound CSV v +------------------------+ +--------------------------+ | Response Poller & | <------ | Card Network SFTP Server | | Reconciler | | (/inbound, /outbound) | +------------------------+ +--------------------------+Decoupling ingestion, CSV generation, and SFTP transmission gives us fault isolation: if Visa's SFTP server goes down for 3 hours, disputes keep entering
RECEIVED -> VALIDATED, 2-hour batches keep sealing intoGENERATEDfiles in WORM storage, and the uploader simply drains the stored files in sequence order once SFTP recovers.- The transactional outbox pattern writes outgoing events into an
Deep dive 1: Three-layer deduplication
Duplicates can enter at three different points, so a single check is not enough. We layer three database-enforced guards:
Duplicate scenario Guard that stops it Caller sees ------------------------------------------- ----------------------------------- ---------------------------- 1. Upstream service times out and retries idempotency_keys (source, idem_key) Original 202 + same ID the exact same HTTP request or event + payload_hash check (or 422 if body changed) 2. Two services (or two user clicks) submit chargebacks UNIQUE 409 Conflict + existing separate requests for the same dispute (card_txn_id, dispute_phase) chargeback_id 3. Worker retry or bug tries to export the batch_items UNIQUE Constraint error; batch same dispute attempt into two CSV files (chargeback_id, filing_attempt) transaction rolls backAt ingestion, Layer 1 and Layer 2 execute together inside one database transaction under PostgreSQL's default
READ COMMITTEDisolation:BEGIN; -- Layer 1: claim the caller's idempotency key. INSERT INTO idempotency_keys (source, idem_key, payload_hash, created_at) VALUES (:source, :idem_key, :payload_hash, now()) ON CONFLICT (source, idem_key) DO NOTHING; -- If 0 rows inserted: this is a retry! Read the existing idempotency_keys row: -- same payload_hash -> roll back and replay stored response_status + response_body; -- different hash -> roll back and return 422 IDEMPOTENCY_KEY_REUSED. -- Layer 2: enforce business uniqueness per transaction and dispute phase. INSERT INTO chargebacks (chargeback_id, card_txn_id, dispute_phase, network, state, ...) VALUES (:new_id, :card_txn_id, :dispute_phase, :network, 'RECEIVED', ...) ON CONFLICT (card_txn_id, dispute_phase) DO NOTHING; -- If 0 rows inserted: another request already filed this dispute! -- Look up existing chargeback_id, save status 409 in idempotency_keys, COMMIT, return 409. INSERT INTO chargeback_events (...) VALUES (...); INSERT INTO outbox (...) VALUES (...); UPDATE idempotency_keys SET chargeback_id = :new_id, response_status = 202, response_body = :response_json WHERE source = :source AND idem_key = :idem_key; COMMIT;Walk through what happens if two identical retries arrive at the exact same millisecond: Transaction B blocks on the
(source, idem_key)unique index until Transaction A commits. Once A commits, B'sINSERT ... ON CONFLICT DO NOTHINGreturns 0 rows, and B's nextSELECTstatement takes a freshREAD COMMITTEDsnapshot that sees A's committed202response. No distributed locks or Redis caches are required.Why not put deduplication only in Redis with a 24-hour TTL (time-to-live)? At 500 peak writes/s, PostgreSQL handles the unique index check directly in under a millisecond. A Redis cache introduces a second store that can lose keys during failover or let a delayed retry slip through after the 24-hour TTL expires, creating an illegal duplicate filing.
Deep dive 2: Race-free batch sealing with row locks
Every 2 hours, the batch sealer gathers eligible disputes for each card network. Two subtle traps ruin naive batching jobs:
- The timestamp-window trap: Suppose a cron job runs
SELECT * FROM chargebacks WHERE validated_at >= '08:00' AND validated_at < '10:00'right at10:00:00. If a validator worker setsvalidated_at = '09:59:59.900'in memory, pauses briefly, and commits at10:00:00.200, the10:00batch already ran without seeing that uncommitted row—and the12:00batch checksvalidated_at >= '10:00'and skips it forever! - The read-then-mark race: If Job 1 runs
SELECT ... WHERE state = 'VALIDATED', generates a CSV, and only then runsUPDATE ... SET state = 'BATCHED', an overlapping or retried Job 2 will read the exact sameVALIDATEDrows and export them a second time.
We eliminate both traps by claiming by current state (
state = 'VALIDATED') inside an atomic transaction usingFOR UPDATE SKIP LOCKED.FOR UPDATE SKIP LOCKEDis a SQL clause that locks each matching row for our transaction while immediately skipping any row currently locked by another transaction (such as a customerwithdrawcall happening at that exact instant).BEGIN; -- 1. Serialize sealers per network and allocate a gapless sequence number. UPDATE network_counters SET last_file_seq = last_file_seq + 1 WHERE network = :network RETURNING last_file_seq; -- bound to :seq -- 2. Ensure at most one batch exists for (network, window_start). INSERT INTO batches (batch_id, network, window_start, file_seq, state) VALUES (:batch_id, :network, :window_start, :seq, 'OPEN') ON CONFLICT (network, window_start) DO NOTHING; -- If 0 rows inserted: this window was already sealed! ROLLBACK (undoing :seq increment too). -- 3. Atomically lock and transition all currently VALIDATED rows for this network. WITH claimed AS ( SELECT chargeback_id, filing_attempt, reason_code, amount_minor, currency, txn_date FROM chargebacks WHERE network = :network AND state = 'VALIDATED' ORDER BY chargeback_id FOR UPDATE SKIP LOCKED ) UPDATE chargebacks c SET state = 'BATCHED', batch_id = :batch_id, updated_at = now() FROM claimed WHERE c.chargeback_id = claimed.chargeback_id; -- 4. Freeze exact line numbers and field snapshots in batch_items. INSERT INTO batch_items (batch_id, line_no, chargeback_id, filing_attempt, row_data) SELECT :batch_id, ROW_NUMBER() OVER (ORDER BY chargeback_id), chargeback_id, filing_attempt, jsonb_build_object('card_txn_id', card_txn_id, 'reason_code', reason_code, 'amount_minor', amount_minor, 'currency', currency, 'txn_date', txn_date) FROM chargebacks WHERE batch_id = :batch_id; -- 5. Seal the batch with control totals. UPDATE batches SET state = 'SEALED', sealed_at = now(), row_count = (SELECT COUNT(*) FROM batch_items WHERE batch_id = :batch_id), total_amount_minor = (SELECT COALESCE(SUM((row_data->>'amount_minor')::bigint), 0) FROM batch_items WHERE batch_id = :batch_id) WHERE batch_id = :batch_id; COMMIT;Why this works cleanly under every race:
- Zero lost rows at cutoff boundaries: Any validator or locked
withdrawtransaction that misses the10:00lock staysVALIDATED(if not withdrawn) and is automatically picked up by the12:00seal. - Gapless file sequence numbers: Card networks often reject files if sequence numbers jump from
41to43. Becausenetwork_countersincrements inside the same transaction asINSERT INTO batches, a duplicate cron run rolls back both statements and leaves zero gaps. - Fast execution: Locking and updating ~20,000–40,000 rows via the partial index
WHERE state = 'VALIDATED'takes 1–2 seconds in PostgreSQL. If batch sizes ever grew to millions of rows, we would claim in loops ofLIMIT 5000into theOPENbatch before flippingOPEN -> SEALED.
- The timestamp-window trap: Suppose a cron job runs
Deep dive 3: Deterministic CSV generation and resilient SFTP delivery
Generating a CSV and uploading it over SFTP are deliberately split into two independent steps separated by WORM object storage.
Step A: Generate once and freeze in WORM storage
- A generator worker picks up a
SEALEDbatch and reads onlybatch_itemsordered byline_no—never livechargebacks. - Formatting is strictly deterministic (given the same
batch_items, it produces the exact same bytes every time): timestamps inside the header come frombatches.sealed_atrather than wall-clocknow(), numbers use integer minor units or fixed decimals, strings follow RFC 4180 CSV escaping, and line endings are fixed. - Before saving, the worker verifies that the generated line count and sum match
batches.row_countandbatches.total_amount_minor. - If a card network mandates PGP encryption (public-key file encryption common in banking), note that PGP generates a fresh random session key on every run, so encrypting twice produces different ciphertext bytes. We therefore write the plaintext audit CSV (encrypted at rest with our bank KMS key) and the exact outbound
.csv.pgpplus its.sha256digest to WORM storage using a create-only condition (If-None-Match: *), then updatebatches.state = 'GENERATED'. Every SFTP retry now streams the exact stored outbound object—never re-generating or re-encrypting.
Step B: Single-leased SFTP upload with staging and atomic rename
To stay strictly inside the partner's 2-session and 20-connections-per-hour limits while keeping files in
file_seqorder, one uploader worker per network acquires a lease—a row inuploader_leaseswith a 90-second expiration renewed every 30 seconds. If that worker crashes, its lease expires after 90 seconds and a standby worker takes over.Uploading directly to
inbound/visa_0018.csvis dangerous: if the TCP connection drops at 50%, the partner's pickup job can ingest a half-written file! Instead, we upload to a temporary.partname that the partner ignores, verify the byte count, and atomically rename:Uploader Worker Partner SFTP Server (/inbound) | | | 1. Check hourly connection budget (<= 15/hr used) | |--- SSH connect (pinned host key + client key) ---->| |--- STAT visa_0018.csv ---------------------------->| Already exists with size_bytes? Jump to step 7! |--- STAT visa_0018.csv.part ----------------------->| Partial file? Resume at offset (or overwrite) |--- WRITE stream -> visa_0018.csv.part ------------>| |--- STAT visa_0018.csv.part ----------------------->| Confirm remote size == batches.size_bytes | [Log "UPLOAD_VERIFIED" in transfer_attempts] | |--- POSIX RENAME .part -> visa_0018.csv ----------->| Atomic: partner sees 0% or 100% of file | 7. Mark batch + batch_items rows TRANSMITTED |Handling the hardest SFTP failure modes:
- Checksum verification: Standard SFTP v3 has no built-in remote hash command. We verify exact
size_bytesviaSTAT, upload the companionvisa_0018.csv.sha256manifest (plus trailer row/amount totals inside the CSV) so the card network validates cryptographic integrity before ingesting, and confirm via the network's acknowledgment file. - Connection-budget protection: Transient network errors retry with exponential backoff and jitter (waiting 15 s, 30 s, 1 min, 2 min, 5 min with small random offsets so retries don't collide), capped at 12 upload connections per hour so ~5 connections remain for response polling. Permanent errors (
Authentication failed,Permission denied) stop retrying immediately and page on-call so we don't lock out our credentials. - Ambiguous disconnect during
RENAME: Suppose the connection drops while step 6 (RENAME) is in flight. On reconnect, step 2 checksSTAT visa_0018.csv. What if neithervisa_0018.csvnorvisa_0018.csv.partis there? Because our prior attempt loggedUPLOAD_VERIFIED, the partner's pickup job almost certainly grabbed and moved the finished file! Rather than blindly re-uploading—which could double-submit 20,000 disputes if the partner doesn't deduplicatefile_seq—the worker pauses and checks the outbound receipt folder (or alerts operations) first.
- A generator worker picks up a
Scaling, failure recovery, and auditability
Failure event How the system recovers without losing or duplicating data ---------------------------------------- ------------------------------------------------------------------- API crashes after DB commit, before 202 Caller retries with same Idempotency-Key -> gets stored 202 replay PostgreSQL primary node dies Automatic failover to synchronous standby (zero committed rows lost) Core ledger service is down for 1 hour Disputes accumulate safely in RECEIVED; ingestion stays 100% up Two batch sealers trigger simultaneously network_counters lock + UNIQUE(network, window_start) stops second run CSV generator crashes after WORM write Rerun sees object already exists via If-None-Match, updates DB state Partner SFTP server down for 4 hours Batches queue in GENERATED state; uploaded in file_seq order later Network rejects 3 rows in response CSV Reconciler marks 3 rows REJECTED (network) and 39,997 ACKNOWLEDGEDScaling notes and database partitioning trap
- Do not partition
chargebacksbycreated_atin PostgreSQL: PostgreSQL requires everyUNIQUEindex on a partitioned table to include the partition column. Partitioningchargebacksby month would forcecreated_atintoUNIQUE (card_txn_id, dispute_phase, created_at), allowing duplicate disputes across month boundaries! Keep activechargebacksin one unpartitioned table (~180M rows/year fits comfortably with B-tree indexes) and archive closed disputes older than network deadlines to cold storage, while partitioning append-onlychargeback_eventsby month. - If volume ever grows 100x (50M events/day): Shard
chargebackshorizontally byhash(card_txn_id)so(card_txn_id, dispute_phase)uniqueness stays inside a single shard, claim validated rows per shard intobatch_items, and switch from single-file SFTP over 2 sessions to multi-part managed file transfer or direct card-network APIs.
Continuous audit invariants (checked every 15 minutes):
- Every accepted
chargeback_idis accounted for across states (COUNT(*)conservation), and zeroVALIDATEDrows are older than 2 cutoff windows (4 hours). - For every sealed batch,
batches.row_count == COUNT(batch_items) == CSV trailer count, and anyGENERATEDbatch still un-transmitted 30 minutes into its 60-minute cutoff window pages on-call immediately.
- Do not partition
Intuition & how it works
Think of this system like an armored mailroom at a bank. Throughout the day, customer-service desks drop off signed dispute forms. Before accepting a form, the mailroom clerk stamps it in a master ledger so nobody can file two claims for the same card purchase. Every two hours, a supervisor locks a stack of verified forms into a numbered pouch, photographs every page for the 7-year audit vault, and hands the sealed pouch to a single courier. The courier uploads the pouch to Visa or Mastercard under a temporary "in-progress" label and only flips the label to "ready for pickup" once every byte has arrived.
A naive script that runs every two hours, queries WHERE created_at >= now() - 2 hours, builds a CSV in memory, and streams it straight to SFTP fails in three ways. First, upstream retries or overlapping cron jobs submit the same monetary dispute twice. Second, database transactions that start just before 10:00:00 and commit a split-second after 10:00:00 miss the 10:00 timestamp query and look too old for the 12:00 query, silently vanishing. Third, if the SFTP connection drops halfway through streaming an in-memory CSV, the card network can ingest a truncated file while our retry generates a slightly different CSV than what we logged.
Walk through a tiny concrete trace with one dispute (card_txn_id = "txn_51904822", dispute_phase = "FIRST_CHARGEBACK", $245.00) to see how each safeguard works:
- Ingest & deduplicate: Service A sends
POST /v1/chargebackswith idempotency key (a caller-generated unique token reused on retries)key_a. One database transaction insertskey_a, insertscb_204in stateRECEIVEDunderUNIQUE (card_txn_id, dispute_phase), and returns202 Accepted. When Service A times out and retrieskey_a, it gets the stored202replay; when Service B accidentally submitstxn_51904822again withkey_b, the(card_txn_id, dispute_phase)unique index catches it and returns409 Conflict. - Validate asynchronously: A validator worker checks
txn_51904822against the bank's ledger and movescb_204fromRECEIVEDtoVALIDATED. - Seal by state, not timestamp: At
10:00 UTC, the batch sealer allocates gaplessfile_seq = 18, locks all rows currently instate = 'VALIDATED'usingFOR UPDATE SKIP LOCKED(a SQL row-locking clause that locks available rows and skips any row currently locked by another transaction), flipscb_204toBATCHED, and freezes its exact CSV fields asline_no = 1inbatch_items. - Freeze CSV, then upload safely: The generator reads frozen
batch_items, writesvisa_0018.csvand its SHA-256 checksum once to WORM object storage (Write-Once-Read-Many storage that blocks edits and deletions for 7 years), and marks the batchGENERATED. The network's single leased SFTP uploader streams those exact bytes toinbound/visa_0018.csv.part, verifies the remote file size, atomically renames it toinbound/visa_0018.csv, and markscb_204TRANSMITTED—ready to flip toACKNOWLEDGEDwhen Visa's response CSV arrives 24 hours later.
Key trade-offs
- Relational unique constraints vs. a Redis TTL cache for deduplication. Storing idempotency keys and
UNIQUE (card_txn_id, dispute_phase)in PostgreSQL inside the same ACID transaction (an all-or-nothing database write) guarantees the deduplication state never drifts from the stored chargebacks and never expires early. A Redis cache with a TTL (time-to-live expiration) responds slightly faster, but cache eviction, failover, or retries arriving after the TTL would allow illegal duplicate chargebacks. At 500 peak writes per second, PostgreSQL handles this directly without a cache. - Accept as
RECEIVEDfirst vs. synchronous business validation. Returning202 Acceptedas soon as the request is durably written decouples ingestion from downstream ledger outages and traffic spikes. The trade-off is that business-rule rejections (REJECTED) are delivered asynchronously via events rather than inside the initial HTTP response. - Claiming batches by
state = 'VALIDATED'withSKIP LOCKEDvs. plainFOR UPDATEor timestamps. Claiming by state ensures zero rows slip through timestamp boundaries. AddingSKIP LOCKEDkeeps the batch sealer fast if a customer is concurrently withdrawing a single dispute, pushing that contested row to the next 2-hour window rather than making the whole batch wait. - Storing generated CSVs in WORM storage before SFTP vs. streaming directly from the database. Writing an immutable file first adds one object-storage hop and an extra batch state (
GENERATED), but guarantees every SFTP retry transmits byte-for-byte identical data (especially critical when PGP encryption adds randomness per encryption run) and ensures our 7-year audit copy matches what the partner received. - Single leased uploader per network vs. parallel SFTP workers. Using a database lease (a time-bounded ownership lock renewed by heartbeats) caps us at one active SFTP session per card network. That sacrifices parallel upload bandwidth we do not need (16–80 MB uploads in under a minute) in exchange for respecting the partner's 2-session limit and keeping
file_seqdeliveries strictly ordered.
Common mistakes
- Relying only on an in-memory or TTL-expiring cache for idempotency, allowing crashes or late retries to file duplicate monetary claims.
- Deduplicating only on
Idempotency-Key(or only oncard_txn_id):Idempotency-Keyalone misses duplicate disputes created by two separate upstream calls, whilecard_txn_idalone wrongly blocks legitimatePRE_ARBITRATIONfilings months after aFIRST_CHARGEBACK. - Batching with timestamp filters (
WHERE validated_at < cutoff), silently dropping in-flight transactions that generated an earlier timestamp before committing slightly after the cutoff. - Querying
VALIDATEDrows, generating the CSV, and markingBATCHEDat the end, which lets two overlapping cron runs export the same rows twice. - Re-generating or re-encrypting the CSV from live rows on every SFTP retry, causing the partner's file and the internal audit archive to diverge.
- Partitioning the
chargebackstable by month in PostgreSQL, which forces the date column into everyUNIQUEindex and breaks global(card_txn_id, dispute_phase)uniqueness across months. - Uploading directly to the final filename on the SFTP server, exposing half-written CSVs to the partner's pickup job whenever a connection drops mid-transfer.
- Retrying permanent SFTP errors (like expired SSH keys) in a tight loop, burning the 20-connections-per-hour budget and getting locked out instead of paging an operator immediately.
Follow-up questions
- Suppose the card scheme drops a return CSV a day later flagging specific rows as rejected—how would you architect the ingestion and reconciliation flow to update individual claims? A scheduled response poller (sharing the hourly SFTP connection budget with the uploader) lists the partner's outbound directory, archives each unseen file unchanged into WORM object storage, and records it in
inbound_fileskeyed by filename so re-downloads are harmless no-ops. A reconciler worker then parses each row intonetwork_responseskeyed by(inbound_file, line_no)and joins back to our exact filing via(chargeback_id, filing_attempt)(or(batch_id, line_no)). Each row runs a guarded transaction transitioningTRANSMITTED -> ACKNOWLEDGEDorTRANSMITTED -> REJECTED(withreject_source = 'NETWORK'and the partner's error code) while writing an audit event and an outbox message so upstream services notify the customer or queue correctable errors for re-filing underfiling_attempt + 1. Finally, a monitor alerts if anyTRANSMITTEDbatch has not received a response file within 36 hours. - What upload protocol prevents the partner's pickup job from reading a truncated or corrupt CSV when an SFTP session disconnects mid-transfer? Upload every file to a temporary staging filename such as
inbound/visa_0018.csv.part(or a/stagingdirectory on the same filesystem) that the partner's ingestion job explicitly ignores, verify via SFTPSTATthat the remote byte size matchesbatches.size_bytes, and only then issue an atomic POSIXRENAMEtoinbound/visa_0018.csvalongside its.sha256checksum manifest. Because same-filesystem rename is atomic, the partner sees either nothing or the complete file, and the trailer totals plus SHA-256 manifest let the partner verify integrity before processing. On reconnect after a mid-transfer drop, the worker checksSTATon the final filename first, then resumes or overwrites.part; if a prior attempt already verified the.partupload and both filenames are now gone, the partner likely picked up the renamed file, so the worker checks for a partner receipt before re-uploading. - Which signals and alerting thresholds would you instrument to warn operators before persistent SFTP timeouts cause a missed settlement cutoff? Instrument four metrics per card network: age of the oldest un-transmitted
GENERATEDbatch relative to its 60-minute cutoff deadline, consecutive SFTP failure count, remaining hourly connection budget, and periodic 10-minute lightweight connectivity probes between batch windows. Configure tiered alerts: warn after 3 consecutive connection timeouts, page on-call if a batch is still notTRANSMITTED30 minutes after window close (50% of the cutoff budget burned) or whenevertime_to_cutoff < estimated_upload_time + next_backoff_delay, and escalate at 45 minutes with a runbook to fail over to a secondary SFTP endpoint or manual partner portal upload. Separately, flag high-priority alerts whenever a delayed batch contains disputes within 24 hours of their final card-network filing deadline.
Follow-up questions
- Suppose the card scheme drops a return CSV a day later flagging specific rows as rejected—how would you architect the ingestion and reconciliation flow to update individual claims?
- What upload protocol prevents the partner's pickup job from reading a truncated or corrupt CSV when an SFTP session disconnects mid-transfer?
- Which signals and alerting thresholds would you instrument to warn operators before persistent SFTP timeouts cause a missed settlement cutoff?
Similar questions
- Chargeback Webhook Pipeline and Daily SFTP Export
- Live Competitive Programming Contest Backend
- Global Live Video Streaming Platform
- Multi-User Collaborative Document Editor
- Burst-Resilient Multi-Channel Notification Platform
- Prior Authorization Status Engine, Clinical Worklists, and Digests