Dual-Rail Fiat & Crypto Payment Processing Gateway
Designed and deployed mission-critical dual-rail payment infrastructure uniting PCI-compliant Fiat card checkout with multi-chain Crypto settlement (USDT, USDC, SOL, ETH, and self-hosted BTCPay Server) backed by an immutable double-entry ledger.
The Production Challenge
Reconciling instantaneous credit card authorizations with asynchronous, variable-finality blockchain confirmations (including network retries, duplicate webhooks, partial underpayments, and chain reorgs) without ever double-crediting accounts.
The Engineered Solution
Engineered a strict idempotent state machine in Laravel protected by distributed Redis locks, cryptographic webhook verification, a self-hosted BTCPay Server, real-time Solana/EVM confirmation listeners, and an append-only double-entry ledger.
Payment engineering is unforgiving: webhooks arrive out of order, providers retry timeouts aggressively, users refresh checkout tabs mid-flight, and blockchains experience confirmation variance across Bitcoin, EVM networks, and Solana. A naive `UPDATE accounts SET balance = balance + amount` pattern inevitably breaks under concurrency.
The gateway separates payment intent detection from financial settlement. Inbound card webhooks (verified via HMAC signatures) and on-chain block listeners feed into a single idempotent state machine. Every state transition acquires a scoped Redis lock, validates the legal state transition inside a serializable MySQL transaction, and writes balanced debit/credit rows into an append-only double-entry ledger.
Race Conditions & Fragile Balance Updates
- Overlapping payment provider webhooks risked crediting the same invoice twice during network retries.
- Mutable balance columns offered no forensic audit trail when disputes, fees, or FX spreads occurred.
- Custodial third-party crypto processors added high fees, KYC friction, and withdrawal delays.
- Slow blockchain confirmations left users staring at frozen checkout spinners.
Redis-Locked State Machine & Double-Entry Ledger
- Composite idempotency keys + Redis distributed locks guarantee each settlement transitions exactly once.
- Every penny and satoshi is recorded as balanced debit/credit journal entries in an immutable ledger.
- Self-hosted BTCPay Server + direct EVM/Solana listeners provide non-custodial zero-middleman settlement.
- Optimistic mempool detection updates Livewire checkout status in real time before final confirmation.
Dual-Rail Topology — Fiat Tokens, Multi-Chain Listeners & BTCPay
Both traditional card rails and non-custodial crypto nodes converge into one idempotent Laravel settlement core.
flowchart TD
Checkout["Unified Checkout UI (Livewire)"] --> Router{"Payment Rail"}
Router -->|"Fiat Cards"| Card["PCI Tokenized Card Processor"]
Router -->|"USDT / USDC / ETH / SOL"| Nodes["Real-Time EVM & Solana Listeners"]
Router -->|"Bitcoin / Lightning"| BTCPay["Self-Hosted BTCPay Server"]
Card -->|"HMAC Webhook"| Guard["Idempotency & Redis Lock Guard"]
Nodes -->|"Tx Finality Event"| Guard
BTCPay -->|"Signed Invoice Webhook"| Guard
Guard --> Ledger[("Immutable Double-Entry Ledger (MySQL 8)")]
Settlement Sequence — Guaranteeing Exactly-Once Crediting
How duplicate webhooks or concurrent retry workers are safely absorbed without double-settlement.
sequenceDiagram
participant W as Webhook / Chain Listener
participant R as Redis Lock
participant S as Settlement State Machine
participant D as MySQL Double-Entry Ledger
W->>W: Verify HMAC / On-chain Tx Signature
W->>R: Acquire lock(payment_intent_id)
R-->>W: Lock Granted
W->>S: Transition Pending -> Settled
S->>D: BEGIN TRANSACTION
D->>D: Unique constraint check(idempotency_key)
alt Already Settled
D-->>S: No-op (Idempotent 200 OK)
else First Settlement
D->>D: Insert Debit(Clearing) + Credit(Merchant)
D-->>S: COMMIT
end
S->>R: Release Lock
S-->>W: Dispatch Fulfillment Event
public function settlePayment(PaymentIntent $intent, string $idempotencyKey, int $minorUnits): void
{
Cache::lock("settlement:{$intent->id}", 10)->block(5, function () use ($intent, $idempotencyKey, $minorUnits): void {
DB::transaction(function () use ($intent, $idempotencyKey, $minorUnits): void {
$locked = PaymentIntent::query()->lockForUpdate()->findOrFail($intent->id);
if ($locked->status === PaymentStatus::Settled) {
return; // Safe idempotent exit on duplicate webhook retries
}
LedgerTransaction::createOrFailUnique($idempotencyKey, [
['account_id' => $locked->clearing_account_id, 'direction' => 'debit', 'amount' => $minorUnits],
['account_id' => $locked->merchant_account_id, 'direction' => 'credit', 'amount' => $minorUnits],
]);
$locked->update([
'status' => PaymentStatus::Settled,
'settled_at' => now(),
]);
});
});
}
// ledger_transactions enforces UNIQUE (idempotency_key) as a final DB safety net
Architectural Highlights
- Distributed Redis locks + MySQL unique idempotency keys preventing duplicate settlements across overlapping webhooks and queue retries.
- Self-hosted BTCPay Server paired with custom EVM and Solana block listeners for non-custodial BTC, USDT, USDC, SOL, and ETH settlement.
- Append-only double-entry accounting ledger guaranteeing balanced debits and credits across multi-currency settlements, fees, and refunds.
- Strict cryptographic HMAC webhook verification and PCI-compliant card tokenization keeping raw card data off origin servers.
- Optimistic UI state resolution in Livewire giving customers sub-second feedback upon mempool or authorization detection.
Double-Entry Ledger Over Single Balance Columns
Storing a mutable `balance` integer makes reconciliation and chargeback audits fragile. Recording immutable debit/credit journal lines guarantees every balance can be mathematically proven at any point in time.
Self-Hosted BTCPay + Direct Chain Listeners
Running a dedicated BTCPay Server alongside custom EVM/Solana listeners eliminated recurring percentage processor fees and gave full custody and confirmation-threshold control.
Designing or rescuing a system like this?
I work directly with engineering teams and startup founders on high-concurrency Laravel, MySQL performance engineering, payment infrastructure, and edge caching.