Bird
Raised Fist0
HLDsystem_design~25 mins

Payment integration architecture in HLD - System Design Exercise

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Design: Payment Integration System
Design covers payment processing flow, integration with payment gateways, security, and scalability. Out of scope are user account management and order management systems.
Functional Requirements
FR1: Allow users to make payments using multiple payment methods (credit card, debit card, digital wallets).
FR2: Support secure storage and transmission of payment data.
FR3: Handle payment authorization, capture, and refunds.
FR4: Provide real-time payment status updates to users.
FR5: Integrate with external payment gateways and banks.
FR6: Ensure compliance with PCI-DSS security standards.
FR7: Support at least 10,000 concurrent payment transactions.
FR8: Provide high availability with 99.9% uptime.
Non-Functional Requirements
NFR1: API response latency must be under 300ms for payment initiation.
NFR2: System must handle peak loads during sales events (up to 50,000 transactions per hour).
NFR3: Sensitive data must be encrypted both in transit and at rest.
NFR4: System must be scalable to add new payment methods easily.
Think Before You Design
Questions to Ask
❓ Question 1
❓ Question 2
❓ Question 3
❓ Question 4
❓ Question 5
❓ Question 6
Key Components
API Gateway for client requests
Authentication and Authorization service
Payment Processing Service
Payment Gateway Integrations
Database for transaction records
Cache for quick status retrieval
Message Queue for asynchronous processing
Monitoring and Logging system
Security components (encryption, tokenization)
Design Patterns
Circuit Breaker pattern for external gateway calls
Event-driven architecture for asynchronous payment status updates
Retry and backoff strategies for failed transactions
Tokenization to avoid storing sensitive card data
Load balancing for scaling API endpoints
Reference Architecture
Client
  |
  v
API Gateway -- Auth Service
  |
  v
Payment Processing Service
  |          \
  |           -> Message Queue -> Async Workers -> Payment Gateway Integrations
  |
  v
Database <-> Cache
  |
  v
Monitoring & Logging
Components
API Gateway
Nginx or AWS API Gateway
Handles incoming client requests, routes to services, enforces rate limiting and security.
Authentication and Authorization Service
OAuth 2.0 / JWT
Verifies user identity and permissions before allowing payment operations.
Payment Processing Service
Java Spring Boot / Node.js
Core business logic for payment initiation, validation, and coordination.
Message Queue
RabbitMQ / AWS SQS
Decouples synchronous API calls from slower external payment gateway interactions.
Async Workers
Kubernetes pods running worker processes
Process payment gateway requests asynchronously, handle retries and failures.
Payment Gateway Integrations
REST/gRPC clients
Communicate with external payment providers for authorization, capture, refunds.
Database
PostgreSQL
Store transaction records, payment statuses, and audit logs.
Cache
Redis
Store recent payment statuses for fast retrieval.
Monitoring & Logging
Prometheus, Grafana, ELK Stack
Track system health, performance, and audit payment flows.
Security Components
TLS, HSM, Tokenization libraries
Encrypt data in transit and at rest, tokenize sensitive card data.
Request Flow
1. Client sends payment request to API Gateway.
2. API Gateway forwards request to Authentication Service for user validation.
3. Upon success, request goes to Payment Processing Service.
4. Payment Processing Service validates payment details and stores initial transaction record.
5. Payment request is placed on Message Queue for asynchronous processing.
6. Async Workers consume the queue, call external Payment Gateway APIs for authorization.
7. Payment Gateway responds with success or failure; Async Workers update transaction status in Database.
8. Cache is updated with latest payment status for quick client queries.
9. Client can poll or receive webhook notifications for payment status updates.
10. Monitoring system collects logs and metrics throughout the process.
Database Schema
Entities: - User (user_id, name, email) - Transaction (transaction_id, user_id, amount, currency, status, payment_method, created_at, updated_at) - PaymentMethod (payment_method_id, type, details_tokenized) - PaymentGatewayResponse (response_id, transaction_id, gateway_name, status, response_data, timestamp) Relationships: - User 1:N Transaction - Transaction 1:1 PaymentMethod - Transaction 1:N PaymentGatewayResponse
Scaling Discussion
Bottlenecks
API Gateway can become a bottleneck under high concurrent requests.
Database write and read load increases with transaction volume.
External payment gateway latency and rate limits can slow processing.
Message Queue saturation if async workers are slow.
Cache invalidation and consistency under heavy load.
Solutions
Use load balancers and auto-scaling groups for API Gateway and services.
Implement database sharding or read replicas to distribute load.
Use circuit breakers and fallback strategies for payment gateway calls.
Scale async workers horizontally and monitor queue length for auto-scaling.
Use cache with TTL and event-driven invalidation to maintain consistency.
Interview Tips
Time: Spend 10 minutes understanding requirements and clarifying scope, 20 minutes designing architecture and data flow, 10 minutes discussing scaling and security, 5 minutes summarizing.
Emphasize security and PCI-DSS compliance.
Explain asynchronous processing to handle slow external gateways.
Discuss how to handle failures and retries gracefully.
Highlight scalability strategies for peak loads.
Mention monitoring and alerting for operational health.

Practice

(1/5)
1. Which component in a payment integration architecture is primarily responsible for securely transmitting payment data between your system and the bank?
easy
A. Payment Gateway
B. Merchant Database
C. User Interface
D. Inventory Management System

Solution

  1. Step 1: Understand the role of each component

    The Payment Gateway acts as the secure bridge that transmits payment data from your system to the bank or processor.
  2. Step 2: Identify the secure transmission responsibility

    Other components like Merchant Database or User Interface do not handle secure transmission of payment data.
  3. Final Answer:

    Payment Gateway -> Option A
  4. Quick Check:

    Secure transmission = Payment Gateway [OK]
Hint: Payment Gateway always handles secure payment data transfer [OK]
Common Mistakes:
  • Confusing Payment Gateway with Merchant Database
  • Thinking User Interface handles security
  • Assuming Inventory Management is involved in payments
2. Which of the following is the correct sequence of steps in a typical payment integration flow?
easy
A. Bank -> Payment Processor -> Payment Gateway -> User initiates payment
B. User initiates payment -> Payment Gateway -> Payment Processor -> Bank
C. Payment Processor -> User initiates payment -> Bank -> Payment Gateway
D. Payment Gateway -> Bank -> User initiates payment -> Payment Processor

Solution

  1. Step 1: Identify the logical payment flow

    The user starts the payment, which goes to the Payment Gateway, then to the Payment Processor, and finally to the Bank for authorization.
  2. Step 2: Verify the order of components

    Options B, C, and D have incorrect sequences that do not match the real-world payment flow.
  3. Final Answer:

    User initiates payment -> Payment Gateway -> Payment Processor -> Bank -> Option B
  4. Quick Check:

    Payment flow order = A [OK]
Hint: Payment always starts with user and ends at bank authorization [OK]
Common Mistakes:
  • Reversing the order of components
  • Placing Bank before Payment Gateway
  • Confusing Payment Processor and Gateway roles
3. Consider this simplified payment request flow in pseudocode:
sendPaymentRequest(userData) {
  gatewayResponse = callPaymentGateway(userData)
  if (gatewayResponse.status == 'success') {
    processorResponse = callPaymentProcessor(gatewayResponse.data)
    return processorResponse.status
  } else {
    return 'failed'
  }
}

What will be the output if callPaymentGateway returns {status: 'success', data: 'txn123'} and callPaymentProcessor returns {status: 'approved'}?
medium
A. 'txn123'
B. 'success'
C. 'failed'
D. 'approved'

Solution

  1. Step 1: Analyze the gateway response

    The gateway returns status 'success' and data 'txn123', so the if condition is true and the processor is called.
  2. Step 2: Analyze the processor response

    The processor returns status 'approved', which is returned by the function.
  3. Final Answer:

    'approved' -> Option D
  4. Quick Check:

    Processor status returned = 'approved' [OK]
Hint: If gateway success, processor status is final output [OK]
Common Mistakes:
  • Returning gateway status instead of processor status
  • Returning transaction data instead of status
  • Ignoring the else branch
4. In a payment integration system, a developer notices that payment requests sometimes fail silently without error logs. Which is the most likely cause?
medium
A. Missing error handling after calling the payment gateway
B. Using HTTPS for communication
C. Encrypting payment data before sending
D. Validating user input before payment

Solution

  1. Step 1: Identify silent failure cause

    Silent failures usually happen when errors are not caught or logged properly, indicating missing error handling.
  2. Step 2: Evaluate other options

    Using HTTPS, encrypting data, and validating input improve security and correctness but do not cause silent failures.
  3. Final Answer:

    Missing error handling after calling the payment gateway -> Option A
  4. Quick Check:

    Silent failure = Missing error handling [OK]
Hint: Silent failures mean errors are not caught or logged [OK]
Common Mistakes:
  • Blaming HTTPS or encryption for failures
  • Ignoring the need for error handling
  • Assuming validation causes silent failures
5. You are designing a payment integration system expected to handle 10,000 transactions per second. Which architectural choice best supports scalability and reliability?
hard
A. Store all payment data in a single database table without sharding
B. Process all payments synchronously in a single server to ensure order
C. Use asynchronous message queues between components and horizontally scale payment processors
D. Skip retries on failed payments to reduce load

Solution

  1. Step 1: Identify scalability needs

    Handling 10,000 TPS requires distributing load and decoupling components to avoid bottlenecks.
  2. Step 2: Evaluate architectural choices

    Asynchronous queues and horizontal scaling allow parallel processing and fault tolerance. Single server or unsharded DB cause bottlenecks. Skipping retries reduces reliability.
  3. Final Answer:

    Use asynchronous message queues between components and horizontally scale payment processors -> Option C
  4. Quick Check:

    High TPS needs async queues + horizontal scaling [OK]
Hint: Scale horizontally and use async queues for high throughput [OK]
Common Mistakes:
  • Choosing synchronous single server processing
  • Ignoring database sharding or partitioning
  • Skipping retries reduces payment reliability