Design a payments factory: channels, routing rules, fraud screening, and exception…
- User
Design a payments factory: channels, routing rules, fraud screening, and exception handling.
- Assistant
Payments Factory Design
A Payments Factory is a centralized, scalable platform that ingests payments from diverse sources, normalizes them, applies intelligence (fraud, routing), executes them across optimal processors, and handles lifecycle events with resilience. It supports high-volume enterprise use cases like treasury management, mass payouts, and marketplaces.
This design is modular, event-driven (using Kafka/RabbitMQ), microservices-based (Kubernetes/Docker), and compliant with PCI-DSS, PSD2, GDPR. Assumes cloud-native (AWS/GCP) with serverless options for scale.
High-Level Architecture
[Channels Ingress] --> [Normalization Gateway] --> [Fraud Screening] --> [Routing Engine] --> [Execution Orchestrator] | v [Event Bus (Kafka)] <--> [Exception Handler] <--> [Manual Review Queue] <--> [DLT/Blockchain Settlement (Optional)] | v [Reporting & Analytics] <-- [Observability (Prometheus/Grafana/ELK)]- Data Flow: Asynchronous via events for decoupling.
- Key Principles: Idempotency (unique
payment_id), eventual consistency, circuit breakers (Resilience4j), rate limiting. - Scalability: Horizontal pods, auto-scaling, sharding by tenant/region.
- Tech Stack: Go/Java/Spring Boot for services; PostgreSQL/CockroachDB for state; Redis for caching; gRPC/REST APIs.
1. Channels (Ingress Layer)
Handles multi-channel ingestion with protocol normalization to a canonical
PaymentRequestschema (JSON/Protobuf).Channel Type Description Protocol/Format Examples Validation API Real-time pulls/pushes REST/gRPC/Webhooks Merchant apps, POS systems Schema (JSON Schema/OpenAPI), rate limits (10k TPS) Batch Files High-volume scheduled SFTP/SCP, formats: CSV, MT940, ISO 20022, NACHA ERP exports, bank statements File parsers (Apache Camel), CRC checksums Real-Time Streams Event-driven Kafka, Kinesis Wallet apps, IoT payments Schema registry (Avro), dead-letter queues Bank Integrals Direct bank feeds ISO 20022 API, FIX SEPA, ACH, Swift GPI CA pinning, OAuth2/mTLS P2P/Wallets Consumer-facing WebSockets, Push notifications Venmo-like, crypto on-ramps CAPTCHA, device fingerprinting - Gateway: NGINX/Kong for API mgmt; transforms to unified schema:
{payment_id, amount, currency, payer/payee, metadata, timestamp}. - Security: mTLS, JWT auth, WAF (Cloudflare/AWS Shield).
- Throughput: 100k+ TPS with buffering.
2. Routing Rules Engine
Decision engine selects optimal processor/provider based on rules, optimizing for cost, speed, success rate, and compliance.
- Core Model: Drools/Esper rules engine or ML-based (TensorFlow Serving) for dynamic routing.
- Routing Criteria (evaluated in priority order):
Priority Criteria Examples Providers Routed To 1. Compliance/Region Country, sanctions (OFAC) EU → SEPA; US → ACH Local: TrueLayer (EU), Plaid (US); Global: Adyen 2. Speed Instant/Next-day <5min → RTP (Visa Direct); Batch → ACH RTP: FedNow, Visa B2B Connect 3. Cost FX markup, fees Low-value → Stripe; High-value → Treasury (JPM) Cards: Stripe/Braintree; Bank: SVB/Synapse 4. Amount/Volume Tiered <10k → Wire Crypto: Coinbase Commerce 5. Risk Score From fraud (see below) Low → Fast track; High → Fallback Fallback: Manual processor 6. Fallback Success rate >95% Round-robin with health checks Multi: Adyen → Stripe → Payoneer - Dynamic Rules: Configurable via UI/API (e.g., YAML DSL). A/B testing via feature flags (LaunchDarkly).
- Output:
RouteDecision {processor, estimated_fee, eta, backup_routes}. - ML Enhancement: Reinforcement learning on historical success/cost data.
Pseudocode Example:
func Route(payment PaymentRequest, fraudScore float64) RouteDecision { if isSanctioned(payer.country) { return Decline("Sanctions") } if fraudScore > 0.8 { return RouteTo("ManualReview") } if payment.amount < 1000 && payment.currency == "USD" { return RouteTo("stripe", cost: 0.029) } // ... rules }3. Fraud Screening
Multi-layered, real-time scoring (sub-100ms latency).
-
Layers:
- Rules-Based (Immediate): Velocity checks (e.g., >5 txns/min), blacklists (IP/Email/Device), BIN checks.
- ML Models (Async): XGBoost/Neural Nets trained on features: device ID, geolocation velocity, amount anomaly, graph (payer-payee links). Hosted on SageMaker.
- External Oracles: 3rd-party APIs (Sift, Forter, Signifyd) for device intelligence, email validation.
- Behavioral: Session analysis, graph neural nets for networks.
-
Scoring: 0-1 risk score.
Score Action Probability <0.3 Approve 95% 0.3-0.7 Challenge (3DS/OTP) 80% >0.7 Decline/Review Block 90% -
Integration: Sidecar pattern; events to fraud service pre-routing.
-
Feedback Loop: Label outcomes → retrain models weekly.
-
False Positive Tuning: Per-tenant thresholds.
4. Exception Handling
Resilient lifecycle management for failures (5-9s target uptime).
Exception Type Triggers Handling Strategy Validation Errors Invalid schema, missing funds Immediate reject; sync response with error_code. Log to Sentry.Fraud/Decline High score, processor reject Async event to DECLINED; notify payer/payee via webhook/email (SendGrid).Processor Failure Timeout, 4xx/5xx Retry (exponential backoff, max 3x); fallback route; circuit breaker. Network/Infra Kafka outage, DB failover Dead-letter queue (DLQ) → reprocessing; idempotent workers. Manual Review Ambiguous fraud, high-value Queue (RabbitMQ priority); UI dashboard (React + Material-UI) for reviewers; SLA <1hr. Settlement Delays Provisional → final Webhook callbacks; reconciliation cron (daily). - State Machine: XState/Apache Step Functions for payment states:
PENDING → ROUTED → EXECUTING → SETTLED/FAILED. - Notifications: Slack/Teams alerts for SLO breaches; customer webhooks with retries.
- Audit Trail: Immutable log (Kafka + Elasticsearch); 7-year retention.
Monitoring & Observability
- Metrics: Payment latency, success rate, fraud TP/FP (Datadog/Prometheus).
- Tracing: Jaeger for end-to-end.
- Alerts: PagerDuty for >1% failure rate.
- Reporting: BI dashboard (Metabase) for volume, costs, ROI.
Implementation Roadmap
- MVP (4 weeks): API channel + basic routing/fraud (Stripe only).
- Scale (8 weeks): Multi-channel, ML fraud, exceptions.
- Enterprise: Batch, DLT settlement, custom rules UI.
This design handles 1M+ daily payments at <1% cost overhead. Cost: ~$0.50/100 txns (infra + processors). Open to refinements!
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.