Build a Royalty Settlement System for Music Streaming
System DesignModel answerLast updated
Design infrastructure to compute artist earnings from streaming activity, close monthly accounting windows, and execute payments with idempotency guarantees.
You're building a backend for a music streaming platform. Every month, artists earn money based on how many times their tracks were played. Your job is to design the system that ingests play events, determines which ones qualify for payment, groups them by artist, computes what each artist is owed, and sends that money through a third-party payment API.
The payment API requires an idempotency key with every request—if you retry with the same key, it won't send duplicate funds. Your system must be auditable: finance and legal teams need to trace every dollar from raw plays to completed transfers.
What You Need to Address
-
Event ingestion and validity: How do you receive play events? What makes a play "valid" for payment? How do you handle duplicates or fraud flags that arrive days later?
-
Monthly boundary handling: When does a month officially close? Can corrections or late events affect a closed month, and if so, how?
-
Payout calculation and storage: How do you store the amount owed to each artist? What data model ensures you can recalculate or audit any month's numbers?
-
Idempotency and retry safety: How do you generate idempotency keys? What happens if your payment request times out—how do you know whether the money was sent?
-
Reconciliation: The payment provider sends webhooks and offers a reconciliation API. How do you confirm that what you think you paid matches what actually left your account?
-
Late adjustments: A rights dispute is resolved two months after the original period. How do you handle the correction without reopening closed books?
Start by stating your assumptions (validity rules, payout rates, provider SLAs), then walk through the architecture and data models that satisfy these requirements.
Hints
Hint 1
Think about separating the 'obligation to pay' from the 'act of paying'—these are two different concerns with different consistency needs.
Hint 2
Use versioned aggregates or snapshots so you can recompute without mutating history.
Hint 3
Design your idempotency keys to be deterministic and include everything that makes a payment unique: who, when, and which version of the data.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
Assumptions
- Validity: A play counts if it lasted at least 30 seconds, came from an authenticated user, and wasn't flagged for bot activity. Fraud signals may arrive up to 72 hours after the play.
- Payout formula: Fixed rate of $0.004 per valid play (we can extend this to contract-specific rates later).
- Period closure: The month closes 5 days after it ends, giving time for late fraud signals and event pipeline delays.
- Payment provider: Supports idempotency keys, returns success/failure synchronously, sends a webhook on settlement, and offers a daily reconciliation file. Requests may time out without a definitive answer.
Architecture Overview
The system has four main stages:
- Event ingestion → raw plays land in an append-only log
- Validity resolution → decide which plays count, handle late corrections
- Obligation recording → compute and freeze each artist's earnings for the month
- Payment execution → send funds and track settlement state
Each stage is independently auditable and reproducible.
1. Event Ingestion and Deduplication
Data model:
StreamEvent {
event_id: UUID (deterministic from user_id + track_id + timestamp)
user_id, track_id, artist_id
timestamp
duration_sec
received_at
}
Write every event to an immutable log (Kafka, Kinesis, or a database with append-only semantics). Use event_id to deduplicate: if the same play arrives twice, reject the duplicate at write time or in a downstream dedup stage.
Validity tagging: A separate service consumes these events and writes validity decisions:
ValidityDecision {
event_id
decision_time
is_valid: bool
reason: "duration_ok" | "bot_detected" | "auth_failed"
version: int
}
If fraud detection flags an event three days later, write a new ValidityDecision with an incremented version. The original event never changes; only the interpretation does.
2. Monthly Window Closure
On day 5 of the new month, a batch job runs:
- Query all
StreamEventrecords wheretimestampfalls in the previous month. - Join with the latest
ValidityDecisionfor each event (highest version). - Aggregate by
artist_id:SELECT artist_id, COUNT(*) as valid_plays FROM StreamEvent e JOIN ValidityDecision v ON e.event_id = v.event_id WHERE e.timestamp >= '2025-01-01' AND e.timestamp < '2025-02-01' AND v.is_valid = true AND v.version = (SELECT MAX(version) FROM ValidityDecision WHERE event_id = e.event_id) GROUP BY artist_id - Write the result to an obligation snapshot:
PayoutObligation { period: "2025-01" artist_id valid_play_count amount_cents: valid_play_count * 0.4 // $0.004 = 0.4¢ snapshot_version: 1 created_at }
This snapshot is immutable. If a correction comes later, we create version 2 with adjusted counts and a delta amount.
3. Payment Execution with Idempotency
For each PayoutObligation, create a payment record:
Payment {
payment_id: UUID
artist_id
period: "2025-01"
snapshot_version: 1
amount_cents
idempotency_key: sha256("artist_123|2025-01|v1")
state: pending | submitted | confirmed | failed
provider_transaction_id
submitted_at, confirmed_at
}
State machine:
pending: not yet sentsubmitted: API call made, waiting for responseconfirmed: provider confirmed receipt (via sync response or webhook)failed: provider rejected or we exhausted retries
Idempotency key construction: Derive it from artist_id + period + snapshot_version. If version 2 is needed (a correction), it gets a different key and a separate payment.
Handling timeouts: If the API call times out, the state stays submitted. A background reconciler polls the provider's transaction lookup API using idempotency_key to discover the actual outcome. Once known, transition to confirmed or retry with a new submission if it never reached the provider.
4. Reconciliation
Webhook processing: When the provider sends a settlement webhook, match it to a Payment by idempotency_key or provider_transaction_id. If state is submitted, move it to confirmed. If no matching record exists, alert for investigation (potential duplicate or data loss).
Daily reconciliation file: Download the provider's file of all settled transactions. Join against internal Payment records. Flag:
- Payments we think are confirmed but don't appear in the file.
- Transactions in the file we have no record of.
- Amount mismatches.
Store discrepancies in an AuditAlert table for manual review.
5. Late Adjustments
Suppose in March, we discover 100 of Artist X's January plays were fraudulent. We:
- Write new
ValidityDecisionrecords (version 2) marking those events invalid. - Recompute the January aggregate → new
PayoutObligationfor "2025-01" withsnapshot_version: 2and a negativeamount_centsdelta. - Create a
Paymentwith the delta amount (e.g., -$0.40) and a new idempotency key ("artist_X|2025-01|v2"). - Execute that payment (which might be a debit or a corrected net-up in the next cycle, depending on provider capabilities).
The original January snapshot stays in the database. Audit logs show both versions and the correction history.
Key Design Principles
- Immutability: Stream events and validity decisions are append-only. Aggregates are versioned snapshots, never updated in place.
- Deterministic idempotency keys: Derived from semantic identity (artist + period + version), not random UUIDs. Retries use the same key.
- Separation of obligation and execution: We decide what we owe (the snapshot) before we attempt payment. The payment layer handles retries and failures independently.
- State machine for payments: Explicit states and transitions let you reason about retry safety and timeout ambiguity.
- Reconciliation as a first-class concern: Treat the provider as eventually consistent. Regularly verify internal beliefs against external truth.
Common Mistakes
- Updating aggregates in place: Loses auditability. Always version.
- Random idempotency keys: Can't safely retry—use deterministic keys.
- Assuming synchronous success: Timeouts happen. Build a reconciliation loop.
- Reopening closed periods: Instead of mutating history, record deltas in new versions.
- Ignoring minor-unit precision: Use integer cents (or smaller) to avoid floating-point rounding errors in financial calculations.
Complexity Notes
- Data volume: If you have 10M plays/day, that's ~300M/month. Partition events by day or use a time-series database. Aggregation can run incrementally (daily sub-aggregates that roll up at month-end).
- Latency: Most of this is batch-oriented. For real-time artist dashboards, maintain a separate "provisional" aggregate that updates continuously, but use the frozen snapshot for actual payments.
- Scale of payments: If you're paying 100k artists/month, batch the API calls but track each individually. Use a work queue (SQS, Redis) to parallelize submission and retry.
This design ensures every dollar is traceable, every payment is retry-safe, and corrections are handled without rewriting history.