Monthly Creator Royalty Calculation and Payouts

Medium · System Design · Software Engineer · Technical Screen

Prompt

Design the backend for a music and audio streaming service that tallies qualifying track plays, aggregates monthly play totals per creator, computes creator royalties, and disburses funds through a third-party payment gateway. Every outbound disbursement request must attach an idempotency key so retries across network drops or worker crashes can never pay a creator twice for the same monthly obligation.

State clear assumptions before diving into components: define what qualifies a playback event as royalty-bearing and whether post-cutoff fraud or rights revisions can arrive weeks later; choose between uniform per-play rates and custom creator agreements; establish when a monthly billing window closes and how late adjustments roll forward; and specify the rate limits, status lookups, and webhook delivery semantics provided by the external payment gateway.

Scope & Expectations

  • Playback ingestion, deduplication, and period cutoff: Show how high-volume play telemetry is collected, deduplicated across mobile retries and offline syncs, validated against eligibility caps, and frozen into a closed monthly window without mutating historical periods when late data arrives.
  • Reproducible royalty math and ledger schema: Design versioned calculation records and integer-precision accounting tables that turn validated track counts, contractual rates/splits, and prior-month adjustments into deterministic creator obligations.
  • Idempotent disbursement state machine: Walk through payout and attempt state transitions, commit-before-call transactional handoffs to the external payment gateway, idempotency-key rules, and safe retry handling across ambiguous timeouts, permanent bank rejections, and unordered webhooks.
  • Provider reconciliation and auditability: Explain how internal ledgers, gateway settlement files, and treasury bank statements are reconciled daily, and how every historical cent or creator play-count dispute traces back to immutable evidence.

Step-by-step walkthrough

  1. Clarify requirements, assumptions, and answers to key questions

    This problem combines two fundamentally different workloads under one roof: 1. A high-throughput telemetry pipeline that ingests ~1 billion audio play events per day cheaply and tolerates mobile retries and offline uploads. 2. A strict financial accounting & payout engine that sends ~300,000 real bank payouts once a month and must never double-pay, lose a fraction of a cent, or silently rewrite past statements.

    The core architectural insight is to keep those two worlds separate and connect them once a month through a sealed, immutable snapshot (manifest) so every dollar paid is 100% reproducible.

    Core design assumptions

    • Stream eligibility and post-cutoff revisions: A playback event qualifies as royalty-bearing ("valid") when listening reaches >= 30 seconds, the listener account is in good standing, the track holds an active territorial license at play time, neither listener nor device is flagged for bot-stream manipulation, and the listener has logged at most 20 qualifying plays of that track on that UTC day. Coordinated stream-farming investigations and split/ownership amendments routinely surface weeks after a billing month closes.
    • Contractual rates and co-creator splits: Creators hold versioned contracts specifying a per-stream rate in micro-dollars (1 micro-dollar = $0.000001), paired with per-track ownership splits expressed in basis points (100 bps = 1%, 10,000 bps = 100% across co-creators and labels). We contrast this with a shared pro-rata revenue pool in the trade-offs.
    • Monthly window cutoff and forward adjustments: Accounting month YYYY-MM seals at a deterministic cutoff of 00:00 UTC on the 4th day of the following month (leaving 72 hours for offline mobile plays to sync). Once approved, a closed month is strictly immutable; late-arriving offline plays and post-cutoff fraud or split corrections post as explicit adjustment lines in the next open cycle. Minimum disbursement is $10.00, with smaller balances carrying forward automatically.
    • Payment gateway semantics and webhooks: The external gateway honors an Idempotency-Key header (retained for at least 7 days), indexes our permanent reference identifier for status queries (GET /payouts?reference=...), enforces a 20 requests/s rate cap, delivers HMAC-signed webhooks at least once and potentially out of order, and exports a daily settlement file.

    Functional & non-functional summary

    • Correctness over latency: August royalties disburse around September 10. Zero duplicate wires, zero lost obligations, and byte-identical output whenever a sealed month's calculation is replayed.
    • End-to-end auditability: every cent paid traces back to specific input files, contract versions, and adjustment approvals. Financial records are append-only (no UPDATE/DELETE on ledger or calculation lines) and retained for 7+ years.
    • Fault isolation: play ingestion absorbs 1B events/day (3x evening peak) even if the financial database or external payment provider is completely offline.
  2. Back-of-the-envelope capacity estimates

    1. Streaming ingestion (Big Data — immutable object storage + batch Spark)
       Daily active listeners        40M DAU * 25 plays/day = 1.0B raw play events/day
       Throughput                    1B / 86,400 s = ~11,600 events/s avg, ~35,000 events/s peak (3x)
       Raw event payload             ~300 bytes -> ~300 GB/day raw (~9 TB/month)
       Parquet lake (~5x compressed) ~60 GB/day -> ~1.8 TB/month
       Valid billable share (~70%)   ~700M valid streams/day -> ~21B valid streams/month
    
    2. Monthly royalty calculation & payouts (Small Data — single ACID PostgreSQL cluster)
       Active tracks streamed/month  ~10M tracks
       Artists with >= 1 stream      ~1.5M artists
       Artists >= $10.00 threshold   ~300,000 payouts/month
       Illustrative payout pool      21B valid streams * ~$0.003 avg = ~$63M/month
       External provider send time   300,000 payouts / 20 req/s = 15,000 s = ~4.2 hours
    
    3. Financial database row growth
       Ledger rows/month             1.5M accruals (2 entries each) + 300k payouts * 2 stages * 2 entries
                                     = 3.0M + 1.2M = ~4.2M ledger rows/month
       Payouts + attempts + events   ~1M rows/month
    

    What these numbers tell us: the event pipeline handles terabytes and belongs on Kafka + Parquet object storage + daily Spark jobs, whereas the financial state is tiny (~5 million rows a month). A single PostgreSQL primary with a synchronous cross-AZ standby handles the financial side effortlessly, giving us full ACID transactions, foreign keys, and partial unique indexes without distributed-database complexity.

  3. APIs: play ingestion, finance operations, artist portal, and provider

    1. Client Play Ingestion (Mobile / Web / Desktop SDKs, authenticated session)
       POST /v1/plays:batch
       {
         "events": [
           { "event_id": "9b4d2e71-...", "track_id": "trk_501",
             "started_at": "2026-08-31T23:58:10Z", "ms_played": 194000,
             "device_id": "dev_18", "offline": true }
         ]
       }
       -> 202 Accepted { "accepted": 50 }
       (Client generates event_id when playback reaches 30 s or ends, and reuses the exact same
        event_id if retrying offline uploads; server stamps user_id, country, and ingest_time.)
    
    2. Internal Finance & Calculation Control
       POST /v1/periods/2026-08/runs            -> 201 { "run_id": "run_01", "version": 1 }
       GET  /v1/runs/{run_id}/summary           -> totals, month-over-month diffs, anomaly flags
       POST /v1/runs/{run_id}/approve           -> requires 2nd distinct finance approver (maker-checker)
       POST /v1/adjustments
            { "artist_id": "art_14", "track_id": "trk_501", "origin_period": "2026-07",
              "delta_streams": -30000, "reason": "BOT_FARM_REVERSAL", "evidence_ref": "case_612" }
    
    3. Artist Portal & Disputes
       GET  /v1/artists/{artist_id}/statements/2026-08
            -> per-track valid streams, excluded counts by reason, contract rate, split %, net amount
       POST /v1/artists/{artist_id}/disputes    { "period": "2026-08", "track_id": "trk_501", "claim": "..." }
       GET  /v1/artists/{artist_id}/disputes/{dispute_id}
    
    4. External Payment Provider Integration
       Outbound: POST https://provider.example/v1/payouts
                 Headers: Idempotency-Key: att_4b8e21...
                 Body:    { "amount_cents": 556611, "currency": "USD",
                            "destination_token": "ba_...", "reference": "att_4b8e21..." }
       Inquiry:  GET  https://provider.example/v1/payouts?reference=att_4b8e21...
       Inbound:  POST /v1/webhooks/provider     (HMAC-signed, delivered >= 1 time, unordered)
    

    Notice a critical detail on the outbound provider call: we pass attempt_id (att_4b8e21...) as both the HTTP Idempotency-Key header and the permanent reference field. Even if the provider purges idempotency keys after 7 days, GET /payouts?reference=att_4b8e21... lets us look up whether that attempt ever succeeded weeks later.

  4. Data model: immutable data lake and ACID financial database

    ================ DATA LAKE (Object Storage with WORM Object Lock, Parquet) ================
    raw_plays/ingest_hour=2026-08-31T23/part-*.parquet
      (event_id, user_id, track_id, started_at, ms_played, country, device_id, ingest_time)
    
    plays_checked/event_date=2026-08-31/snapshot=.../part-*.parquet
      -- exact 1 row per unique event_id for that event_date + verdict + reason_code
      -- enables exact cross-day deduplication AND exact 20-plays/user/track/day cap across late uploads
    
    daily_counts/period=2026-08/ingest_date=2026-09-01/run_id=.../part-*.parquet
      (track_id, home_period, valid_streams, excl_short, excl_dup, excl_cap, excl_fraud, excl_unlicensed)
    
    manifests/2026-08.json
      -- immutable JSON listing exact daily_counts file URIs + SHA-256 hashes, approved adjustment_ids,
      -- as_of_recorded_at timestamp for contracts/splits, and calculator git commit SHA
    
    ================ FINANCIAL DB (PostgreSQL Primary + Synchronous Standby) ==================
    periods              (period PK, status [OPEN|CLOSING|COMPUTED|APPROVED|PAID|RECONCILED],
                          cutoff_at, manifest_sha256)
    
    contracts            (contract_id PK, artist_id, rate_micros BIGINT, currency,
                          valid_from DATE, valid_to DATE, recorded_at TIMESTAMPTZ)  -- append-only!
    track_splits         (split_id PK, track_id, artist_id, share_bps INT,
                          valid_from DATE, valid_to DATE, recorded_at TIMESTAMPTZ)  -- sum(share_bps)=10000
    
    adjustments          (adjustment_id PK, artist_id, track_id, origin_period, delta_streams BIGINT,
                          delta_micros BIGINT, reason, correction_group_id, created_by, approved_by)
    applied_adjustments  (adjustment_id PK, run_id)  -- guarantees each adjustment is applied once
    
    calc_runs            (run_id PK, period, version INT, status [COMPUTED|SUPERSEDED|APPROVED],
                          manifest_sha256, code_sha, output_sha256, approved_by_1, approved_by_2)
                         UNIQUE (period) WHERE status = 'APPROVED'
    
    calc_lines           (run_id, artist_id, track_id, home_period, contract_id, valid_streams BIGINT,
                          rate_micros BIGINT, share_bps INT, line_micros BIGINT, adjustment_id NULL)
    
    ledger_txns          (txn_id PK, kind, ref_id, created_at)   UNIQUE (kind, ref_id)
    ledger_entries       (entry_id PK, txn_id FK, account, debit_micros BIGINT, credit_micros BIGINT)
    
    payouts              (payout_id PK, run_id, artist_id, period, amount_cents BIGINT)
                         UNIQUE (artist_id, period)
    
    payment_attempts     (attempt_id PK, payout_id FK, attempt_no INT,
                          status [CREATED|SENDING|UNKNOWN|SUBMITTED|PAID|REJECTED|FAILED|RETURNED],
                          provider_payout_id NULL, created_at, updated_at)
                         UNIQUE (payout_id)
                           WHERE status IN ('CREATED', 'SENDING', 'UNKNOWN', 'SUBMITTED', 'PAID')
    
    attempt_events       (event_id PK, attempt_id FK, from_status, to_status, cause, raw_ref, at)
    outbox               (outbox_id PK, attempt_id UNIQUE, next_try_at, tries INT, done_at NULL)
    webhook_events       (provider_event_id PK, payload JSONB, received_at)
    disputes / dispute_events   -- append-only dispute ticket + status/comment log
    

    Four schema rules guarantee auditability: - Integer money everywhere: internal math uses micro-dollars ($1.00 = 1,000,000 micros, $0.01 = 10,000 micros), and provider payouts use integer amount_cents. Floating-point numbers (FLOAT/DOUBLE) never touch money. - Bitemporal ("as-of") contracts and splits: contracts and track_splits are never updated in place. Changing a split inserts new rows with a fresh recorded_at timestamp, so querying WHERE recorded_at <= manifest.as_of_recorded_at reproduces exactly what we knew on September 4 even if someone updates a contract in October. - DB-enforced append-only tables: the application's database user lacks UPDATE and DELETE privileges on calc_lines, ledger_entries, adjustments, attempt_events, and dispute_events. - Two partial unique indexes prevent catastrophic bugs: UNIQUE (period) WHERE status = 'APPROVED' guarantees one approved run per month, and UNIQUE (payout_id) WHERE status IN ('CREATED','SENDING','UNKNOWN','SUBMITTED','PAID') makes it physically impossible in SQL to start a second payment attempt while an earlier one is in-flight, succeeded, or UNKNOWN.

  5. High-level architecture and monthly lifecycle

      Mobile / Web / Smart Speakers
            |  POST /v1/plays:batch (with client event_id)
            v
      +-------------+      +-------------------------+      +-------------------------------+
      |  Play API   |----->|   Kafka (plays.raw)     |----->| Lake Writer                   |
      | (stateless) |      | 48 partitions, 7d ret.  |      | -> raw_plays/ (hourly Parquet)|
      +-------------+      +-------------------------+      +-------------------------------+
                                     |                                      |
                                     v                                      v
                           +-------------------+           +--------------------------------+
                           | Streaming Counter |           | Daily Batch Job (Spark)        |<-- Fraud flags,
                           | (Flink/Redis:     |           | Exact dedup + 20/day cap +     |    territory
                           |  live estimates   |           | license check -> daily_counts/ |    licenses
                           |  ONLY, never pay) |           +--------------------------------+
                           +-------------------+                            |
                                                                            v
      [Period Closer] --(00:00 UTC on 4th: verify Kafka/jobs caught up, write manifests/2026-08.json)-->+
                                                                                                        |
                                      +-----------------------------------------------------------------+
                                      v
                           +-----------------------+      +---------------------------------+
                           |   Payout Calculator   |----->| Finance Review + 2-Person       |
                           | (pure fn of manifest) |      | Maker-Checker Approval          |
                           +-----------------------+      +---------------------------------+
                                                                            |
                                             writes calc_lines, ledger accruals, payouts, attempts + outbox
                                                                            v
      +--------------------------- Financial PostgreSQL (Primary + Sync Standby) -----------------------+
      | calc_runs | ledger_entries | payouts | payment_attempts | outbox | adjustments | disputes       |
      +-------------------------------------------------------------------------------------------------+
             ^                                   | poll leased outbox rows
             |                                   v
      +------------------+             +------------------+   POST /payouts    +------------------------+
      | Webhook Receiver |<------------|  Payment Sender  |------------------->| External Payment       |
      | (HMAC + dedup)   |             | (20 req/s cap)   |<-------------------| Provider               |
      +------------------+             +------------------+   Idempotency-Key  +------------------------+
             ^                                                                             |
             +-------------------------[ Daily 3-Way Reconciler ]<-------------------------+
                                        (DB vs Provider Report vs Bank Statement)
    
  6. Deep dive 1: Deduplicating plays, validity rules, and closing the month

    Exact deduplication & daily-cap enforcement without dropping valid plays

    Mobile clients retry on flaky networks, and Play API pods occasionally publish a batch to Kafka twice on timeout. A real-time streaming counter (with a 24-hour state TTL) powers live artist dashboards labeled "Estimated", while money is computed strictly by the daily batch job: 1. Intra-day deduplication: group today's ingested raw_plays by event_id and keep the earliest ingest_time. 2. Cross-day deduplication & 20-play/day cap: because a client retry resends the identical started_at, any duplicate shares the same calendar event_date (YYYY-MM-DD) as the original. Offline plays up to MAX_OFFLINE = 30 days old can arrive in today's files, so the job joins incoming events against the plays_checked table for the last 30 event_date partitions (30 days * 1B IDs * 16 bytes = ~480 GB of sequential Parquet column scans — a few minutes on a Spark cluster). Using an exact column join rather than a probabilistic Bloom filter (a compact bit-array set that can falsely claim a new item was already seen) guarantees zero legitimate artist streams are dropped to false positives. Simultaneously, plays_checked supplies the user's already-accepted count for (user_id, track_id, event_date), so uploading 15 offline plays two days after listening to 18 online plays on August 15 still enforces the 20-play daily cap (2 valid, 13 marked OVER_DAILY_CAP). 3. Explicit exclusion reasons: every unique event receives one deterministic verdict (VALID, SHORT_PLAY, UNLICENSED_TERRITORY, ACCOUNT_SUSPENDED, FRAUD, OVER_DAILY_CAP, INVALID_TIMESTAMP), aggregated into daily_counts so artists can see why plays were filtered.

    Assigning each stream to a deterministic billing month

    What if a commuter listens to a song offline on August 31 at 23:50 UTC, stays on a flight or camping trip, and their phone uploads the play on September 6 — two days after August closed on September 4? We assign the billing period using both started_at (client play time) and ingest_time (trusted server receipt time):

    from datetime import timedelta
    
    MAX_OFFLINE_AGE = timedelta(days=30)
    MAX_CLOCK_SKEW = timedelta(minutes=5)
    
    
    def year_month(ts) -> str:
        return f"{ts.year:04d}-{ts.month:02d}"
    
    
    def assign_billing_period(started_at, ingest_time, cutoff_for_period, earliest_open_period) -> str | None:
        """Return the 'YYYY-MM' payout period for a play, or None if its timestamp is invalid."""
        # Reject plays claiming to come from the future (beyond 5 min device clock skew)
        if started_at > ingest_time + MAX_CLOCK_SKEW:
            return None
        # Reject plays older than our 30-day offline window
        if ingest_time - started_at > MAX_OFFLINE_AGE:
            return None
    
        home_period = year_month(started_at)
        if ingest_time < cutoff_for_period(home_period):
            # Arrived before 00:00 UTC on the 4th of next month -> billed in its home month
            return home_period
    
        # Arrived after home_period closed -> paid in the earliest still-open period,
        # while keeping home_period on the row so it uses August's contract rate!
        return earliest_open_period(ingest_time)
    

    During September 1–3, both 2026-08 (cutoff Sep 4) and 2026-09 (cutoff Oct 4) are open; earliest_open_period deterministically picks the earliest period whose cutoff is still in the future.

    Sealing the monthly window (manifests/2026-08.json)

    At 2026-09-04T00:00:00Z, the Period Closer moves 2026-08 from OPEN -> CLOSING, but does not compute immediately. It waits until: - Every Kafka partition's Lake Writer watermark has passed ingest_time >= cutoff + 1 hour (absorbing clock skew across API pods), - Every daily Spark job covering ingest hours before the cutoff has committed its immutable snapshot, and - The pre-cutoff fraud sweep has published its verdicts.

    Only then does it write manifests/2026-08.json (containing every input Parquet URI + SHA-256 hash, the explicit list of approved unapplied adjustment_ids, as_of_recorded_at, and code_sha) under WORM object lock (Write-Once-Read-Many storage that blocks modification or deletion). Re-running the calculator on that manifest 3 years from now is guaranteed to read identical bytes.

  7. Deep dive 2: Reproducible calculation runs, integer math, and double-entry ledger

    The Payout Calculator is a pure, stateless batch function of manifests/2026-08.json. To prevent penny-shaving bugs across thousands of tracks, we keep full precision through multiplication and divide once per artist:

    TOTAL_BPS = 10_000          # 10,000 basis points = 100.00% split share
    MICROS_PER_CENT = 10_000    # 10,000 micro-dollars = $0.01 (1 cent); 1,000,000 micros = $1.00
    
    
    def compute_artist_accrual_micros(lines) -> int:
        """Sum (streams * rate_micros * share_bps) across all lines, dividing by TOTAL_BPS once."""
        weighted_sum = 0
        for valid_streams, rate_micros, share_bps in lines:
            weighted_sum += valid_streams * rate_micros * share_bps
        return weighted_sum // TOTAL_BPS
    

    Let's trace a concrete August calculation for Creator M (art_14) with contract rate $0.003333 (3,333 micro-dollars/stream):

    Line  Description                                       Arithmetic (in micro-dollars)
    ----  ------------------------------------------------  -------------------------------------------
    1     Track trk_501: 1,500,001 streams * 3,333 * 100%   (1,500,001 * 3,333 * 10,000) / 10,000
                                                            =  4,999,503,333 micros
    2     Track trk_502: 400,000 streams * 3,333 * 50%      (400,000 * 3,333 * 5,000) / 10,000
                                                            =    666,600,000 micros
    3     July fraud adjustment: -30,000 streams on trk_501 (-30,000 * 3,333 * 10,000) / 10,000
                                                            =    -99,990,000 micros
    ---------------------------------------------------------------------------------------------------
    Net August accrual credited to payable:creator_M        =  5,566,113,333 micros ($5,566.113333)
    Payout created (balance // MICROS_PER_CENT = 556,611 c) =  5,566,110,000 micros ($5,566.11)
    Sub-cent remainder left in payable:creator_M for Sept   =          3,333 micros ($0.003333)
    

    Notice two properties: 1. Even for a superstar with 21B streams at 10,000 micros and 10,000 bps, 21 * 10^9 * 10^4 * 10^4 = 2.1 * 10^18, which fits inside signed 64-bit BIGINT (9.22 * 10^18), and Spark/SQL uses DECIMAL(38,0) for extra safety. 2. Zero sub-cent loss: the leftover 3,333 micro-dollars (1/3 of a cent) stays in Creator M's ledger balance and rolls into September automatically!

    Versioned runs, maker-checker approval, and the double-entry ledger

    • Run versions: Run v1 writes calc_lines with status COMPUTED. Automated sanity gates verify that total streams are within 2% of the live streaming counter, flag any artist with >5x and >$1,000 jump for human inspection, and verify a second independent worker reproduces the exact output_sha256. If a bug is caught before approval, we mark v1 SUPERSEDED and compute v2.
    • Maker-checker approval: two distinct finance approvers sign off (approved_by_1 != approved_by_2). Approval posts balanced entries to our double-entry ledger (an accounting structure where every transaction has equal debit_micros and credit_micros, and account balances are computed by summing entries rather than overwriting a mutable balance column):
    Lifecycle Event                        Debit Account          Credit Account         Amount
    -------------------------------------  ---------------------  ---------------------  ------------------------
    1. Run approved (monthly accrual)      royalty_expense        payable:creator_M      5,566,113,333 micros
    2. Payout >= $10 queued (reserve)      payable:creator_M      in_flight:creator_M    5,566,110,000 micros
    3. Provider settles payout (PAID)      in_flight:creator_M    provider_cash          5,566,110,000 micros
    4. Attempt definitively rejected       in_flight:creator_M    payable:creator_M      5,566,110,000 micros
    5. Bank returns funds days after PAID  provider_cash          payable:creator_M      5,566,110,000 micros
    6. Post-settlement overpayment clawback payable:creator_M     royalty_expense        (adjustment micros)
    

    Writing ~1.5M accruals runs in idempotent batches of 5,000 artists keyed by UNIQUE (kind = 'ACCRUAL', ref_id = '<run_id>:<artist_id>'), so restarting mid-approval never double-credits an artist.

  8. Deep dive 3: Exactly-once external payouts, timeouts, and the state machine

    Why we separate payouts from payment_attempts

    A payout represents what we owe Creator M for August ($5,566.11, one row per (artist_id, period)). A payment_attempt represents one submission to the payment provider with its own attempt_id (att_4b8e21...). Why not use payout_id directly as the provider's Idempotency-Key? Because if Attempt #1 fails permanently (REJECTED: CLOSED_BANK_ACCOUNT), the provider permanently binds that idempotency key to the 422 failure! Once the artist updates their bank details, we must send Attempt #2 with a fresh key (att_9c1a07...) — but ONLY after Attempt #1 is provably dead.

    Our partial unique index enforces that invariant inside PostgreSQL: UNIQUE (payout_id) WHERE status IN ('CREATED', 'SENDING', 'UNKNOWN', 'SUBMITTED', 'PAID') As long as Attempt #1 is in any live or ambiguous state (especially UNKNOWN!), PostgreSQL rejects inserting Attempt #2!

    Commit-before-call transactional outbox & sender loop

    We never call the provider before committing our database intent — otherwise a power loss right after the HTTP response would send money with zero database record. Instead, approval (or retry creation) writes payment_attempts (CREATED) + ledger reserve + outbox in one ACID transaction, and the Payment Sender executes:

    Step 1 (Lease):   BEGIN;
                      SELECT attempt_id FROM outbox
                      WHERE done_at IS NULL AND next_try_at <= now()
                      FOR UPDATE SKIP LOCKED LIMIT 50;
                      UPDATE outbox SET next_try_at = now() + interval '2 minutes' WHERE ...;
                      UPDATE payment_attempts SET status = 'SENDING' WHERE status = 'CREATED' AND ...;
                      COMMIT;   -- Row lock released; 2-minute lease prevents duplicate pickup
    
    Step 2 (Call):    POST /v1/payouts (HTTP timeout = 30s, well inside the 2-minute lease)
                        Idempotency-Key: <attempt_id>
                        Body: { amount_cents, currency, destination_token, reference: <attempt_id> }
    
    Step 3 (Record):  - HTTP 2xx               -> status = SUBMITTED (or PAID), set outbox.done_at = now()
                      - HTTP 4xx definitive    -> status = REJECTED, reverse in_flight -> payable, set done_at
                      - Timeout / 5xx / 409    -> status = UNKNOWN, keep outbox open with backoff + jitter!
    

    Monotonic state machine for unordered/duplicate webhooks

    Webhooks can arrive twice or out of order (SUBMITTED arriving after PAID). A monotonic state machine (where transitions only move forward along a directed acyclic graph) ignores stale duplicates while alerting on impossible contradictions:

    ALLOWED_TRANSITIONS = {
        "CREATED": {"SENDING"},
        "SENDING": {"SUBMITTED", "UNKNOWN", "REJECTED", "PAID", "FAILED"},
        "UNKNOWN": {"SUBMITTED", "REJECTED", "PAID", "FAILED"},
        "SUBMITTED": {"PAID", "FAILED"},
        "PAID": {"RETURNED"},  # e.g., ACH return 3 days after provider marked payout PAID
        "REJECTED": set(),
        "FAILED": set(),
        "RETURNED": set(),
    }
    
    
    def resolve_next_status(current_status: str, reported_status: str) -> str:
        """Advance forward along allowed transitions; ignore duplicate or out-of-order stale events."""
        if reported_status == current_status:
            return current_status
        if reported_status not in ALLOWED_TRANSITIONS[current_status]:
            return current_status
        return reported_status
    

    Every webhook is first deduplicated by webhook_events (provider_event_id PK). If an ignored transition is merely stale (SUBMITTED when already PAID), we log and ack 200. If it contradicts a terminal failure (PAID when our DB says REJECTED), we page finance immediately because unexpected money moved!

  9. Deep dive 4: Provider reconciliation, post-close adjustments, and disputes

    Three-way daily reconciliation (closing the UNKNOWN loop safely)

    Every morning, the Reconciler joins our payment_attempts, the provider's daily settlement report, and our treasury bank statement: - Lost webhook (SUBMITTED/UNKNOWN in DB, PAID in report): advance attempt to PAID, post in_flight -> provider_cash, and close outbox.done_at. - Unresolved UNKNOWN absent from 2 consecutive daily reports: we must be careful of a subtle race — if we immediately checked GET /payouts?reference=att_1 while a sender worker was mid-flight on POST /payouts, the POST could land milliseconds after our GET returned 404! To eliminate that race: 1. Set outbox.done_at = now() so no worker starts a new retry for att_1. 2. Wait until max(outbox.next_try_at, now) has passed (guaranteeing any leased worker's 30-second HTTP call has finished). 3. Call GET /v1/payouts?reference=att_1 one final time. Only if it still returns 404 Not Found do we transition UNKNOWN -> REJECTED (NEVER_RECEIVED), returning funds from in_flight to payable and unlocking a fresh attempt_id. - Provider amount mismatch or unknown reference: trigger a P1 critical alert and freeze payouts for the affected artist until investigated.

    Post-cutoff corrections & artist disputes

    • Never mutate closed periods: late bot-fraud reversals emit negative stream adjustments (delta_streams < 0 referencing origin_period); retroactive split corrections emit paired negative + positive adjustments linked by correction_group_id so they apply atomically in the next open period's manifest. Adjustments exceeding $1,000 require maker-checker dual approval.
    • Auditable artist disputes: when a creator disputes August's count for trk_501, support queries the immutable manifests/2026-08.json and daily_counts to show exact daily valid streams alongside aggregated exclusion counts (SHORT_PLAY, DUPLICATE, OVER_DAILY_CAP, UNLICENSED_TERRITORY) without exposing listener PII. Every comment and decision appends to dispute_events, and an upheld claim creates an approved adjustment linked to dispute_id for the next payout run.
  10. Scaling, failure modes, observability, and trade-off summary

    Bottlenecks & horizontal scaling

    • Play ingestion (35k events/s peak): batched ~50 plays/request = ~700 HTTP RPS across stateless pods into 48 Kafka partitions (~730 events/s/partition). Seven-day Kafka retention (~6.3 TB across 3 replicas) buffers multi-day Lake Writer maintenance with zero data loss.
    • Hot-track skew in Spark: a viral hit with 50M plays/day will skew a naive GROUP BY track_id. Deduplication shuffles by event_id (uniform UUID), the 20-play daily cap shuffles by (user_id, track_id) (uniform), and final track aggregation uses map-side partial combining so each executor emits a single pre-summed count per track.
    • Payout throughput & statement reads: throttled cleanly to 20 req/s via a shared token bucket (~4.2 hours for 300k payouts, or faster via provider batch endpoints while preserving per-item reference IDs). Artist statements are pre-rendered to immutable JSON/PDF documents upon run approval so portal traffic never queries the data lake.

    Failure handling matrix & key metrics

    Failure scenario System behavior & recovery
    Play API / Kafka outage Client SDKs queue events locally on disk and retry with identical event_ids; assign_billing_period places them deterministically.
    Lake writer lags past midnight on the 4th Period Closer waits on Kafka watermark >= cutoff + 1h before sealing manifests/YYYY-MM.json; never closes with partial files.
    Daily Spark job crashes mid-run Writes go to an isolated run_id=<uuid> path and commit atomically via snapshot pointer; reruns replace cleanly without double-counting.
    Provider 5xx / outage during payout day Circuit breaker pauses the sender loop; attempts sit safely in outbox (CREATED or UNKNOWN) with days of schedule slack.
    PostgreSQL primary hardware failure Synchronous standby in a second AZ promotes with RPO = 0; zero committed ledger entries or attempt_id keys are lost.

    Key alerts: daily SUM(debit_micros) == SUM(credit_micros) ledger invariant (page on != 0), any UNKNOWN attempt older than 24h, any contradictory webhook (PAID after REJECTED), any reconciliation discrepancy, and >2% divergence between batch valid counts and streaming estimates.

    Summary of key trade-offs

    • Daily batch over WORM files + manifest vs. real-time streaming payouts: trades live penny-accurate balances for exact 30-day deduplication and byte-for-byte reproducible audits.
    • Fixed 4th-of-month cutoff + forward adjustments vs. reopening closed months: late corrections wait one cycle, but closed statements and tax/accounting books never mutate retroactively.
    • Per-stream contract rates vs. pro-rata revenue pool: keeps post-close adjustments isolated to a single artist/track rather than forcing a platform-wide recalculation of every artist's pool share.
    • payouts + payment_attempts with partial unique index + commit-before-call outbox: adds one extra table and state machine, making double payouts impossible unless both our database constraint and the provider's idempotency store fail simultaneously.

Intuition & how it works

Think of this system like an electric utility reading smart meters all month and mailing numbered checks on the 10th. Smart meters chatter constantly over flaky wireless links (1 billion play events a day), so you never wire cash straight from a live dashboard counter. Instead, four days after the month ends, you take a sealed photograph of all verified meter files (an immutable manifest — a locked JSON file listing the exact input files and SHA-256 hashes used for that month), compute each artist's royalty using exact integer math into a double-entry ledger (an accounting log where every dollar added to one account is subtracted from another so money can never appear or vanish silently), and send each payout with a sticky idempotency key (a unique attempt ID stored before calling the provider so retrying a timed-out request returns the original payment receipt instead of paying twice).

A naive design that increments a live artist_streams counter in Redis, multiplies by floating-point dollar rates like 0.003333, and calls POST /payouts inside a cron loop breaks down immediately at scale. Mobile apps retrying offline uploads inflate stream counts, IEEE-754 floating-point math silently drops fractions of cents across billions of plays, and editing August's rows when bot fraud is discovered in September makes historical creator statements disagree with actual bank wires. Worse, if the payment gateway times out after accepting a request and your loop retries with a newly generated idempotency key, you wire the creator double their money.

Here is a concrete walkthrough of Creator M's August payout ($0.003333 = 3,333 micro-dollars per stream): 1. Play ingestion & exact deduplication: On Aug 31 at 23:58 UTC, a listener plays Track trk_501 offline for 194 seconds (event_id = e_74); flaky Wi-Fi uploads e_74 twice on Sep 2. Because Sep 2 is before August's Sep 4 00:00 UTC cutoff, the daily batch job deduplicates e_74 by event_id, checks the 20-plays/day user cap, and records 1 valid August stream. 2. Manifest seal & exact integer math: On Sep 4, the closer seals manifests/2026-08.json. Creator M has 1,500,001 solo streams (10,000 basis points = 100%) on trk_501, 400,000 50%-split streams (5,000 bps) on trk_502, and a -30,000-stream July fraud clawback -> exact accrual 5,566,113,333 micro-dollars ($5,566.11 reserved for payout + 3,333 micro-dollars kept in payable:creator_M for September). 3. Commit-before-call & provider timeout: In one Postgres transaction, we insert attempt_id = att_4b8e (CREATED), move $5,566.11 from payable:creator_M to in_flight:creator_M, and enqueue an outbox row. The sender transitions att_4b8e to SENDING and calls POST /payouts with Idempotency-Key: att_4b8e and reference: att_4b8e, which times out after 30 seconds -> status becomes UNKNOWN. 4. Safe retry & settlement: While att_4b8e is UNKNOWN, our database partial unique index (a uniqueness rule covering all non-failed states) blocks creating any second attempt. The sender retries with the same Idempotency-Key: att_4b8e, the provider recognizes it and returns the existing payout (SUBMITTED), and the signed webhook advances SUBMITTED -> PAID, settling in_flight:creator_M -> provider_cash.

Key trade-offs

  • Daily batch over WORM files + manifest vs. real-time streaming counts for payouts. A streaming Flink/Redis pipeline gives sub-second dashboards, but state TTLs, late arrivals, and job restarts make it nearly impossible to prove byte-identical reruns for financial audits. Computing payouts from daily Parquet snapshots under WORM object lock (Write-Once-Read-Many storage that prevents file edits) sealed by a manifest gives exact 30-day deduplication and deterministic replays, at the cost of labeling live creator dashboards as estimates until the 4th.
  • Fixed 4th-of-month cutoff + forward adjustments vs. reopening past months. Reopening August whenever fraud or split updates arrive in September mutates numbers already wired to banks and breaks tax and accounting ledgers. Waiting 72 hours (Sep 4 00:00 UTC) captures >99% of offline plays while routing anything later — plus all post-close fraud/rights fixes — into auditable adjustment lines in the next open month.
  • Combined (started_at, ingest_time) period assignment vs. pure event time or pure ingest time. Pure event time forces closed months to change when offline plays arrive weeks later; pure ingest time unfairly pushes an Aug 31 evening play uploaded on Sep 1 into September. Assigning plays to month(started_at) if ingested before that month's cutoff — and otherwise to the earliest open month while preserving the original month's contract rate — is fair, deterministic, and tamper-resistant because ingest_time comes from our servers.
  • Per-stream artist contracts vs. a shared pro-rata revenue pool. Under per-stream rates, a late fraud reversal or split fix affects only that track's payees. Under a pro-rata subscription pool (where artists split X% of total monthly subscription revenue by stream share), a single stream adjustment technically alters every artist's denominator; platforms using pro-rata pools therefore hold a small reserve buffer or batch minor adjustments into a periodic true-up.
  • Separating payouts (obligation) from payment_attempts (provider tries) with a partial unique index. Keeping one row with a retry counter cannot safely distinguish "retry the same timed-out request with the same key" from "the bank rejected a closed account, so send a fresh key after the artist updates their bank". Splitting payouts and payment_attempts — guarded by UNIQUE (payout_id) WHERE status IN ('CREATED','SENDING','UNKNOWN','SUBMITTED','PAID') — supports legitimate re-attempts while making concurrent double-sends impossible in SQL.
  • Transactional outbox (commit-before-call) vs. synchronous provider calls. Committing attempt_id and outbox before making the HTTP request ensures a crash can only leave an unsent row that cleanly retries, never an unrecorded wire transfer. The few seconds of outbox polling latency are irrelevant for monthly payouts.
  • Single ACID PostgreSQL cluster + double-entry ledger vs. distributed NoSQL or mutable balance columns. Three hundred thousand payouts and ~4.2M ledger rows per month fit easily on one Postgres primary with a synchronous standby (RPO = 0), giving us ACID transactions and unique constraints while tracking carry-overs, sub-cent remainders, ACH returns, and clawbacks without ever overwriting history.

Common mistakes

  • Wiring real money from a live streaming counter, whose approximate deduplication windows and replay semantics drift from audit snapshots.
  • Deduplicating by (user_id, track_id, timestamp) instead of a client-generated event_id, which either double-counts retries when the client regenerates upload timestamps or falsely drops legitimate repeat listens when timestamps are coarse.
  • Using floating-point numbers (float/double) or rounding each track line to cents, losing up to $0.0099 per track across millions of (artist, track) pairs instead of summing exact micro-dollars and dividing once per artist.
  • Editing closed calculation runs or ledger entries in place when post-settlement fraud or split disputes arise, destroying the audit trail between statements and bank transfers.
  • Generating a brand-new Idempotency-Key inside the HTTP retry wrapper, or treating a 30-second read timeout / HTTP 502 as FAILED and launching a second payment attempt while the first may have succeeded.
  • Marking a stale UNKNOWN attempt as REJECTED without stopping and draining the sender's lease first, allowing an already in-flight retry of Attempt #1 to succeed at the provider moments after Attempt #2 is created.
  • Calling POST /payouts before committing the attempt row to the database, so a process crash mid-request sends cash with zero local record of the attempt_id.
  • Blindly applying provider webhooks without deduplication or a monotonic state machine, allowing an out-of-order SUBMITTED webhook to roll a PAID attempt backward or double-book ledger settlements.

Follow-up questions

  • If a post-settlement audit reveals that a creator was overpaid in a closed month, how do you recover those funds cleanly? Never edit or delete the settled calculation run, ledger journal, or payout row. Instead, create an approved negative adjustment row referencing origin_period and the evidence ticket; in the next run, this posts a balanced ledger entry (DEBIT payable:creator_M, CREDIT royalty_expense), turning the creator's payable balance negative (or offsetting future royalties automatically since payouts only fire when payable >= $10.00). If clawing back 100% at once would wipe out a smaller creator's income for months, book the debt to receivable:creator_M and cap monthly recoupment at, say, 50% of each new month's accrual (DEBIT payable:creator_M, CREDIT receivable:creator_M), or request a bank reversal through the gateway if the overpayment stemmed from an actual duplicate transfer.
  • How does your payout state machine respond when an HTTP submission to the payment gateway times out after the gateway already accepted it? The sender immediately records the attempt as UNKNOWN, which keeps the database's partial unique index locked so no second attempt_id can be created for that payout. Background retries re-submit POST /payouts using the exact same Idempotency-Key (attempt_id) with exponential backoff and jitter; the gateway recognizes the key and harmlessly returns the already-created payout (SUBMITTED or PAID), or an asynchronous webhook / next-day settlement report resolves it first. If the attempt remains UNKNOWN past 24–48 hours, the reconciler first closes outbox.done_at, waits for any active 2-minute sender lease to expire so no POST can be in flight, queries GET /payouts?reference=<attempt_id> (which never expires even after the 7-day idempotency window), and marks REJECTED only if confirmed never received.
  • How can a creator challenge a monthly stream total while keeping historical financial records strictly immutable? Filing a dispute creates a disputes ticket plus append-only dispute_events rows recording every claim, reviewer note, and timestamp. Because August's inputs were frozen in manifests/2026-08.json under WORM object lock, support can re-query the exact daily_counts files used in that run and show the creator day-by-day valid streams alongside aggregated exclusion totals (SHORT_PLAY, DUPLICATE, OVER_DAILY_CAP, UNLICENSED_TERRITORY, FRAUD) without exposing individual listener data. If the dispute is upheld, two approvers sign off on a positive adjustment linked to dispute_id that pays out as a clearly labeled line item on next month's statement, leaving August's historical run and ledger untouched.

Follow-up questions

Similar questions

More Commure interview questions

All 3 Commure questions →