
Table of Contents
By Khimananda Oli | Last reviewed: August 2026
Building a Payment Gateway API from Scratch is fundamentally an exercise in data integrity and security, not just web development. Unlike standard CRUD applications, financial systems cannot tolerate eventual consistency, lost requests, or silent failures; every transaction must be atomic, traceable, and cryptographically verified. This guide outlines the architectural patterns, database schemas, and operational safeguards required to build a production-grade payment platform that meets global compliance standards while serving local markets like Nepal.
What core architecture is needed when building a payment gateway API from scratch?
The most common mistake engineers make when building a payment gateway API from scratch is treating money as a mutable integer in a single column. In production fintech systems, you must adopt a double-entry ledger model where every transaction creates at least two opposing entries. This ensures the system can always self-audit: the sum of all debits must equal the sum of all credits. Before writing a single line of API code, you need to understand how data flows through your system securely.
This architecture separates concerns strictly. The API Gateway handles authentication, rate limiting, and idempotency checks before any request touches the Core Ledger. For teams in Nepal integrating with local wallets like eSewa or Khalti alongside international cards, this abstraction layer is vital. It allows you to normalize disparate upstream responses into a unified internal state machine. If you are also managing high-volume transactional data, reviewing PostgreSQL administration essentials will help ensure your ledger database remains performant under load.
How do you implement idempotency and prevent double-spending?
Networks are unreliable. Clients retry. When building a payment gateway API from scratch, you must assume every POST request could arrive twice. Without idempotency, a retried charge results in double billing. The solution is an idempotency key pattern enforced at the database level, not just the application cache.
Designing the Idempotency Schema
Never rely solely on Redis for idempotency in financial systems. Cache evictions can lead to duplicate processing. Instead, use a dedicated PostgreSQL table with a unique constraint. This guarantees atomicity even during failovers.
CREATE TABLE idempotency_keys (
key_hash BYTEA PRIMARY KEY, -- SHA-256 hash of client key
endpoint TEXT NOT NULL,
request_body_hash BYTEA NOT NULL,
response_code INT,
response_body JSONB,
created_at TIMESTAMPTZ DEFAULT NOW(),
locked_at TIMESTAMPTZ -- Prevents concurrent processing
);
-- Index for cleanup jobs
CREATE INDEX idx_idempotency_created ON idempotency_keys(created_at); Handling Concurrent Requests Safely
A common race condition occurs when two identical requests hit different pods simultaneously. You must use row-level locking. The workflow should be:
- Hash the incoming
Idempotency-Keyheader combined with the endpoint path. - Attempt an
INSERTwithlocked_at = NOW(). If it fails due to constraint violation, another request is active. - If the row exists but
response_codeis NULL andlocked_atis recent, return409 Conflictor wait briefly. - If the row exists with a completed response, return the cached response immediately without re-processing.
- After processing, update the row with the actual response and clear
locked_at.
This pattern ensures exactly-once semantics for side effects. For deeper insights into handling concurrency and replication lag in your ledger backend, see our guide on PostgreSQL replication and high availability.
What security standards apply when building a payment gateway API from scratch?
Security in payments is non-negotiable. When building a payment gateway API from scratch, you inherit the responsibility of protecting cardholder data (CHD) and sensitive authentication data (SAD). Even if you offload raw card handling to a processor, your API metadata and user PII remain targets.
Tokenization Over Encryption
Do not encrypt PANs in your application database. Use a dedicated vault service (like AWS Payment Cryptography or a FIPS 140-2 validated HSM) to exchange raw card data for format-preserving tokens. Your ledger should only ever see these tokens. This drastically reduces your PCI-DSS scope from Level 1 to potentially Level 4, saving hundreds of thousands in annual audit costs.
Secrets Management and Signing
All API responses containing financial data must be signed. Use HMAC-SHA256 with rotating keys stored in a secrets manager like HashiCorp Vault or AWS Secrets Manager. Never hardcode keys. For webhook notifications to merchants, implement a signature verification header so they can trust the payload originated from you. If you are deploying this infrastructure on Kubernetes, follow Kubernetes secrets management done right to avoid leaking credentials via environment variables or logs.
How do you choose between SQL and NoSQL for payment ledgers?
When building a payment gateway API from scratch, the choice of database dictates your reliability ceiling. While NoSQL offers horizontal scale, financial ledgers demand strong consistency and complex joins for reconciliation. Here is a practical comparison based on production experience:
| Criteria | PostgreSQL (Recommended) | MongoDB / DynamoDB |
|---|---|---|
| Consistency Model | Strong ACID by default; serializable isolation available | Eventual consistency default; read-after-write requires tuning |
| Transaction Support | Multi-table, multi-row atomic transactions native | Multi-document transactions supported but performance-heavy |
| Schema Enforcement | Strict typing prevents invalid ledger states | Flexible schema risks inconsistent historical records |
| Reconciliation | Complex aggregations and window functions optimized | Aggregation pipeline powerful but less mature for finance |
| Compliance Audits | Widely accepted by QSA auditors; mature tooling | Requires additional justification and controls |
| Best Use Case | Core ledger, user balances, settlement | Metadata, audit logs, session state, analytics |
In practice, use PostgreSQL for the ledger and MongoDB for unstructured metadata. If you are new to managing document stores alongside your relational ledger, our MongoDB administration basics guide covers essential operational patterns.
What observability practices are critical for payment APIs?
You cannot fix what you cannot see. When building a payment gateway API from scratch, traditional metrics like CPU and memory are insufficient. You need business-level observability that tracks money movement in real-time.
The Four Golden Signals for Payments
- Latency: Distinguish between successful and failed request latency. A slow failure is worse than a fast one because it holds resources and frustrates users.
- Traffic: Monitor transactions per second (TPS) broken down by merchant, payment method, and region. Sudden drops often indicate upstream bank outages, not your code.
- Errors: Track explicit error codes (e.g.,
INSUFFICIENT_FUNDS,CARD_DECLINED) separately from system errors (500,TIMEOUT). Alert on system errors; dashboard business errors. - Saturation: Measure connection pool usage, queue depth, and HSM throughput. Financial systems fail catastrophically when saturated, not gracefully.
Distributed Tracing for Reconciliation
Every transaction must carry a correlation ID from ingress to bank response. When a merchant claims "I was charged but got no confirmation," you need to trace that specific request across services in seconds. Implement OpenTelemetry early. Retrofitting tracing into a live payment system is painful and error-prone. Structured logging with context fields (merchant_id, txn_id, idempotency_key) is mandatory for forensic analysis.
Next Steps for Your Payment Platform
Building a Payment Gateway API from Scratch is a marathon that demands discipline in data modeling, security, and operational excellence. Start with a robust double-entry ledger and idempotency layer before adding features. Prioritize PCI compliance and observability from day one; retrofitting them later is exponentially harder. Whether you are serving Kathmandu merchants or global SaaS platforms, the principles of atomicity and auditability remain universal. If your team needs architectural review or compliance guidance for your payment infrastructure, contact me to discuss your specific requirements.