Engineering · Distributed Systems · Financial Infrastructure

Building a Lending Platform Across Four Markets: Correctness at Scale

How we designed Samsung's lending platform's infrastructure to guarantee financial correctness under distributed failure — and why the hardest problems were not throughput, but consistency, auditability, and the operational reality of third-party payment rails.

4
Active markets
TH · ID · PH · IN
0
Core changes
per new geography
T+0
Settlement
from T+2 manual
1×
Every payment event
processed, guaranteed

Background

When Samsung's lending platform began expanding its device financing product across Southeast Asia and India, the engineering team hit a problem that compounds silently until it becomes unmanageable: every new market was a separate engineering project. Thailand had different regulatory requirements around loan tenures and repayment schedules. Indonesia required different currency handling and local payment rail integrations. The Philippines had its own collection workflows and delinquency thresholds. India brought an entirely different compliance surface.

The natural instinct — branch the codebase, override per market — is a trap. By the time a third market is live, the fourth requires an audit of every service before a single transaction can be processed. The bugs that surface in market three are invisible until they hit market four with different timing, different rail behaviour, and a different regulatory consequence.

The architectural question was not "how do we support four markets." It was "how do we design a system where a financial correctness failure in one market cannot propagate to another, and where the fifth market costs us nothing to add." Those two constraints — isolation and extensibility — shaped every decision.

This post describes the full architecture: a config-driven market abstraction that makes new geography rollout a data operation; a distributed saga-based payment pipeline with event sourcing for complete audit replay; a CRDT-influenced state machine that holds correctness under concurrent writes across markets; and the non-obvious production failures that only emerge when third-party payment rails behave adversarially.

System Requirements

  • R1 · Market isolation and extensibility Market-specific behaviour — repayment schedules, currency, collection thresholds, rail integrations — must be expressible as configuration. A bug in Thailand's EMI calculation must not touch Indonesia's loan state. A new market must require zero changes to core service logic.
  • R2 · Financial correctness under partial failure A repayment event processed twice must produce exactly one ledger entry. A loan state transition interrupted mid-execution must be resumable without double-booking. This is a correctness requirement, not a data quality requirement — the consequence of failure is a financial statement error or a regulatory finding.
  • R3 · Full audit replay Every loan's current state must be deterministically reconstructible from its event history. Regulators in all four markets require reconstructible audit trails — not log approximations, but the ability to replay every state transition from origination to closure.
  • R4 · Third-party rail resilience Payment rail providers across four markets have materially different availability and delivery SLAs. The platform must remain financially consistent during provider outages, delayed settlement signals, and duplicate event delivery — without manual intervention.
  • Architecture Overview

    MARKET LAYER
    Config Store v2
    →
    Schema Registry
    Versioned Contracts
    Canary Rollout
    Config Audit Log
    PAYMENT RAIL
    TH · PromptPay
    ID · GoPay / OVO
    PH · GCash
    IN · UPI / NACH
    →
    Transactional Outbox
    EVENT BUS
    Event Bus
    →
    Payment events
    State change events
    Audit events
    DLQ (structured)
    SAGA LAYER
    Saga Orchestrator
    →
    Reconciliation step
    Ledger write step
    State transition step
    Compensating txns
    EVENT STORE
    Append-only Event Log
    →
    Loan projections (read)
    Audit replay engine
    WORM retention
    COLLECTION
    Delinquency Pipeline
    →
    Risk scoring
    Settlement window gate
    Market-policy router

    Figure 1 — Full platform topology. The transactional outbox decouples rail integration from event publication. The saga orchestrator manages distributed state across services with compensating transactions. The event store provides full audit replay.

    Key Design Decisions

    Config-driven market abstraction: versioned contracts, not runtime flags

    The v1 instinct for multi-market configuration is a feature flag system: check the market ID at runtime, branch on it. This works for two markets. By four markets, the branching is pervasive. By eight, it is the dominant maintenance burden. The failure mode is not complexity — it is silent misconfiguration. A flag set incorrectly in Indonesia produces a bug that surfaces as a collection error in a market the debugging engineer does not have context for.

    The design we landed on makes market behaviour entirely external to the services that consume it, with two additions over a naive config store: a schema registry with versioned contracts, and canary rollout for config changes.

    Schema versioning is the lesson we learned painfully. The config store schema evolved across the first two market rollouts. Services deployed against v1 of the schema consumed fields that v2 renamed or restructured. The compatibility shim we added retroactively was functional but fragile. The fix is to treat config schema changes exactly like API changes: they are versioned, backward-compatible by default, and breaking changes require an explicit migration with a deprecation window.

    // Config schema versioning — services declare the version they support
    data class MarketConfig(
        val schemaVersion : Int,           // consumers pin to a version
        val marketId       : String,
        val currencyCode   : String,
        val roundingRule   : RoundingRule,
        val dayCountConvention : DayCount,
        val defaultTenureMonths : Int,
        val settlementWindowMs  : Long,    // per-rail SLA tolerance
        val delinquencyPolicy   : DelinquencyPolicy,
        val railAdapterId       : String,
        val stateTableExtensions: List<StateExtension>  // RESTRUCTURED, HOLD, etc.
    )
    
    // Canary rollout — new config version serves N% of loans before full promotion
    fun resolveConfig(marketId: String, loanId: String): MarketConfig {
        val canary = configStore.getCanary(marketId)
        if (canary != null && stableHash(loanId) % 100 < canary.rolloutPct) {
            return canary.config   // deterministic per loan, not per request
        }
        return configStore.getStable(marketId)
    }

    The canary rollout detail is load-bearing. Config changes in a financial platform are not code changes, but they carry the same risk — a misconfigured delinquency threshold or rounding rule affects every loan in a market. Rolling out a config change to 5% of loans, observing ledger reconciliation and state transition metrics for 24 hours, then promoting to 100% is the same discipline as a code canary. The hash on `loanId` rather than on a random seed ensures the same loan always sees the same config version during rollout — preventing a loan from being processed under v1 and then v2 for the same repayment event.

    Transactional outbox: decoupling rail integration from event publication

    The naive payment integration architecture: the rail adapter receives a settlement event, writes to the loan database, then publishes to the event bus. This is a dual-write. If the database write succeeds and the event bus publish fails, the loan state is updated but no downstream service — reconciliation, delinquency scoring, audit log — knows it happened. The system is silently inconsistent.

    The standard solution is the transactional outbox pattern. The rail adapter writes the payment event to an outbox table in the same database transaction as the loan update. A separate relay process reads unprocessed outbox rows and publishes them to the event bus, marking them processed on acknowledgement. The loan state update and the event publication are now atomic — either both happen, or neither does.

    // Transactional outbox — atomic loan update + event publication
    fun handleSettlementEvent(event: SettlementEvent) = db.transaction {
        // Both writes in the same transaction — no dual-write risk
        loanRepo.markPaymentReceived(event.loanId, event.amount, event.settledAt)
    
        outboxRepo.insert(
            OutboxEntry(
                aggregateId  = event.loanId,
                eventType    = "PAYMENT_SETTLED",
                payload      = event.toJson(),
                idempotencyKey = event.providerRef,   // dedup across relay retries
                createdAt    = Instant.now()
            )
        )
        // Transaction commits. Relay picks up outbox row and publishes to event bus.
        // If relay fails, it retries from the outbox — loan state is already correct.
    }
    
    // Relay: at-least-once publish with idempotency key on the consumer side
    fun relayLoop() {
        outboxRepo.findUnprocessed(batchSize = 100).forEach { entry ->
            val published = eventBus.publishIdempotent(
                topic          = "loan-events.${entry.marketId}",
                key            = entry.aggregateId,    // partition by loan
                payload        = entry.payload,
                idempotencyKey = entry.idempotencyKey
            )
            if (published) outboxRepo.markProcessed(entry.id)
        }
    }

    The outbox pattern shifts the failure surface from "atomic dual-write" — which cannot be made safe — to "at-least-once relay with idempotent consumer" — which can. Downstream consumers handle duplicate events via the idempotency key. The event bus sees each settlement event at least once, and consumers discard duplicates. The loan database is always the source of truth; the event bus is its durable projection.

    Distributed saga: financial correctness across service boundaries

    Processing a repayment spans multiple services: reconciliation verifies the amount, the ledger service records the entry, the loan service transitions the state, and the delinquency service rescores. In a monolith, these are sequential steps in a single database transaction. In a distributed system, they are separate network calls that can fail at any point.

    A local database transaction cannot span service boundaries. The distributed alternative is a saga — a sequence of local transactions, each of which publishes an event that triggers the next step. If a step fails, compensating transactions undo the preceding steps.

    // Saga definition — each step owns its local transaction + compensation
    val repaymentSaga = saga {
        step(
            execute     = { reconciliationSvc.applyRepayment(it) },
            compensate  = { reconciliationSvc.reverseRepayment(it) }
        )
        step(
            execute     = { ledgerSvc.recordEntry(it) },
            compensate  = { ledgerSvc.reverseEntry(it) }    // accounting contra-entry
        )
        step(
            execute     = { loanSvc.transitionState(it) },
            compensate  = { loanSvc.revertTransition(it) }
        )
        step(
            execute     = { delinquencySvc.rescore(it) },
            compensate  = { /* rescore is idempotent — no compensation needed */ }
        )
    }
    
    // Saga orchestrator persists progress — resumable after crash
    fun executeSaga(sagaId: String, event: PaymentEvent) {
        val state = sagaStore.getOrCreate(sagaId)
        repaymentSaga.resume(state, event)   // picks up from last completed step
    }

    The saga store is the correctness guarantee. Every step completion and every compensation is written to the saga store before the next step executes. If the orchestrator crashes mid-saga, it resumes from the last persisted checkpoint. A repayment event that crashes between ledger write and loan state transition will, on recovery, either complete the transition or reverse the ledger entry — never leave both services in divergent states.

    The compensation for a ledger write is not a delete — it is an accounting contra-entry. Deleting a ledger row violates audit requirements in every market we operate in. The compensating transaction produces a new row that exactly offsets the original, preserving the complete financial history. This distinction — between technical rollback and accounting reversal — is one that most distributed systems literature ignores because it is domain-specific.

    Event sourcing: loan state as a deterministic function of its history

    In a conventional architecture, the loan record is mutable state. The current balance, current status, and current payment schedule are columns in a table that gets updated in place. This is operationally simple and produces a correctness problem: given the current state, you cannot reconstruct how you got there. When a regulator asks "show me every state transition for this loan from origination to closure", the answer requires log reconstruction — a forensic exercise that is imprecise by construction.

    We model the loan as an event-sourced aggregate. The append-only event log is the source of truth. The current loan state — the projection — is derived by replaying the event stream from the beginning. Read paths query the projection; write paths append an event and update the projection.

    // Event-sourced loan aggregate — state is a pure function of events
    data class Loan(
        val loanId       : String,
        val state        : LoanState,
        val outstandingBalance : Money,
        val version      : Long           // monotonic event sequence number
    )
    
    fun apply(loan: Loan, event: LoanEvent): Loan = when (event) {
        is PaymentSettled  -> loan.copy(
            outstandingBalance = loan.outstandingBalance - event.amount,
            state              = if (loan.outstandingBalance == event.amount) LoanState.CLOSED
                                 else loan.state,
            version            = event.sequenceNumber
        )
        is OverdueThresholdCrossed -> loan.copy(
            state   = LoanState.DELINQUENT,
            version = event.sequenceNumber
        )
        // All transitions are pure functions — no side effects, fully testable
    }
    
    // Audit replay — reconstruct any point-in-time state for regulator queries
    fun replayAt(loanId: String, asOf: Instant): Loan =
        eventStore
            .streamEvents(loanId)
            .takeWhile { it.occurredAt <= asOf }
            .fold(Loan.empty(loanId), ::apply)

    The audit replay function is load-bearing infrastructure, not an analytics convenience. When a regulator queries a disputed loan in Indonesia and asks for its state at a specific timestamp, `replayAt` produces a deterministic answer from the immutable event log — not a reconstruction from a mutable table's change history. The event log is stored with WORM retention; once written, events cannot be modified or deleted. The projection can be rebuilt at any time from scratch.

    The version field on the loan aggregate is the optimistic concurrency control mechanism. A state transition event carries the version it was generated from. If two events are generated concurrently from the same version, only one can be appended — the second fails with a version conflict and must be retried. This makes concurrent write races structurally detectable rather than silently corrupting state.

    Saga + event sourcing: the interaction that matters

    Running saga orchestration on top of an event-sourced aggregate produces a correctness guarantee that neither provides alone. The saga ensures that multi-service operations are atomic or fully compensated. Event sourcing ensures that every state the aggregate passes through is permanently recorded and replayable. Together, they mean that a repayment processed under a degraded rail provider — delayed acknowledgement, retry storm, partial completion — leaves a complete, auditable, reversible trail regardless of what failed and when.

    The failure mode that exposed this most sharply in production: a GCash settlement event arrived, the saga began, the ledger write succeeded, and the loan state transition service timed out. The saga compensated — reversed the ledger entry. Twenty seconds later, GCash retried the settlement event. The outbox relay published it again. The saga re-executed from scratch. This time all steps completed. The event log shows: PAYMENT_SETTLED attempt 1, COMPENSATION_APPLIED, PAYMENT_SETTLED attempt 2, SUCCESS. The loan state is correct. The audit trail is complete. No manual intervention was required.

    The Latency Budget Model

    A lending lifecycle system is not a real-time scoring pipeline — the latency SLA is measured in seconds for reconciliation, not milliseconds. But the principle of owned per-stage latency budgets applies equally. Without explicit budgets, latency regressions are invisible until they cascade. A slow ledger write delays saga completion, which delays delinquency scoring, which delays automated collection workflows during peak repayment periods — a compounding effect that shows up as unexplained collection lag, not as a latency alert.

    Per-stage latency budgets — P99 targets, enforced with circuit breakers
    Rail adapter → outbox write
    50ms
    Outbox relay → event bus
    200ms
    Reconciliation step
    300ms
    Ledger write step
    300ms
    Loan state transition
    250ms
    Delinquency rescore
    250ms
    Audit event write
    async
    Total P99 (settlement → consistent state)
    < 2s

    The audit event write is deliberately async. Every other step in the saga is on the critical path — a customer who made a repayment should see their loan reflect it within two seconds. The audit log is not. Writing to the WORM event store synchronously on every saga step adds latency on the critical path without improving correctness: the event store's write-ahead log already guarantees durability. The audit write is fire-and-forget with its own retry queue, never blocking saga completion.

    A Non-Obvious Production Problem: The Delayed Settlement Cascade

    The failure mode that cost the most debugging time was not a component failure — it was an emergent interaction between three independently correct subsystems.

    The sequence: a customer repays via GCash. GCash sends an acknowledgement immediately — payment accepted, pending settlement. Normally, settlement completes in seconds. Under GCash's peak load on a Friday evening, settlement is delayed by 47 minutes. During those 47 minutes, the delinquency scoring pipeline runs its scheduled sweep. The loan's overdue age crosses the threshold. The pipeline triggers an automated collection workflow — an SMS to a customer who has already paid.

    Each subsystem was individually correct. The outbox relay was working. The delinquency pipeline was reading accurate loan state. The collection workflow was following its configured policy. The problem was a missing synchronisation point: the delinquency pipeline had no visibility into the settlement window state maintained by the reconciliation service.

    The fix introduces a settlement window gate as an explicit stage between the delinquency scorer and the collection trigger. The gate reads the pending payment flag from the reconciliation service, checks it against the market-configured settlement window tolerance, and suppresses collection triggers for loans within tolerance. Loans that exceed the tolerance — where a settlement signal is genuinely overdue — are routed to manual review rather than automated collection.

    // Settlement window gate — explicit synchronisation between subsystems
    fun evaluateCollectionTrigger(loan: Loan): CollectionDecision {
        val config = configStore.resolve(loan.marketId)
    
        // Check reconciliation service for pending settlement state
        val pendingPayment = reconciliationSvc.getPendingPayment(loan.loanId)
    
        if (pendingPayment != null) {
            val age = Duration.between(pendingPayment.acceptedAt, Instant.now())
    
            return when {
                age < config.settlementWindowMs ->
                    // Within SLA window — provider is expected to settle. Do nothing.
                    CollectionDecision.SUPPRESS
    
                age < config.settlementWindowMs * 3 ->
                    // Past SLA but within escalation window — human review, not auto-collect
                    CollectionDecision.ESCALATE_TO_REVIEW
    
                else ->
                    // Provider has materially failed to settle — treat as non-payment
                    CollectionDecision.INITIATE_COLLECTION
            }
        }
    
        return delinquencySvc.score(loan, config.delinquencyPolicy)
            .toCollectionDecision()
    }

    The settlement window tolerance is per-market configuration — GCash in the Philippines has a materially different SLA profile than UPI in India. UPI settlements clear in under 30 seconds under normal conditions; GCash has a documented P99 of several minutes during peak load. Treating these identically would either produce excessive false-positive collection triggers for the Philippines or insufficient coverage for India. The config resolution at this stage is the same pattern used everywhere in the platform — the gate has no hardcoded market awareness.

    The broader lesson: in a distributed system with multiple independently-scheduled pipelines, the interactions between pipelines are a class of failure that does not appear in unit tests, integration tests, or load tests. They require explicit system-level design — identifying every point where two pipelines share state and inserting a synchronisation contract. The settlement window gate is that contract between the reconciliation pipeline and the collection pipeline.

    Chaos Engineering as a Design Requirement

    The delayed settlement cascade was discovered in production. It should have been discovered in staging. The reason it was not: the staging environment did not simulate adversarial provider behaviour. The GCash integration was tested against a mock that returned settlement immediately. Real-world rail behaviour — delayed acknowledgement, duplicate delivery, out-of-order events, provider timeouts — was not part of the test surface.

    After this incident, we made chaos engineering a design requirement rather than an operational exercise. Every rail integration ships with a corresponding fault injection profile — a set of failure scenarios that the staging environment exercises on a scheduled basis before any production deployment.

    Fault scenarioWhat it testsTarget subsystem
    Settlement delayed N minutes Settlement window gate suppresses collection triggers correctly Delinquency pipeline
    Duplicate settlement event Idempotency key prevents double ledger entry Outbox relay + reconciliation
    Out-of-order events (settlement before acknowledgement) Event sequence validation; saga handles unexpected order Saga orchestrator
    Ledger service timeout mid-saga Compensation reverses reconciliation; retry completes cleanly Saga compensating transactions
    Config store unavailable Services fall back to last-known-good config; alert fires Config resolution layer
    Event store write latency spike Audit write stays async; saga P99 unaffected Latency budget isolation

    The config store unavailability scenario deserves elaboration. Services cache their resolved market config with a short TTL. When the config store is unreachable, they serve from cache rather than failing the request. This is intentional — a config store outage should not take down loan processing. But it introduces a risk: if a config change is in flight when the outage occurs, some services will have the new config and others will have the old. The chaos test exercises this split-brain scenario explicitly, verifying that the canary hash on loan ID keeps each individual loan consistently on one config version regardless of which service is handling it.

    Summary of Key Decisions

    DecisionOption chosenRationale
    Config versioning Schema registry + versioned contracts + canary rollout Config changes carry the same production risk as code changes; they require the same deployment discipline
    Event publication Transactional outbox pattern Eliminates dual-write; loan DB write and event publication are atomic or neither occurs
    Multi-service correctness Saga orchestration with compensating transactions Distributed transactions are unavailable; saga provides atomic-or-compensated guarantee across service boundaries
    Ledger compensation Accounting contra-entry, not row deletion Regulatory audit requirements in all four markets prohibit deleting financial records
    Loan state model Event sourcing with append-only log Deterministic audit replay from event history; mutable state cannot satisfy regulatory reconstruction requirements
    Concurrent write safety Optimistic concurrency via event sequence version Makes concurrent transition races structurally detectable; no silent corruption
    Collection trigger safety Settlement window gate as explicit synchronisation Pipeline interaction failures are invisible without explicit synchronisation contracts between independently-scheduled subsystems
    Resilience validation Fault injection profiles per rail integration Adversarial provider behaviour is not discoverable through standard integration testing; it requires explicit simulation

    What We Would Do Differently

    01
    Ship the saga store and DLQ tooling before going live — not after.

    Saga failures and unreconcilable outbox events surfaced in production before the operational tooling to inspect, replay, and resolve them was ready. In a financial system, a stuck saga is not a background concern — it represents a loan in an inconsistent state. The replay and resolution tooling should be a launch gate, not a follow-up. We now treat it as a first-class deliverable alongside the saga itself.

    02
    Define config schema contracts before the first service ships against them.

    The compatibility shim we added after the v1→v2 config schema migration was a three-week engineering engagement that should have been unnecessary. Schema-first design — agree the contract, version it, write the migration path — before any consumer is deployed costs two days. Retrofitting it costs twenty. The rule we now enforce: no service ships against a config schema that does not have a documented versioning strategy.

    03
    Model pipeline interactions as first-class design artifacts.

    The delayed settlement cascade was caused by an unmodelled interaction between two independently correct pipelines. The gap was not in either pipeline's design — it was in the system-level design that should have enumerated every shared state boundary and inserted an explicit synchronisation contract. We now produce a pipeline interaction map as part of every service design review, identifying all shared state and the contract at each boundary.

    04
    Instrument saga step latency and compensation rate as primary metrics.

    We added saga observability reactively — after a compensation storm from a degraded ledger service was invisible in our dashboards for 18 minutes. The compensation rate is one of the highest-signal metrics in a saga-based system: a spike indicates either a downstream service degradation or a correctness problem in the saga definition itself. It should be on the primary ops dashboard from day one, with an alert set at 2× baseline.

    Conclusion

    The dominant constraint in financial infrastructure is not throughput — it is correctness under failure. A lending platform that processes repayments correctly 99.9% of the time and double-books 0.1% of the time is not a 99.9% correct system. It is a system with a correctness bug that surfaces on a schedule determined by transaction volume.

    The architecture described here — transactional outbox, saga orchestration with compensating transactions, event sourcing with deterministic replay, settlement window gating — is not sophisticated for its own sake. Each component exists to close a specific correctness gap. The outbox eliminates dual-write. The saga eliminates partial multi-service state. Event sourcing eliminates audit reconstruction ambiguity. The settlement gate eliminates pipeline interaction failures. Removing any one of them reintroduces the gap it was designed to close.

    The broader principle: in a distributed financial system, correctness is a property of the interaction between components, not of any individual component. A reconciliation service that is correct in isolation, a delinquency pipeline that is correct in isolation, and a collection service that is correct in isolation can collectively produce an incorrect outcome — as they did, until we modelled their interaction explicitly. Designing for correctness at the system level, not the service level, is the engineering discipline that separates platforms that hold up from platforms that require constant firefighting.

    © Utkarsh Mehrotra