The user wants a design for a "payments factory." This is a common architectural pattern in fintech for handling diverse payment types through a unified system.
Key Components to Design:
- Channels (Ingress): How payments enter the system.
- Routing Rules (Orchestration): How to decide where a payment goes (which PSP/Gateway).
- Fraud Screening (Risk): Security checks.
- Exception Handling (Reconciliation & Monitoring): Handling failures and edge cases.
High-Level Architecture Strategy:
A "factory" implies a modular, assembly-line approach.
- Input: API requests (API Gateway), Batch files (SFTP), Internal Triggers (Scheduled jobs).
- Processing Pipeline: Validation → Risk → Routing → Execution → Post-Processing.
1. Channels (The Input Layer):
- Concept: Decouple the source from the processing logic.
- Types:
- Real-time API (E-commerce, Mobile Apps).
- Batch/File-based (Payroll, B2B payouts).
- Internal/System (Refunds, Fee deductions).
- Design Pattern: Ingress Adapter. Normalize incoming requests into a canonical "Payment Order" model.
2. Routing Rules (The Brain):
- Concept: Smart switching based on cost, success rate, and compliance.
- Factors:
- Cost: Which PSP is cheapest for this corridor/currency?
- Performance: Which has the highest success rate?
- Compliance: Sanction lists, currency support.
- Volume caps: Daily limits on specific providers.
- Design Pattern: Rule Engine (Drools, custom logic) or Strategy Pattern.
- Mechanism: "Best Fit" algorithm.
3. Fraud Screening (The Shield):
- Concept: Stop bad actors before money moves.
- Layers:
- Pre-Processing: Velocity checks, blacklist/whitelist, format validation.
- Real-time Scoring: ML models (Features: amount, time, geo, device fingerprint).
- External Data: 3D Secure (3DS), AVS (Address Verification).
- Action: Allow, Deny, Challenge (Step-up auth), or Review (Manual queue).
4. Exception Handling (The Safety Net):
- Concept: Payments fail often (network blips, insufficient funds). The system needs resilience.
- Categories:
- Technical Failures: Timeouts, 500 errors → Retry with exponential backoff.
- Business Declines: Insufficient funds, card blocked → Notify user, try alternate route (if applicable).
- Ambiguous States: Network timeout but money might have moved → Reconciliation loop.
- Reconciliation: Idempotency keys, async status webhooks, T+1 settlement file matching.
Structure of the Response:
I should organize this logically, perhaps like a technical spec or architectural overview.
- Introduction: Define the "Factory" concept (centralized processing).
- Core Architecture Diagram (Mental or text-based): Explain the flow.
- Detailed Sections:
- Ingestion Channels (API, Batch).
- Fraud & Risk Engine (Pre-auth, Post-auth).
- Intelligent Routing (Cost, Compliance, Tech).
- Execution (PSP Abstraction).
- Exception Handling & Reconciliation (Retries, Ledger).
- Data Model: Briefly mention the Canonical Payment Object.
- Technology Stack: Suggest modern tools (Kafka, Redis, PostgreSQL).
Refining the content:
- Routing: Make sure to mention "Smart Routing" vs. "Static Routing." Smart routing involves looking at real-time success rates.
- Fraud: Distinguish between hard rules (velocity) and soft rules (ML scores).
- Exceptions: Crucial point: Idempotency. If the system crashes, we shouldn't double-charge.
- Ledger: A payments factory needs an immutable log of every state transition.
Self-Correction during drafting:
- Initial thought: Focus heavily on database schemas.
- Correction: Keep it architectural. The prompt asks for "design," implying system design and flow, not just SQL tables.
- Add: The concept of an "Anti-Corruption Layer" or "Canonical Model" is vital. We receive many formats (ISO 20022, JSON, Proprietary), but internally we must speak one language.
Final Polish: Use standard industry terminology (ISO 8583, ISO 20022, PCI-DSS, Idempotency, Reconciliation).
Let's structure the output with clear headings and bullet points for readability. I will create a conceptual architecture diagram using Mermaid syntax for clarity.
Designing a Payments Factory requires moving away from monolithic payment processing to a modular, orchestrated architecture. In this model, the "factory" accepts raw inputs (payment requests) from various channels, processes them through a standardized assembly line (screening, routing), and delivers the finished product (a successful transaction) via the optimal provider.
Here is the architectural design for a high-scale Payments Factory.
1. High-Level Architecture
The system is designed as an Orchestrated Pipeline. A payment request enters the factory and moves sequentially through specific stations.
graph LR
A[Channels] --> B[Ingestion & Normalization]
B --> C[Fraud & Risk Screening]
C --> D{Decision Engine}
D -- Reject --> E[Exception Handling]
D -- Approve --> F[Smart Router]
F --> G[Provider Adapters]
G --> H[Settlement & Reconciliation]
2. Ingestion & Channels (The Input Funnel)
The Factory must decouple how a payment is requested from how it is processed.
Supported Channels
- E-Commerce API: Real-time, synchronous requests (e.g., checkout).
- Mobile SDKs: Tokenized card details sent via the gateway.
- Batch Processing (ACH/Wire): FTP/S3 drops of bulk payment files (e.g., payroll, supplier payouts).
- Internal Triggers: Scheduled recurring billing or subscription renewals.
The Normalization Layer (Anti-Corruption Layer)
Do not pass raw channel data to the core engine.
- Function: Transforms diverse inputs (JSON, XML, CSV) into a Canonical Payment Model.
- Canonical Model: A strictly typed internal object containing:
Payer (ID, Device Fingerprint, Billing Info)
Payee (Merchant ID, Bank Account)
Transaction (Amount, Currency, 3DS Data, Metadata)
Idempotency Key (Critical for preventing double-spending during retries).
3. Fraud Screening & Risk (The Gatekeeper)
Screening happens before routing. The factory must not spend resources routing a transaction that will be blocked.
The Risk Pipeline
- Velocity Checks (Stateless): Redis-based counters.
- Rule: If > 5 attempts from
IP Address in 1 minute → Hard Block.
- Rule: If > 10 failed cards from
User ID in 1 hour → Soft Block (MFA required).
- Internal Watchlists:
- Check against internal blacklists (users who issued chargebacks previously).
- External Screening:
- Sanctions/PEP: Screen against OFAC, UN, EU lists (mandatory for compliance).
- Device Fingerprinting: Analyze the device context (e.g., is the user browsing via Tor? Is the device "rooted"?).
- Machine Learning Scoring:
- If the transaction is "High Value" (configurable threshold), send to an ML model.
- Output: Risk Score (0–100).
Actionable Outcomes
- ALLOW: Proceed to routing.
- BLOCK: Return 403/Decline.
- CHALLENGE: Trigger 3D Secure (Strong Customer Authentication) or 2FA.
- MANUAL REVIEW: Pause transaction and push to a human ops queue (e.g., KYC verification required).
4. Routing Rules (The Brain)
The Routing Engine determines the best way to execute the approved payment.
Routing Strategy: Cost vs. Success Rate
The engine selects a Payment Service Provider (PSP) (e.g., Stripe, Adyen, PayPal, Direct Visa/Mastercard connection) based on a rule chain.
Priority Logic:
- Regulatory/Geo-Routing:
- Rule: If
Currency == INR, route to Razorpay (Local Schema).
- Rule: If
Region == EU, ensure PSD2 compliance, route to Adyen.
- Volume/Cost Optimization:
- Rule: If
Transaction_Amount > $1000, route to WireProvider (lower flat fee).
- Rule: If
Transaction_Amount < $5, route to WalletProvider (micropayments).
- Intelligent Retry (Cascade Logic):
- If the primary route fails with a "soft decline" (e.g., Bank Down), automatically re-route to a secondary provider.
- Note: This is handled by the Exception Handler.
The "Smart Router"
- Static: Rules defined by ops teams (YAML/JSON configs).
- Dynamic: A feedback loop where the system monitors real-time success rates of PSPs. If
Stripe latency > 2s or success rate drops < 80%, traffic is shifted to Checkout.com.
5. Exception Handling (The Safety Net)
Payments fail constantly. A robust factory distinguishes between "Business Failures" and "Technical Failures."
Types of Exceptions
- Hard Declines (Business):
- Code: Insufficient Funds, Card Stolen.
- Action: Do not retry. Notify the user immediately.
- Soft Declines (Temporary):
- Code: Bank Busy, Timeout, Generic Decline.
- Action: Retry with Backoff or Route Switch. Attempt 2: Route to a different acquiring bank.
- Technical Failures:
- Code: TCP Timeout, 500 Error from PSP.
- Action: Ensure Idempotency. The system must query the PSP to check the status before retrying (to prevent duplicate charges).
The Dead Letter Queue (DLQ)
If a payment gets "stuck" (e.g., the provider returned a malformed response or the database locked), the message goes to a DLQ.
- Ops Dashboard: Humans investigate stuck payments here.
- Replay capability: Allow ops to fix the data and re-inject the message into the pipeline.
6. Reconciliation & Ledger (The Truth)
The "Factory" isn't done until the money is settled.
- Immutable Ledger: Every state change (Created → Risk Pass → Routing → Success) is written to an append-only log.
- Batch Reconciliation:
- PSPs send settlement reports (usually daily CSVs).
- The system ingests these files and matches them against the internal Ledger.
- Discrepancy Handling: If the Internal Ledger says "Success" but the Bank File says "Failed," an alert is raised for manual accounting.
Summary of Technical Requirements
| Component | Tech Recommendation |
|---|
| Orchestration | Temporal.io or Camunda (Handles long-running workflows and retries natively). |
| Message Queue | Apache Kafka or RabbitMQ (for decoupling ingestion from processing). |
| Database | PostgreSQL (Transaction states) + Cassandra/DynamoDB (High volume audit logs). |
| Caching | Redis (Velocity checks, session tokens, routing config). |
| Idempotency | SHA-256 hash of request body + User ID stored in Redis with TTL. |
Operational Dashboard (KPIs)
You cannot manage what you cannot measure. The Factory needs a real-time UI showing:
- TPS (Transactions Per Second): Current load.
- Approval Rate: Aggregated and per-provider.
- Latency: P99 processing time.
- Financial Exposure: Total liability in "Pending" states.