We need to architect a resilient payment gateway router that supports several features:
- ISO 20022: message transformation (likely to/from ISO 20022 format)
- SLA-tiering: different service levels (e.g., priority, latency, throughput)
- Per-issuer fallbacks: for each card issuer (or payment method), define fallback routes if primary fails
- Reconciliation proofs: ability to prove that transactions are correctly reconciled (maybe cryptographic proofs)
- Anomaly detection: detect suspicious or abnormal patterns
We need to design the system. The user said "Architect a resilient payment gateway router". So we need to produce a design, possibly with diagrams, descriptions, components, data flows, technologies, and how it meets the requirements.
We should produce a comprehensive architecture document. Let's break down:
- Overview: high-level description, goals, scope.
- Key components:
- Ingestion layer: receives payment requests (likely from merchants) in various formats (maybe ISO 8583, JSON, etc.) and transforms to internal canonical format.
- Router: core decision engine that routes payments based on rules, SLA, issuer, etc.
- Transformation engine: handles ISO 20022 message conversion (to/from internal format).
- SLA manager: tracks and enforces SLA tiers (maybe using priority queues, circuit breakers, etc.)
- Fallback manager: per-issuer fallback configurations, alternative endpoints.
- Reconciliation service: generates and verifies reconciliation proofs (like Merkle trees, digital signatures).
- Anomaly detection: real-time monitoring, ML models, alerts.
- Resilience features: circuit breakers, retries, failover, load balancing, idempotency, exactly-once semantics, monitoring, alerting.
- Persistence: databases, message queues, logging.
- Security: encryption, authentication, authorization, PCI DSS compliance.
- Data flow: step-by-step from request receipt to response, and asynchronous processes like reconciliation.
- Technology stack suggestions: languages (Java, Go, Python), frameworks, databases, message brokers (Kafka, RabbitMQ), cloud services, etc.
- Deployment: microservices, containerization, orchestration (K8s), multi-region.
- Scalability and performance.
- Fault tolerance and disaster recovery.
- Monitoring and observability: metrics, logs, tracing.
- Compliance: ISO 20022, PCI DSS, GDPR, etc.
- Implementation considerations: idempotency keys, deduplication, timeouts, retries with backoff, fallback sequencing.
We'll produce a structured answer with sections. The user likely expects a textual description with maybe diagrams in ASCII or described. We can produce a Mermaid diagram for architecture? Possibly we can include Mermaid code blocks. That would be nice.
Given that we are ChatGPT, we can output markdown with code blocks for diagrams.
Let's plan:
Introduction: brief context.
Architecture Principles: resilience, scalability, extensibility, security.
System Components:
- Front Door / API Gateway: entry point, authentication, rate limiting.
- Payment Ingress: receives messages, validates, transforms to internal representation. Supports multiple message types (ISO 20022, legacy). Uses ISO 20022 Transformation Service.
- Canonical Payment Model: internal data structure.
- Router Engine: core routing logic. Considers SLA tier (assigned per merchant or transaction), issuer, amount, etc. Selects appropriate acquirer/processor endpoint. Uses routing rules and fallback chain.
- SLA Manager: defines tiers (e.g., platinum, gold, silver) with expected latency, throughput, and fallback behavior. Enforces by prioritizing requests, allocating resources.
- Fallback Manager: stores per-issuer fallback configurations (e.g., if primary processor down, route to secondary). May include circuit breaker states.
- Processor Connectors: outbound adapters to various payment processors (e.g., Visa, Mastercard, local schemes). Each handles protocol conversion (maybe to ISO 8583, or proprietary).
- Response Aggregator: collects responses from processors, handles async responses, maps back to canonical model.
- Transformation Service: converts between canonical model and ISO 20022 XML/JSON. Also handles other formats if needed.
- Anomaly Detection Service: streams transaction events to detect anomalies (e.g., sudden spike in declines, fraud patterns). Could use rules engine or ML. Can trigger alerts or block transactions.
- Reconciliation Service: generates proofs for each batch/settlement. Uses cryptographic techniques (e.g., hash chaining, Merkle trees) to provide tamper-evident reconciliation. Also supports dispute resolution.
- Persistence Layer: transactional store (SQL for relational data, NoSQL for logs/events). Possibly separate databases: transactions, routing rules, fallback configs, SLA definitions, reconciliation data.
- Messaging: event bus (Kafka) for async processing (e.g., after transaction completed, send to reconciliation, anomaly detection, audit logs).
- Monitoring & Observability: Prometheus metrics, distributed tracing (OpenTelemetry), centralized logging (ELK).
- Control Plane: admin UI for managing rules, SLA tiers, fallback configs, viewing anomalies, reconciliation proofs.
Data Flow:
- Merchant sends payment request (maybe ISO 20022 pain.001 or custom JSON) to API Gateway.
- API Gateway forwards to Payment Ingress after auth.
- Ingress validates schema, transforms to canonical Payment object using Transformation Service.
- Ingress publishes PaymentRequested event to Kafka (or directly calls Router synchronously? For real-time, we need low latency, so might be synchronous path, but also async for non-critical). Actually, we need to consider that payment gateway typically responds quickly (within seconds). So the core flow should be synchronous end-to-end? But we can use async for non-critical tasks (logging, anomaly detection, reconciliation later). So main path: Ingress -> Router -> Processor Connector -> Response -> back to Ingress -> response to merchant. Possibly use a request-reply pattern on Kafka for async processing but still wait for reply? That might add latency. Better to use direct RPC (gRPC) between microservices for low latency. But we also want resilience: if a component fails, we need retries and fallback. So we can use a synchronous call chain with circuit breakers and timeouts.
Thus:
- Ingress calls Router (synchronous).
- Router, using SLA and rules, selects a Processor Connector and calls it (synchronous).
- Processor Connector sends request to external processor, gets response, returns to Router.
- Router returns to Ingress, which transforms response to appropriate format and returns to merchant.
Simultaneously, Ingress publishes an event to Kafka for async processing: transaction completed, for logging, anomaly detection, reconciliation, analytics.
Fallback handling: Router may have a list of processors for a given issuer. Primary is tried; if fails (timeout, error code), fallback manager may trigger next processor. This is per-issuer fallback. We need to handle idempotency: ensure that fallback does not cause duplicate payments. Use idempotency key from merchant. The processor connectors should support idempotency (some processors support it). For those that don't, we need to manage deduplication at our level (track in database, not retry if already processed). But careful: if first processor didn't respond (network failure), we may not know if payment went through, so we need to query or use a two-phase? Actually, typical payment gateways rely on the processor's response. If we get no response, we may retry with fallback but that could cause double charge if first one actually processed but we didn't get response. That's a classic problem. To be resilient, we need to implement safe retry strategies: maybe use a unique transaction ID that processors can deduplicate. Many processors have idempotency keys. We should require that. So we include idempotency key in request.
SLA-tiering: Different merchants or transaction types may have different SLA promises. We need to allocate resources accordingly. Could use priority queues and separate thread pools. Also define timeouts per tier. For example, platinum: 1-second timeout, gold: 2 sec, etc. If a transaction cannot be completed within SLA, we might proactively fallback or return an error. Also we may route platinum traffic to more reliable processors.
ISO 20022 transformation: Need to support both inbound and outbound ISO 20022 messages. The transformation service should be configurable with mapping rules (XSD to canonical). Could use a library or custom code. For high performance, we might pre-compile mappings.
Reconciliation proofs: For each settlement batch, we generate a Merkle root of all transactions. The proof can be provided to merchants or partners to verify inclusion. We'll need a service that periodically (e.g., daily) builds a Merkle tree from the settled transactions and publishes the root. Individual transaction proofs can be generated by providing the transaction's hash and the path. This ensures data integrity. We can also sign the root with a private key.
Anomaly detection: Could be rule-based (thresholds) and ML-based. We can use a stream processor (Kafka Streams, Flink) to compute aggregates in real-time. For ML, we might train offline and deploy a model that scores each transaction or batch. Anomaly service can subscribe to events and raise alerts to dashboard, or even block transactions by integrating with Router (real-time decision). But to keep it simple, we can have it as a separate service that monitors and alerts, and optionally updates risk scores that Router can use (e.g., if high risk, route to a different processor with stronger fraud checks). But the requirement says "anomaly detection", so we need to include it.
Resilience: Use circuit breakers (Hystrix, Resilience4j) around outbound calls. Implement retries with exponential backoff for transient failures. Have health checks and auto-restart. Deploy multiple instances across zones. Use a service mesh (Istio) for advanced resilience. Database replication. Backups.
PCI Compliance: As a payment gateway, we must protect cardholder data. Use encryption at rest and in transit. Mask sensitive data in logs. Use tokenization for storage. Possibly use a secure vault for keys. Limit access.
Scalability: Microservices that can scale independently. Use load balancers, auto-scaling groups. Partition data (sharding) by merchant ID or other.
Now, we should produce diagrams: a high-level component diagram, and maybe a sequence diagram for the request flow.
We can write mermaid code:
graph TB
subgraph "Client Layer"
M[Merchant] -->|HTTPS/ISO20022| AG[API Gateway]
end
AG -->|Auth, Rate Limit| IG[Payment Ingress]
IG -->|Canonical Event| R[Router]
R -->|SLA, Rules| FM[Fallback Manager]
FM -->|Processor List| PC[Processor Connector]
PC -->|External Processor| EP[Acquirer/Issuer]
EP -->|Response| PC
PC -->|Response| R
R -->|Response| IG
IG -->|Transformed Response| AG
AG -->|Response| M
IG -->|Async Event| KB[Kafka]
KB --> AD[Anomaly Detection]
KB --> RS[Reconciliation Service]
KB --> AL[Audit Logger]
We can also show the transformation service as separate:
graph LR
IG -- uses --> TS[Transformation Service]
R -- may use --> TS
But maybe it's clearer to include it as part of Ingress and Router? Actually, transformation might happen in Ingress to convert inbound to canonical, and in the response path to convert canonical to outbound format. So Ingress uses TS to transform request. For response, after Router returns, Ingress also uses TS to transform to merchant format. So IG depends on TS.
Additionally, we might have a separate Rule Engine for routing decisions? Could be embedded in Router.
Let's produce a more detailed description for each component, including data models.
We also need to discuss message transformation for ISO 20022. That includes pain.001 (credit transfer), pain.008 (direct debit), and maybe others like pacs.008? Actually, ISO 20022 for payments includes many message types. The gateway may need to translate between ISO 20022 and the processor's native format (e.g., ISO 8583). So transformation service may need to map fields accordingly.
Per-issuer fallbacks: The Fallback Manager likely stores configuration like:
issuer_id: "visa"
primary_processor: "visa_net"
fallback_processors: ["mastercard_net", "local_clearing"]
conditions: ["timeout", "high_decline_rate", "maintenance"]
The Router, when processing a transaction, looks up the issuer (from BIN or token) and gets the active processor list. It tries primary; if call fails or returns certain error codes, it triggers fallback to next. Also, the Fallback Manager might be aware of circuit breaker states for each processor (e.g., if processor is down, automatically skip). So integration with circuit breaker.
SLA-tiering: We need to assign a tier to each transaction. Could be based on merchant contract. The tier influences:
- Priority in queues.
- Timeout values.
- Choice of processors (some tiers may have dedicated higher-quality processors).
- Retry limits.
We'll have an SLA Store with definitions.
Reconciliation proofs: For each day, we generate a batch of settled transactions. We compute a Merkle tree where leaves are transaction hashes (including amount, timestamp, unique ID). The root is signed. We store the tree in a database (or just the root). To provide a proof, we can give the transaction hash and the sibling hashes along the path. The Reconciliation Service can generate these on demand.
Anomaly detection: We can define two types: real-time (per transaction) and batch (daily). Real-time: compute aggregates over sliding windows (e.g., declines per minute per merchant) and compare to thresholds. Batch: detect unusual patterns like sudden volume changes. The service can be built using Apache Flink or Kafka Streams. It can also feed risk scores back to the Router via a shared cache.
Implementation details: Let's propose a tech stack.
- Language: Go (for performance, concurrency) or Java. Since it's a payment system, we might want strong typing and maintainability. Go is good for network services. Java with Spring Boot is also common. But to keep language-agnostic, we can describe in abstract.
- API Gateway: Kong, Envoy, AWS API Gateway.
- Service Mesh: Istio for mutual TLS, traffic shifting, circuit breaking.
- Messaging: Apache Kafka for event streaming.
- Databases: PostgreSQL for structured data (transactions, rules); Redis for caching (processor status, rate limits); Cassandra for large volume logs? Possibly.
- Transformation: Use a library for ISO 20022 parsing (like Smooks, or custom with XSD). Or use a commercial solution.
- Monitoring: Prometheus + Grafana; Jaeger for tracing; Loki for logs.
- CI/CD: GitLab CI, ArgoCD for deployments.
- Deployment: Kubernetes clusters across multiple regions.
Now, we need to present the answer. We'll write a comprehensive architecture document with sections. We'll include diagrams in mermaid.
Let's structure:
- Executive Summary
- Design Goals and Principles
- High-Level Architecture
- Detailed Component Design
- API Gateway
- Payment Ingress
- Transformation Service
- Router Core
- SLA Manager
- Fallback Manager
- Processor Connectors
- Anomaly Detection
- Reconciliation Service
- Persistence & Caching
- Event Streaming (Kafka)
- Monitoring & Alerting
- Data Flow and Sequence
- Request Flow
- Asynchronous Processing
- Message Transformation (ISO 20022)
- Mapping Strategy
- Performance Considerations
- SLA Tiering Mechanism
- Per-Issuer Fallback Strategy
- Reconciliation Proofs
- Anomaly Detection Implementation
- Resilience Patterns
- Circuit Breaker
- Retry
- Timeout
- Bulkhead
- Idempotency
- Failover
- Security and Compliance
- Scalability and Performance
- Deployment Architecture
- Operational Considerations
- Conclusion
We'll produce a fairly long answer. But we should be concise yet thorough. The user likely expects a detailed proposal. We'll provide a rich answer.
Let's think about potential pitfalls: ensuring exactly-once processing? In a distributed system, that's hard. But we can aim for at-least-once with idempotency. For payments, exactly-once is critical. So we need to ensure that a transaction is not processed twice. Use a unique idempotency key from the merchant. Store processed keys in a database with TTL. Before processing, check if key exists. If yes, return the stored response (or replay). Also ensure that fallback doesn't cause duplicate: if primary timed out, we don't know if it processed; we must either rely on idempotency key on processor side or implement a two-phase commit? Typically, payment gateways rely on the processor's idempotency. So we will propagate the idempotency key to the processor and ensure the processor supports it. If not, we might need to query the processor to check status, but that's not always possible. So we might have to limit use of non-idempotent processors or have manual reconciliation.
We'll mention that requirement.
Now, let's write.
We'll start with an executive summary:
"The proposed payment gateway router is a cloud-native, microservices-based architecture designed for high availability, low latency, and compliance with ISO 20022 standards. It supports dynamic message transformation, SLA-based routing, per-issuer fallback chains, cryptographic reconciliation proofs, and real-time anomaly detection."
Then design principles: resilience, scalability, security, observability, extensibility.
High-level component diagram: show the major blocks and their interactions.
We'll use mermaid:
graph TB
subgraph "External"
M[Merchant] -->|HTTPS<br/>ISO20022| AG[API Gateway]
P[Payment Processors] -->|ISO8583<br/> Proprietary| PC[Processor Connectors]
end
AG --> IG[Payment Ingress]
IG --> TS[Transformation Service]
TS --> CM[Canonical Model]
IG -->|Canonical Request| R[Router]
R --> FM[Fallback Manager]
FM --> SM[SLA Manager]
R --> PC
PC --> P
PC -->|Response| R
R -->|Canonical Response| IG
IG --> TS
TS -->|Response Format| AG
AG --> M
IG -->|Async Event| KAFKA[Event Bus (Kafka)]
KAFKA --> AD[Anomaly Detection]
KAFKA --> RS[Reconciliation Service]
KAFKA --> AL[Audit Logger]
RS --> DB[(Reconciliation DB)]
AD --> ML[ML Model Service]
FM --> CB[Circuit Breaker Store]
SM --> DB_SLA[(SLA DB)]
R --> CACHE[(Redis Cache)]
That might be a bit messy but okay.
We'll then go through each component.
For Transformation Service: We can describe that it uses a mapping configuration (e.g., JSON or XML) to convert between ISO 20022 messages and the internal canonical model. The canonical model is a normalized representation of a payment transaction, containing fields like amount, currency, payer/payee details, execution date, etc. The transformation is two-way.
Router Core: It receives a canonical payment request. It consults SLA Manager to determine the SLA tier (e.g., from merchant ID or transaction attributes). It consults Fallback Manager to obtain the list of processors for the given issuer (derived from card BIN or token). It then selects a processor based on SLA (priority may be given to high-SLA processors) and current health (circuit breaker state). It invokes the corresponding Processor Connector.
Fallback Manager: Stores issuer-to-processor mappings. It also monitors circuit breakers and can dynamically adjust fallback order. Provides methods to get next processor on failure.
SLA Manager: Defines tiers with parameters: timeout, retry count, priority, dedicated processor pool. Tiers can be assigned per merchant, per transaction type, or by other attributes.
Processor Connectors: Implement outbound communication to each processor's protocol (e.g., ISO 8583 over TCP, HTTPS REST, SWIFT). They handle message construction, signing, encryption, and response parsing. Each connector is isolated, so failure in one does not affect others. They use circuit breaker pattern.
Anomaly Detection: Subscribes to the event stream. Uses stream processing (Kafka Streams) to compute metrics: transaction volume, success/failure rates, average amount, etc. Compares against baselines; triggers alerts when thresholds breached. May also use a ML model to score each transaction for fraud. If a high-risk score, it can send a command to Router (via a shared cache or event) to block or challenge.
Reconciliation Service: Periodically (e.g., nightly) collects settled transactions for a given period (e.g., previous day). It builds a Merkle tree where each leaf is the hash of a transaction's canonical representation (or a canonical ID + amount + timestamp + unique ID). It computes the root hash and signs it with a private key. The root is stored as the reconciliation proof for that batch. Merchants can query a proof for a specific transaction to verify inclusion. This service runs offline but can also generate on-demand.
Persistence:
- Transaction database (PostgreSQL) stores payment records (including status, processor used, timestamps). Indexes for retrieval.
- SLA DB: stores tier definitions, mappings.
- Fallback config DB.
- Redis: cache for processor health (circuit breaker states), idempotency keys (short TTL?), rate limit counters, SLA tier lookups.
- Event store: Kafka retains events for replay.
Event Bus: All payment events (request, response, status updates) are published to Kafka topics. This enables downstream processing and audit.
Monitoring: Each service exports Prometheus metrics (latency, error counts). Distributed tracing via OpenTelemetry. Logs structured JSON, shipped to ELK.
Now, provide sequence diagram for a successful request:
sequenceDiagram
participant M as Merchant
participant AG as API Gateway
participant IG as Payment Ingress
participant TS as Transformation Service
participant R as Router
participant FM as Fallback Manager
participant SM as SLA Manager
participant PC as Processor Connector
participant P as Processor
participant K as Kafka
M->>AG: POST /payment (ISO20022)
AG->>IG: Forward (with auth)
IG->>TS: Transform to canonical
TS-->>IG: Canonical Payment
IG->>R: Route(canonical)
R->>SM: Get SLA tier (merchant)
SM-->>R: Tier (Platinum)
R->>FM: Get processors for issuer
FM-->>R: [procA, procB, procC]
R->>PC: process with procA (sync)
PC->>P: Send request
P-->>PC: Response
PC-->>R: Response
R-->>IG: Canonical response
IG->>TS: Transform to ISO20022
TS-->>IG: Response message
IG-->>AG: Response
AG-->>M: HTTP 200 + body
IG->>K: Asynchronous event (completed)
Note over K: Anomaly Detection, Reconciliation, Audit
Also sequence for fallback:
If procA fails (timeout or error):
sequenceDiagram
participant R as Router
participant PC as Processor Connector (procA)
participant FM as Fallback Manager
participant PC2 as Processor Connector (procB)
R->>PC: process(request)
PC->>P: send
Note over PC: timeout or error
PC-->>R: error
R->>FM: mark failure(procA)
FM-->>R: next processor (procB)
R->>PC2: process(request) // retry with fallback
PC2->>P2: send
P2-->>PC2: success
PC2-->>R: success
But need to ensure idempotency: use same idempotency key.
Now, discuss ISO 20022 transformation in detail. We can use a mapping definition (e.g., XSLT, or custom mapping config). The canonical model is flexible. We'll need to support all necessary fields. Also discuss validation: both inbound (schema validation) and outbound.
SLA Tiering: Timeout values: Platinum 500ms, Gold 1s, Silver 2s. The router sets a deadline for the processor call; if exceeds, it triggers fallback. Also, we may have separate thread pools with different priorities.
Per-issuer fallback: The fallback list is ordered. The router attempts sequentially until success or exhausted. The fallback manager can also incorporate circuit breaker states: if a processor is marked open (failed repeatedly), it's skipped. The fallback config may also include weighting for load balancing.
Reconciliation proofs: We'll generate a daily batch. Steps:
- Collect all settled transactions for the batch (status = settled, settlement date = day).
- Sort by some consistent order (e.g., transaction ID).
- Compute leaf hash = H(transaction_id || amount || currency || timestamp || status).
- Build Merkle tree (binary hash tree). Use SHA-256.
- Root hash is the proof fingerprint. Sign with private key.
- Store each transaction's Merkle proof path (or generate on demand).
- Provide API for merchant to verify: given transaction ID and proof (list of sibling hashes + root), compute leaf and verify.
Anomaly detection: Use a combination of rules (e.g., if decline rate > 5% for a merchant in 5 min) and machine learning. The ML model could be a trained classifier (e.g., isolation forest, neural net) that takes features like amount, time, location, device fingerprint, etc. We can run it in real-time, but might be heavy. Could do near real-time. We can also use unsupervised clustering. The service can generate alerts in dashboard and also send a signal to the router to increase scrutiny or block.
Resilience patterns:
- Circuit Breaker: for each processor connection, track failures; after threshold, open circuit, fail fast, and periodically half-open to test.
- Retry: with exponential backoff; limited to 2-3 retries, but mindful of idempotency.
- Timeout: per SLA tier, enforced by router before fallback.
- Bulkhead: separate thread pools for different SLA tiers to prevent high load on low tier from affecting high tier.
- Idempotency: all inbound requests must include an idempotency key; we store processed keys to avoid duplicates.
- Graceful degradation: if a processor is down, fallback to another; if all fail, return appropriate error.
Security:
- TLS everywhere.
- Mutual TLS for service-to-service.
- Secrets management (Vault).
- PCI DSS: card data encrypted; no storage of CVV; tokens used.
- Authentication: OAuth2/JWT for merchants.
- Authorization: scopes.
Scalability: Horizontal scaling of stateless services. Use Kubernetes HPA based on CPU/latency. Partition Kafka topics by merchant ID for ordering per merchant? Actually, we may need ordering per merchant to preserve idempotency? Not necessarily; idempotency key ensures uniqueness regardless of order. But for processing, order may not be critical as long as idempotent. However, we might want to route all requests for a given merchant to same instance for caching? Not required.
Data partitioning: Shard transaction DB by merchant ID or time.
Deployment: Multi-region active-active? Possibly. But for simplicity, active-passive with failover. Use cloud provider (AWS, GCP). Use managed Kafka (Confluent), managed DB.
Operational: Run chaos testing, have runbooks, alerting on SLA breaches, circuit breaker opens.
Now, produce the answer in markdown with sections. We'll include mermaid diagrams in code blocks. Let's write.
Resilient Payment Gateway Router Architecture
1. Executive Summary
This document outlines a cloud‑native, microservices‑based payment gateway router built for resilience, low latency, and compliance with ISO 20022 standards. The system supports:
- ISO 20022 message transformation (both inbound and outbound)
- SLA‑tiered routing with priority queues and dedicated resources
- Per‑issuer fallback chains with circuit‑breaker awareness
- Cryptographic reconciliation proofs (Merkle trees + signatures)
- Real‑time anomaly detection (rule‑based + ML)
The design follows the 12‑factor app principles, uses Kubernetes for orchestration, and embraces event‑driven processing for scalability and auditability.
2. Design Goals & Principles
| Principle | Implementation |
|---|
| Resilience | Circuit breakers, retries with backoff, bulkheads, graceful degradation |
| Scalability | Stateless services, horizontal scaling, Kafka partitioning, sharded DBs |
| Security & Compliance | TLS/mTLS, PCI‑DSS, tokenization, secrets vault, audit logging |
| Observability | OpenTelemetry tracing, Prometheus metrics, structured logs (ELK) |
| Extensibility | Pluggable processor connectors, configurable mapping rules |
| Exactly‑once semantics | Idempotency keys + deduplication store |
3. High‑Level Architecture
graph TB
subgraph "External Actors"
M[Merchant] -->|HTTPS / ISO20022| AG[API Gateway]
P[Payment Processors] -->|ISO8583 / Proprietary| PC[Processor Connectors]
end
AG --> IG[Payment Ingress]
IG --> TS[Transformation Service]
TS --> CM[Canonical Model]
IG -->|Canonical Request| R[Router]
R --> FM[Fallback Manager]
R --> SM[SLA Manager]
R --> PC
PC --> P
PC -->|Response| R
R -->|Canonical Response| IG
IG --> TS
TS -->|Response Format| AG
AG --> M
IG -->|Async Event| KAFKA[Event Bus (Kafka)]
KAFKA --> AD[Anomaly Detection]
KAFKA --> RS[Reconciliation Service]
KAFKA --> AL[Audit Logger]
RS --> DB_R[(Reconciliation DB)]
AD --> ML[ML Model Service]
FM --> CB[Circuit Breaker Store]
SM --> DB_SLA[(SLA DB)]
R --> CACHE[(Redis Cache)]
4. Detailed Component Design
4.1 API Gateway
- Responsibilities: TLS termination, authentication (OAuth2/JWT), rate limiting, request routing to Ingress.
- Tech: Envoy/Kong, integrated with service mesh (Istio) for mTLS and traffic shifting.
4.2 Payment Ingress
- Validates request format (schema, required fields, signature).
- Extracts idempotency key (
Idempotency-Key header) and stores it in Redis with a short TTL (to detect duplicate submissions).
- Publishes a
PaymentRequested event to Kafka after successful validation (async).
- Calls Transformation Service to convert the inbound message (ISO 20022
pain.001, pain.008, etc.) into the Canonical Payment Model.
- After receiving the response from the Router, transforms the canonical response back to the required outbound format (ISO 20022
pacs.002, pacs.004, or merchant‑specific JSON) and returns it to the API Gateway.
4.3 Transformation Service
- Bidirectional mapping between ISO 20022 (XML/JSON) and the internal canonical model.
- Uses XSLT or a configurable mapping engine (e.g., Smooks, Apache Camel) for high‑performance conversions.
- Maintains XSD‑based validation for ISO 20022 messages.
- Caches compiled mappings to reduce latency.
4.4 Canonical Payment Model
A normalized representation that abstracts away scheme‑specific details:
{
"id": "uuid_v4",
"idempotency_key": "merchant_provided_key",
"amount": 1234.56,
"currency": "EUR",
"direction": "credit|debit",
"payer": { "name": "...", "iban": "...", "bic": "..." },
"payee": { "name": "...", "iban": "...", "bic": "..." },
"execution_date": "2024-01-15",
"issuer_bin": "123456",
"merchant_id": "merchant_123",
"sla_tier": "platinum",
"metadata": { ... }
}
4.5 Router Core
- Input: Canonical payment request.
- Decision flow:
- Ask SLA Manager for the tier (derived from
merchant_id or request attributes).
- Ask Fallback Manager for the ordered list of processors for the
issuer_bin.
- Select processor based on:
- SLA tier (high‑tier may restrict to premium processors)
- Circuit‑breaker state (skip open circuits)
- Load (available connection slots)
- Invoke the chosen Processor Connector within a timeout derived from the SLA tier.
- Failure handling: On timeout or non‑retryable error, mark processor as failed (via Circuit Breaker) and retry with the next processor in the fallback chain. If all fail, return an appropriate error to the Ingress.
- Response: The canonical response from the processor is enriched with routing metadata (processor used, attempt count) and sent back to Ingress.
4.6 SLA Manager
- Stores tier definitions in a relational DB (
sla_tiers):
CREATE TABLE sla_tiers (
name VARCHAR PRIMARY KEY,
timeout_ms INT,
max_retries INT,
priority INT,
allowed_processors JSONB
);
- Tiers are looked up by
merchant_id (or by transaction attribute) and cached in Redis (TTL 5 min).
- The Router passes the tier’s
timeout_ms to the outbound call and configures its thread‑pool priority.
4.7 Fallback Manager
- Configuration table
issuer_fallbacks:
CREATE TABLE issuer_fallbacks (
issuer_bin_prefix VARCHAR,
processor_order JSONB, -- ["procA", "procB", "procC"]
conditions JSONB -- e.g., {"maintenance": ["procA"], "high_declines": ["procB"]}
);
- On each router request, it returns the current ordered list, excluding processors whose circuit breakers are in
OPEN state (read from Redis/CB store).
- The manager also receives failure events (via Kafka) to adjust rankings (e.g., push a flaky processor to the end of the chain).
4.8 Processor Connectors
- One connector per external processor (Visa, Mastercard, local ACH, etc.).
- Each implements the specific protocol (ISO 8583 over TCP, HTTPS REST, SFTP, etc.).
- Uses circuit breaker (Resilience4j) and timeout per SLA.
- Handles request signing/encryption if required.
- Converts between the canonical model and the processor’s message format.
- Idempotency: If the processor supports an idempotency key, the connector adds it. If not, the connector checks the deduplication store before sending to avoid double processing.
4.9 Anomaly Detection Service
- Streaming layer: Kafka Streams or Apache Flink application.
- Metrics (computed over sliding windows):
- Transaction volume per merchant/issuer
- Decline rate, error code distribution
- Average amount, amount variance
- Velocity (txn/sec)
- Rules engine: Simple thresholds (e.g., “decline rate > 5% in 5 min”) → alert.
- ML model: Pre‑trained model (Isolation Forest, Gradient Boosting) that scores each transaction based on features (amount, time, location, device fingerprint). The model runs in a separate service (
ML Model Service) and the detection service calls it asynchronously.
- Actions:
- Push alert to dashboard (Grafana/Elastic).
- Write anomaly record to DB.
- Optionally publish a
TransactionRisk event that the Router can consume (via a shared Redis cache) to block or challenge high‑risk transactions.
4.10 Reconciliation Service
- Runs daily batch (or on‑demand) for a given settlement period.
- Steps:
- Query settled transactions from the primary DB (status =
SETTLED, settlement date = target date).
- Sort deterministically (e.g., by
id).
- Compute leaf hash:
H = SHA256(id || amount || currency || timestamp || status).
- Build a Merkle tree (binary). The root hash is the Reconciliation Fingerprint.
- Sign the root with an offline private key (HSM or cloud KMS).
- Store the root and the Merkle proof paths (or generate on‑demand).
- Proof API: Merchant provides a transaction
id; service returns the sibling hashes and root. Merchant can recompute to verify inclusion.
- The service also publishes the root to a public bulletin board (or blockchain) for extra tamper evidence if required.
4.11 Persistence Layer
| Store | Purpose | Tech |
|---|
| PostgreSQL | Transactions, merchant profiles, SLA definitions, fallback configs | Managed RDS / CloudSQL |
| Redis | Circuit breaker state, idempotency keys (short TTL), rate limits, SLA cache | ElastiCache / Memorystore |
| Kafka | Event streaming (request/response events, anomalies) | Managed Kafka (Confluent, MSK) |
| S3 / Blob | Long‑term raw logs, backups | Cloud storage |
All writes are idempotent (upserts) and durable (WAL, replication).
4.12 Event Bus (Kafka)
- Topics:
payment.requested
payment.completed
payment.failed
processor.health
anomaly.detected
reconciliation.proof
- Consumers: Anomaly Detection, Reconciliation Service, Audit Logger, ML training pipeline (offline).
- Retention: 30 days for replayability.
4.13 Monitoring & Alerting
- Metrics: Prometheus counters/gauges (latency, errors, circuit state, queue depth).
- Tracing: OpenTelemetry distributed traces across all services.
- Logging: Structured JSON logs, aggregated in Elasticsearch/Kibana.
- Alerts: PagerDuty/Opsgenie integration for SLA breaches, circuit openings, anomaly spikes.
5. Data Flow & Sequence Diagrams
5.1 Successful Request Flow
sequenceDiagram
participant M as Merchant
participant AG as API Gateway
participant IG as Payment Ingress
participant TS as Transformation Service
participant R as Router
participant SM as SLA Manager
participant FM as Fallback Manager
participant PC as Processor Connector
participant P as Processor
participant K as Kafka
M->>AG: POST /payment (ISO20022)
AG->>IG: Forward (with auth)
IG->>TS: Transform to canonical
TS-->>IG: Canonical Payment
IG->>R: Route(canonical)
R->>SM: Get SLA tier (merchant)
SM-->>R: Tier (Platinum)
R->>FM: Get processors for issuer
FM-->>R: [procA, procB, procC]
R->>PC: process with procA (sync)
PC->>P: Send request
P-->>PC: Response
PC-->>R: Response
R-->>IG: Canonical response
IG->>TS: Transform to ISO20022
TS-->>IG: Response message
IG-->>AG: Response
AG-->>M: HTTP 200 + body
IG->>K: Async event (completed)
Note over K: Anomaly Detection, Reconciliation, Audit
5.2 Fallback Flow (with Circuit Breaker)
sequenceDiagram
participant R as Router
participant PC as Processor Connector (procA)
participant FM as Fallback Manager
participant PC2 as Processor Connector (procB)
participant CB as Circuit Breaker Store
R->>PC: process(request)
Note over PC: timeout or non‑retryable error
PC-->>R: error
R->>CB: record failure(procA)
R->>FM: get next processor (exclude procA)
FM-->>R: procB
R->>PC2: process(request) // retry with fallback
PC2->>P2: send
P2-->>PC2: success
PC2-->>R: success
6. ISO 20022 Message Transformation
- Inbound: Merchant → API Gateway → Ingress → Transformation Service.
- The service validates against the ISO 20022 XSD (e.g.,
pain.001.001.03).
- Mapping rules are defined in a YAML/JSON config that specifies how each element maps to the canonical field.
- Example:
/Document/CstmrCdtTrfInitn/PmtInf/Cdtr/Nm → canonical.payee.name.
- Outbound: After Router returns, the canonical response is transformed back to the appropriate ISO 20022 message (
pacs.002 for credit transfer status, pacs.004 for direct debit cancellation, etc.).
- Performance: Mappings are compiled at service start and cached; JIT‑enabled languages (Go, Java) achieve sub‑millisecond latency.
7. SLA‑Tiering Mechanism
| Tier | Timeout (ms) | Max Retries | Dedicated Processor Pool? |
|---|
| Platinum | 500 | 0 (no retry, fallback only) | Yes (high‑throughput, low‑latency) |
| Gold | 1000 | 1 | Partial |
| Silver | 2000 | 2 | No (shared pool) |
| Standard | 5000 | 3 | No |
- Allocation: Each tier gets its own thread pool (Bulkhead) so that a flood of Silver traffic cannot starve Platinum.
- Priority: Requests are placed in tier‑specific priority queues; the scheduler always drains Platinum before Gold, etc.
- Monitoring: SLA compliance is tracked per tier and reported to merchants.
8. Per‑Issuer Fallback Strategy
- Configuration: Stored in
issuer_fallbacks table (see §4.7). Supports wildcard BIN prefixes (e.g., 4* for all Visa).
- Dynamic Adjustment: The Fallback Manager listens to
processor.health events. If a processor’s error rate exceeds a threshold for 5 min, its circuit breaker opens and it is automatically excluded.
- Load Balancing: Within the same priority level, the Router can round‑robin or least‑connections across healthy processors.
9. Reconciliation Proofs (Merkle Tree)
- Batch Definition: One batch = all transactions settled on a specific date (UTC).
- Leaf Hash:
H = SHA256( transaction_id || amount || currency || timestamp || status ).
- Tree Construction: Complete binary tree; if number of leaves is not a power of two, duplicate the last leaf.
- Root Signing: Private key stored in an HSM (e.g., AWS CloudHSM) signs the root hash.
- Proof Generation: For a given transaction, the service returns the array of sibling hashes from leaf to root. The client recomputes the leaf hash and combines with siblings up to the root; if the computed root matches the signed root, inclusion is proven.
- API:
GET /reconciliation/proof?txid={id}&date={YYYY-MM-DD} returns JSON with {proof: [...], root: "...", signature: "..."}.
10. Anomaly Detection Implementation
- Stream Processing (Kafka Streams):
- Windows: tumbling (5 min) and sliding (1 min) windows.
- Aggregations: count, sum, avg, stddev per key (merchant_id, issuer_bin).
- Threshold Checks: Configurable rules stored in DB; when a metric crosses threshold, an
AnomalyDetected event is emitted.
- ML Scoring:
- Features:
amount, time_of_day, merchant_category, card_country, ip_geolocation, device_id.
- Model: Trained offline on historical labeled fraud data; deployed as a TensorFlow Serving or ONNX runtime microservice.
- The Anomaly service calls the model for each transaction (or micro‑batch) asynchronously; a risk score > 0.8 triggers a
HighRisk event.
- Integration with Router: The Router subscribes to
HighRisk events and updates a risk cache (Redis) with a block_until timestamp for the affected idempotency_key or card_token. Subsequent attempts to use the same token within the block window are rejected automatically.
11. Resilience Patterns
| Pattern | Usage |
|---|
| Circuit Breaker | Around each outbound Processor Connector call (Resilience4j). State stored in Redis for shared visibility. |
| Retry | Exponential backoff with jitter; respects max_retries from SLA tier. Idempotency key is reused. |
| Timeout | Enforced by Router per SLA; CompletableFuture.orTimeout or similar. |
| Bulkhead | Separate thread pools per SLA tier. |
| Idempotency | Deduplication store (Redis SETNX with TTL 24 h) prevents duplicate processing. |
| Graceful Degradation | If all processors for an issuer are down, the Router returns 503 Service Unavailable with a Retry-After header. |
| Failover | Multi‑region deployment with DNS‑based failover for the API Gateway; Kafka mirroring for cross‑region replay. |
12. Security & Compliance
- Encryption: TLS 1.3 everywhere; mTLS for service‑to‑service.
- PCI‑DSS:
- Cardholder data (PAN, CVV) is never logged; masked in any audit trail.
- Strong encryption (AES‑256) for data at rest.
- Tokenization: PANs are replaced by tokens before storage.
- Regular vulnerability scans and penetration testing.
- Secrets: Vault (HashiCorp) or cloud KMS for DB passwords, API keys, TLS certs.
- Access Control: RBAC via OAuth2 scopes; admin UI requires MFA.
- Audit: All mutating actions are logged to an immutable store (e.g., AWS CloudTrail, GCP Audit Logs).
13. Scalability & Performance
- Stateless Services: All microservices can be scaled horizontally behind a load balancer.
- Auto‑Scaling: Kubernetes HPA based on CPU, request latency, and custom metrics (queue depth).
- Data Partitioning:
- Transactions DB partitioned by
merchant_id hash and month.
- Kafka topics partitioned by
merchant_id to preserve order per merchant (optional, not required due to idempotency).
- Caching: Redis caches for processor health, SLA definitions, and idempotency checks reduces DB load.
- Throughput Target: > 10 k TPS per region (depending on processor connectivity).
14. Deployment Architecture
- Infrastructure: AWS / GCP / Azure. managed Kubernetes (EKS, GKE, AKS).
- Regions: Active‑passive with cross‑region replication for DR. Kafka clusters replicated across regions (MirrorMaker 2).
- CI/CD: GitOps with ArgoCD; automated security scanning (Trivy, Sonar) in pipeline.
- Chaos Engineering: Periodic fault injection (Chaos Mesh) to test resilience.
15. Operational Considerations
- Runbooks:
- Circuit breaker opened → check processor status page, manually adjust fallback order if needed.
- SLA breach → identify bottleneck (DB, thread pool, network) and scale.
- Anomaly spike → investigate via Kibana dashboards.
- Alerting: PagerDuty for critical alerts (circuit open, SLA miss > 5 min, reconciliation failure).
- Backups: Daily snapshots of PostgreSQL; point‑in‑time recovery. Kafka retention backed up to S3.
- Disaster Recovery: RTO < 30 min, RPO < 5 min (using cross‑region replication).
16. Conclusion
This architecture delivers a highly resilient, compliant, and extensible payment gateway that meets modern demands for ISO 20022 support, SLA guarantees, per‑issuer fallback, provable reconciliation, and intelligent anomaly detection. By leveraging proven cloud‑native patterns and a modular design, the system can evolve with regulatory changes and emerging payment schemes while maintaining operational excellence.