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, and REJECTED).
  • 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,000 claims/day; 50/s sustained baseline up to 500/s peak) 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

  1. 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, with REJECTED (failed validation or rejected by the card network) and WITHDRAWN (cancelled by the customer before batching).
    • Batch and export CSVs: Every 2 hours, gather all VALIDATED disputes 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), where dispute_phase is FIRST_CHARGEBACK, PRE_ARBITRATION, or ARBITRATION. One card purchase can legitimately move to a later phase months later, so card_txn_id alone is too broad, while two FIRST_CHARGEBACK requests 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.
  2. 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 yrs
    

    Three design conclusions fall straight out of this math:

    1. 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.
    2. 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.
    3. 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.
  3. 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 Accepted in state RECEIVED instead 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, storing RECEIVED first lets us accept disputes without interruption and publish a chargeback.state_changed event (VALIDATED or REJECTED) seconds later.

  4. 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_code
    

    Notice why batch_items stores a frozen row_data snapshot alongside UNIQUE (chargeback_id, filing_attempt): if Visa later rejects filing_attempt = 1 for a fixable data typo and an agent corrects the dispute for filing_attempt = 2, batch_items still preserves the exact field values that were sent in filing_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] ---> VALIDATED
    

    Every state transition uses a guarded conditional update—an UPDATE whose WHERE clause 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;
    
  5. End-to-end architecture

    Two building blocks keep our pipeline decoupled and auditable:

    • The transactional outbox pattern writes outgoing events into an outbox database 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 into GENERATED files in WORM storage, and the uploader simply drains the stored files in sequence order once SFTP recovers.

  6. 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 back
    

    At ingestion, Layer 1 and Layer 2 execute together inside one database transaction under PostgreSQL's default READ COMMITTED isolation:

    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's INSERT ... ON CONFLICT DO NOTHING returns 0 rows, and B's next SELECT statement takes a fresh READ COMMITTED snapshot that sees A's committed 202 response. 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.

  7. 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:

    1. The timestamp-window trap: Suppose a cron job runs SELECT * FROM chargebacks WHERE validated_at >= '08:00' AND validated_at < '10:00' right at 10:00:00. If a validator worker sets validated_at = '09:59:59.900' in memory, pauses briefly, and commits at 10:00:00.200, the 10:00 batch already ran without seeing that uncommitted row—and the 12:00 batch checks validated_at >= '10:00' and skips it forever!
    2. The read-then-mark race: If Job 1 runs SELECT ... WHERE state = 'VALIDATED', generates a CSV, and only then runs UPDATE ... SET state = 'BATCHED', an overlapping or retried Job 2 will read the exact same VALIDATED rows and export them a second time.

    We eliminate both traps by claiming by current state (state = 'VALIDATED') inside an atomic transaction using FOR UPDATE SKIP LOCKED. FOR UPDATE SKIP LOCKED is a SQL clause that locks each matching row for our transaction while immediately skipping any row currently locked by another transaction (such as a customer withdraw call 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 withdraw transaction that misses the 10:00 lock stays VALIDATED (if not withdrawn) and is automatically picked up by the 12:00 seal.
    • Gapless file sequence numbers: Card networks often reject files if sequence numbers jump from 41 to 43. Because network_counters increments inside the same transaction as INSERT 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 of LIMIT 5000 into the OPEN batch before flipping OPEN -> SEALED.
  8. 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

    1. A generator worker picks up a SEALED batch and reads only batch_items ordered by line_no—never live chargebacks.
    2. Formatting is strictly deterministic (given the same batch_items, it produces the exact same bytes every time): timestamps inside the header come from batches.sealed_at rather than wall-clock now(), numbers use integer minor units or fixed decimals, strings follow RFC 4180 CSV escaping, and line endings are fixed.
    3. Before saving, the worker verifies that the generated line count and sum match batches.row_count and batches.total_amount_minor.
    4. 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.pgp plus its .sha256 digest to WORM storage using a create-only condition (If-None-Match: *), then update batches.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_seq order, one uploader worker per network acquires a lease—a row in uploader_leases with 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.csv is 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 .part name 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_bytes via STAT, upload the companion visa_0018.csv.sha256 manifest (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 checks STAT visa_0018.csv. What if neither visa_0018.csv nor visa_0018.csv.part is there? Because our prior attempt logged UPLOAD_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 deduplicate file_seq—the worker pauses and checks the outbound receipt folder (or alerts operations) first.
  9. 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 ACKNOWLEDGED
    

    Scaling notes and database partitioning trap

    • Do not partition chargebacks by created_at in PostgreSQL: PostgreSQL requires every UNIQUE index on a partitioned table to include the partition column. Partitioning chargebacks by month would force created_at into UNIQUE (card_txn_id, dispute_phase, created_at), allowing duplicate disputes across month boundaries! Keep active chargebacks in 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-only chargeback_events by month.
    • If volume ever grows 100x (50M events/day): Shard chargebacks horizontally by hash(card_txn_id) so (card_txn_id, dispute_phase) uniqueness stays inside a single shard, claim validated rows per shard into batch_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_id is accounted for across states (COUNT(*) conservation), and zero VALIDATED rows are older than 2 cutoff windows (4 hours).
    • For every sealed batch, batches.row_count == COUNT(batch_items) == CSV trailer count, and any GENERATED batch still un-transmitted 30 minutes into its 60-minute cutoff window pages on-call immediately.

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:

  1. Ingest & deduplicate: Service A sends POST /v1/chargebacks with idempotency key (a caller-generated unique token reused on retries) key_a. One database transaction inserts key_a, inserts cb_204 in state RECEIVED under UNIQUE (card_txn_id, dispute_phase), and returns 202 Accepted. When Service A times out and retries key_a, it gets the stored 202 replay; when Service B accidentally submits txn_51904822 again with key_b, the (card_txn_id, dispute_phase) unique index catches it and returns 409 Conflict.
  2. Validate asynchronously: A validator worker checks txn_51904822 against the bank's ledger and moves cb_204 from RECEIVED to VALIDATED.
  3. Seal by state, not timestamp: At 10:00 UTC, the batch sealer allocates gapless file_seq = 18, locks all rows currently in state = 'VALIDATED' using FOR UPDATE SKIP LOCKED (a SQL row-locking clause that locks available rows and skips any row currently locked by another transaction), flips cb_204 to BATCHED, and freezes its exact CSV fields as line_no = 1 in batch_items.
  4. Freeze CSV, then upload safely: The generator reads frozen batch_items, writes visa_0018.csv and 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 batch GENERATED. The network's single leased SFTP uploader streams those exact bytes to inbound/visa_0018.csv.part, verifies the remote file size, atomically renames it to inbound/visa_0018.csv, and marks cb_204 TRANSMITTED—ready to flip to ACKNOWLEDGED when 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 RECEIVED first vs. synchronous business validation. Returning 202 Accepted as 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' with SKIP LOCKED vs. plain FOR UPDATE or timestamps. Claiming by state ensures zero rows slip through timestamp boundaries. Adding SKIP LOCKED keeps 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_seq deliveries 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 on card_txn_id): Idempotency-Key alone misses duplicate disputes created by two separate upstream calls, while card_txn_id alone wrongly blocks legitimate PRE_ARBITRATION filings months after a FIRST_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 VALIDATED rows, generating the CSV, and marking BATCHED at 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 chargebacks table by month in PostgreSQL, which forces the date column into every UNIQUE index 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_files keyed by filename so re-downloads are harmless no-ops. A reconciler worker then parses each row into network_responses keyed 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 transitioning TRANSMITTED -> ACKNOWLEDGED or TRANSMITTED -> REJECTED (with reject_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 under filing_attempt + 1. Finally, a monitor alerts if any TRANSMITTED batch 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 /staging directory on the same filesystem) that the partner's ingestion job explicitly ignores, verify via SFTP STAT that the remote byte size matches batches.size_bytes, and only then issue an atomic POSIX RENAME to inbound/visa_0018.csv alongside its .sha256 checksum 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 checks STAT on the final filename first, then resumes or overwrites .part; if a prior attempt already verified the .part upload 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 GENERATED batch 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 not TRANSMITTED 30 minutes after window close (50% of the cutoff budget burned) or whenever time_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

Similar questions

More Nubank interview questions

All 3 Nubank questions →