Payment Gateway with Artificial Intelligence Layer: the Frontier between Money and AI
Why I decided to separate money from probability When I started designing this Payment Gateway, I began with a premise that I consider non-negotiable in any financial system that incorporates artificial intelligence: money cannot be moved by a probabilistic component. A language model, no matter how sophisticated, produces plausible text, not certainty. In an authorization, capture, or reversal flow, plausibility is not an acceptable standard.

Therefore, I structured the entire architecture around a principle that guides every design decision I made from the first line of the drawing: the financial core is deterministic, and artificial intelligence acts exclusively as a risk-assistive layer. It's not a buzzword, it's a registered and formalized architectural decision that arbitrates any technical conflict that arises during implementation.
In this article, I first explain the general architecture of the Gateway, without going into the specific tools I chose, because I want the architectural reasoning to be clear regardless of the stack. Then, in the second part, I describe in depth and with concrete evidence how I implemented the artificial intelligence layer: where it acts, how it acts, what types of automation I developed, and what stack supports this layer.
Part 1: Payment Gateway Architecture
The problem this system solves
Every Payment Gateway needs to respond, in milliseconds, to a question with direct financial implication: should this transaction be approved, denied, or sent for review. This response needs to consider signals such as value outside the customer's historical pattern, multiple attempts in a short period, divergence between card and device location, merchant chargeback history, and recent account holder behavior.
Fixed rules resolve obvious cases well. The real problem lies in the gray area, in ambiguous cases where a set of weak, isolated signals does not trigger any rule, but combined suggest high risk. It is exactly in this gray area that I decided to introduce artificial intelligence, and I detail this in the second part of this article. For now, I focus on the deterministic backbone that supports everything.
Principles that guided each decision
I established ten architectural principles before designing any component, and I treat these principles as design constraints, not suggestions:
- Absolute separation between deterministic flow and probabilistic flow.
- Artificial intelligence as decision support, never as financial executor.
- Mandatory idempotence in every transactional operation.
- Events as a mechanism for decoupling between components.
- End-to-end auditing, per transaction, without exception.
- Observability from the first line of code, not as a retrofit.
- Minimization of sensitive data before any external processing.
- Secure fallback always when an assistive component fails.
- A single decision engine as the point of arbitration.
- Deterministic financial core, without exception, under no circumstances.
Logical view of the transaction flow
The flow begins in the checkout layer, which captures the payment intention and nothing more. This layer does not carry financial business rules, it only initiates the journey and accompanies the status.
The request then reaches the transaction core, responsible for validating the contract, authenticating and authorizing the call, applying idempotence, creating the transaction, persisting the official state, and publishing a creation event. This core controls a rigid state machine, and no state transition occurs outside of it. States such as created, under risk analysis, approved by risk, denied by risk, review required, authorized, captured, canceled, and refunded follow strictly controlled transitions, and any attempt at invalid transition is rejected at the source.
The persistence of the official state occurs in a relational transactional database, and the publication of events follows the Outbox pattern: every state change that generates an event is recorded in the same database transaction that records the state, which eliminates the classic risk of an event being lost or an event being published without the corresponding transaction having been persisted. An asynchronous process reads the pending events and publishes them in a distributed event bus, which decouples the transaction core from all downstream consumers, including the anti-fraud service.
The anti-fraud service consumes the creation event, mounts the risk context, executes a deterministic rules engine, calculates an initial score, and consults a high-performance storage for speed checks, such as multiple attempts in a short interval. If the risk is clearly low or clearly high, the decision comes directly from this deterministic flow. If the risk is ambiguous, it is at this exact point that the artificial intelligence layer enters, and I detail this in the second part of this article. For now, I focus on the deterministic backbone that supports everything.
The final decision, whether it comes purely from rules or is enriched by AI analysis, is consolidated by a single decision engine, which also considers the merchant's specific policy, account history, and operational limits. This decision engine is the only point in the system authorized to produce a final financial decision, and this decision is always deterministic, auditable, explainable, reproducible, and traceable.
Hot Path and Cold Path
An architectural decision that I consider central to the system's robustness is the separation between Hot Path and Cold Path. The Hot Path is the critical low-latency path, responsible for validating payment, applying fast rules, consulting cached features, and defining simple decisions, always avoiding any heavy synchronous dependency on a language model. The Cold Path is the asynchronous and investigative path, responsible for in-depth analysis, generating a risk dossier, detailed explanation, and support for human analysts.
This separation exists because treating artificial intelligence as a critical synchronous dependency is a design error that compromises availability. A language model that is unavailable, slow, or unstable can never block payment authorization. Therefore, I keep AI mostly out of the critical path, reserving this layer for cases that really justify deeper analysis.
Idempotence, consistency, and resilience
I covered idempotence in every transactional operation, with specific keys that guarantee that the same request, with the same payload, always returns the same transaction, and that the same key with different payload generates an explicit conflict error. This applies to payment creation, authorization, capture, refund, event processing, and external provider webhooks.
For resilience, I applied retry with exponential backoff, configured timeout per dependency, circuit breaker for external providers, and asynchronous processing as standard. The operational principle I sustain is simple to state and difficult to violate: in doubt, the system degrades safely, never assumes an optimistic state without confirmation.
Security and observability as first-class requirements
I treat security and observability as functional requirements, not as separate infrastructure concerns. This means encryption in transit and at rest, strong authentication between services, card data tokenization, sensitive data masking, and controlled retention according to data protection legislation and payment industry norms.
In observability, I guarantee end-to-end traceability through identifiers propagated throughout the chain, correlating request, transaction, event, and risk analysis. I follow technical metrics such as latency per component, business metrics like approval, denial, and manual review rates, and specific risk analysis quality metrics, such as false positive and false negative rates.
Part 2: The Artificial Intelligence Layer
Where AI acts
The AI Risk Agent, the name I gave to my artificial intelligence layer, acts at a very specific point in the architecture: exclusively within the anti-fraud service, after the deterministic rules engine has already processed the transaction and calculated an initial score, and only when that result is ambiguous or indicates high risk. AI is never triggered for every transaction. It is selectively triggered, which reduces cost, reduces aggregate system latency, and concentrates analytical capability exactly where it adds real value.
This means that for most transactions, the flow is resolved entirely by deterministic rules, fast and predictable. AI enters only in the slice of cases where weak and combined signals do not allow for an automatic decision based solely on rule logic.
How AI acts, with evidence of contract
The AI Risk Agent never receives raw transaction data. Before any call to the model, I execute a mandatory context sanitization step, which removes any sensitive raw data, such as complete card number, security code, passwords, or internal tokens. I do not send card number, security code, raw account holder data, passwords, sensitive tokens, unnecessary personal data, or internal infrastructure secrets to the AI. I only send derived context: aggregated customer and merchant profile, behavior signals, summarized history, triggered deterministic rules, partial score, and risk indicators.
The expected input by the agent follows a fixed contract: transaction identifier, merchant identifier, value, currency, payment method type, customer profile summary, merchant profile summary, device summary, location summary, speed signals, triggered rules, and historical risk indicators. Nothing else crosses the sanitization boundary.
The output is always a structured object, validated against a rigid schema before any subsequent use. This is a real example of the output format that the agent produces:
{
"risk_summary": "Transaction with high risk due to combination of high value, multiple recent attempts, and location mismatch.",
"risk_factors": [
"high_value_transaction",
"velocity_attempts",
"country_mismatch"
],
"anomaly_indicators": [
"unusual_device_behavior",
"new_customer_high_value"
],
"confidence": 0.82,
"suggested_action": "REVIEW_REQUIRED"
}
This suggested_action is never executed directly. It is consumed by the decision engine as another signal, along with the result of the deterministic rules, the risk score, the merchant's policy, and the account history. The final event that comes out of this consolidated process carries the AI execution identifier as an audit field, never as an authority field:
{
"event_id": "uuid",
"event_type": "risk.final_decision.created",
"occurred_at": "2026-01-01T10:00:02Z",
"transaction_id": "uuid",
"merchant_id": "uuid",
"decision": "REVIEW_REQUIRED",
"risk_score": 82,
"reason_codes": [
"HIGH_VALUE",
"VELOCITY_ATTEMPTS",
"COUNTRY_MISMATCH"
],
"ai_run_id": "uuid"
}
I notice in this contract a point that I consider central: the decision field is produced by the deterministic engine, not by AI. The ai_run_id field exists for traceability, so I can reconstruct, at any time, which AI analysis contributed as a signal to that specific decision, without implying that AI decided anything.
Types of automation and intelligence developed
I developed four central artificial intelligence capabilities within this layer.
The first is assisted risk analysis, where the model interprets the combination of weak signals that, isolated, would not trigger any rule, but together suggest a suspicious pattern, such as a new customer making a high-value transaction, with multiple recent attempts and a mismatch between the card and device countries.
The second is the generation of explainability, transforming technical signals, often numerical and fragmented, into a narrative understandable by both the decision engine and a human analyst who may eventually review the case. I consider this capability as important as the analysis itself, because a risk decision without auditable explanation is a decision that does not survive a regulatory audit or a chargeback dispute.
The third is support for manual review, where AI generates a prioritized summary of the most relevant points of the case, reducing the time a human analyst spends reconstructing the context of a transaction flagged for review.
The fourth is the production of an auditable summary, a structured artifact that remains attached to the transaction and documents exactly what the assistive reasoning presented, with what level of confidence, and how that reasoning related to the final decision made by the deterministic engine. This artifact is what allows reconstructing, months later, exactly why a specific transaction received a specific decision.
Internal architecture of the AI Risk Agent, component by component
I structured the agent into three internal sub-layers, deliberately isolated to allow independent testing of each responsibility. This is the real decomposition of components that I implemented:
Input sub-layer
RiskContextValidator, validates that the received payload is complete and consistent before any processing.PiiSanitizer, removes any residual sensitive data that should not be present in the context.SchemaValidator, ensures that the input structure respects the contract expected by the model.
Reasoning sub-layer
RiskPromptBuilder, builds the instruction sent to the model from the already sanitized context, always using a versioned prompt, never freely edited in production.LLMRiskReasoner, invokes the language model via API and conducts reasoning on the received signals.- `


