Aegispay
AegisPay is a production-grade payment orchestration SDK built with TypeScript and Node.js, designed for high-volume, mission-critical payment processing. It leverages advanced concurrency control, formal state machines, transactional outbox, event sourcing, and intelligent routing to ensure correctness, reliability, and scalability.
Install / Use
/learn @techySPHINX/AegispayREADME
AegisPay
Enterprise-Grade Payment Orchestration Platform
A mission-critical payment processing SDK built on distributed systems principles, designed for high-volume financial workloads demanding zero data loss, zero duplicate charges, and 99.99% availability.
Built for Scale: Process 10,000+ TPS with sub-200ms P95 latency ✅ Benchmarked
Built for Correctness: Event sourcing + distributed locking + state machine guarantees
Built for Resilience: Circuit breakers + chaos engineering + intelligent routing
📊 Performance Validation
All performance claims are validated through automated benchmarks:
| Metric | Claim | Benchmark Result | Status | | ----------------- | ----------------- | ------------------------------------------ | ------------ | | Throughput | 10,000+ TPS | View Report | ✅ Validated | | Latency (P95) | < 200ms | View Report | ✅ Validated | | Reliability | 95%+ Success Rate | View Report | ✅ Validated |
📖 Full Testing Documentation | 📊 Benchmark Reports
🎯 Why AegisPay?
The Payment Orchestration Problem
Modern payment systems face critical challenges:
- Gateway Failures: 2-5% of transactions fail due to gateway issues
- Duplicate Charges: Race conditions cause customers to be charged multiple times
- Lost Revenue: System crashes during payment processing lose money
- Vendor Lock-in: Hard-coded gateway integrations prevent switching
- Cascading Failures: One gateway failure brings down the entire system
- Audit Nightmares: Missing transaction trails complicate compliance
The AegisPay Solution
AegisPay solves these with mathematically proven correctness and battle-tested resilience patterns:
graph LR
A[Request] --> B{Idempotency<br/>Check}
B -->|New| C[Distributed<br/>Lock]
B -->|Duplicate| Z[Return Cached]
C --> D[State<br/>Machine]
D --> E{Circuit<br/>Breaker}
E -->|Open| F[Fallback<br/>Gateway]
E -->|Closed| G[Primary<br/>Gateway]
F --> H[Event<br/>Sourcing]
G --> H
H --> I[Transactional<br/>Outbox]
I --> J[Success]
style B fill:#4CAF50
style D fill:#FF6B6B
style E fill:#2196F3
style H fill:#9C27B0
✨ Advanced Features
🔐 Correctness Guarantees (Zero Data Loss)
1. Distributed Locking
Prevents concurrent modifications to the same payment:
// Automatic distributed locking
await lockManager.withLock(paymentId, async () => {
// Only one process can execute this at a time
await processPayment(payment);
});
Use Case: Prevents duplicate charges when user clicks "Pay" multiple times or API receives duplicate requests.
2. Optimistic Locking
Prevents lost updates using version-based concurrency control:
const payment = await paymentRepo.findById(id);
payment.version; // Current: 5
// Another process updates it
await otherProcess.update(payment); // Version becomes 6
// This update will fail with ConflictError
await paymentRepo.update(payment); // Still version 5 - CONFLICT!
Use Case: Handles race conditions in distributed systems where multiple services modify the same payment.
3. Event Sourcing
Complete audit trail with state reconstruction from events:
// All state changes become immutable events
PaymentInitiated → PaymentProcessing → PaymentAuthorized → PaymentCompleted
// Reconstruct payment state from event history
const payment = eventStore.replayEvents(paymentId);
Use Case: Audit compliance, debugging production issues, time-travel queries, dispute resolution.
4. Transactional Outbox Pattern
Guarantees exactly-once event delivery:
// Database transaction ensures atomicity
await db.transaction(async (tx) => {
await tx.payments.update(payment);
await tx.outbox.insert(event); // Both succeed or both fail
});
// Separate process publishes events
outboxProcessor.publish(); // Exactly-once delivery guaranteed
Use Case: Ensures webhooks, notifications, and integrations never miss events, even during crashes.
5. Formal State Machine
Prevents invalid state transitions with mathematical guarantees:
// Compile-time and runtime validation
payment.transition(PaymentState.COMPLETED, PaymentState.INITIATED); // ❌ INVALID
payment.transition(PaymentState.INITIATED, PaymentState.PROCESSING); // ✅ VALID
Use Case: Prevents data corruption from invalid operations (e.g., refunding an unpaid order).
🧠 Intelligent Routing & Resilience
6. Multi-Factor Gateway Selection
Real-time metrics-based routing optimizes for success rate, latency, and cost:
const router = new IntelligentRouter({
strategy: RoutingStrategy.METRICS_BASED,
weights: {
successRate: 0.6, // Prioritize reliability
latency: 0.3, // Then speed
cost: 0.1, // Then cost
},
});
// Automatically selects best gateway based on live metrics
const gateway = await router.selectGateway(payment);
Routing Strategies:
- Metrics-Based: Real-time gateway health scoring
- Cost-Optimized: Minimize transaction fees
- Latency-Optimized: Fastest gateway selection
- Round-Robin: Equal distribution
- Weighted: Custom distribution ratios
- Geographic: Route by customer location
- A/B Testing: Experiment with gateway configurations
Use Case: Automatic failover to healthy gateways, cost optimization, geographic compliance.
7. Adaptive Circuit Breakers
Prevent cascading failures with automatic failure detection:
const circuitBreaker = new CircuitBreaker({
failureThreshold: 5, // Open after 5 failures
successThreshold: 2, // Close after 2 successes
timeout: 60000, // 60s timeout in OPEN state
halfOpenMaxAttempts: 3, // Test with 3 requests in HALF_OPEN
});
// Automatically prevents calls to failing gateways
const result = await circuitBreaker.execute(() => gateway.charge(payment));
Circuit States:
- CLOSED: Normal operation, all requests pass through
- OPEN: Gateway failing, fast-fail all requests (no wasted time/money)
- HALF_OPEN: Testing recovery, limited traffic allowed
Use Case: Protect against third-party gateway outages, reduce latency during failures.
8. Exponential Backoff with Jitter
Smart retry logic prevents thundering herd:
const retryPolicy = new RetryPolicy({
maxAttempts: 3,
initialDelay: 1000, // 1s
maxDelay: 30000, // 30s
multiplier: 2, // Exponential
jitter: true, // Randomize to prevent thundering herd
retryableErrors: ['NETWORK_ERROR', 'TIMEOUT', 'RATE_LIMIT'],
});
// Retry: 1s → 2s → 4s → 8s (with random jitter)
Use Case: Gracefully handle transient failures without overwhelming gateways.
9. Gateway Health Monitoring
Real-time health scoring drives routing decisions:
const healthMonitor = new GatewayHealthMonitor();
// Health score: 0.0 (dead) to 1.0 (perfect)
const health = healthMonitor.getHealth(GatewayType.STRIPE);
// {
// score: 0.95,
// successRate: 0.98,
// averageLatency: 145ms,
// errorRate: 0.02,
// circuitState: 'CLOSED'
// }
Metrics Tracked:
- Success rate (last 100 transactions)
- Average latency (P50, P95, P99)
- Error rate and error types
- Circuit breaker state
- Request volume and throughput
Use Case: Data-driven routing, proactive failure detection, SLA monitoring.
🔌 Extensibility & Integration
10. Hook System (Plugin Architecture)
Extend behavior without modifying core code:
// Fraud detection hook
class CustomFraudCheck implements FraudCheckHook {
async execute(context: HookContext) {
const riskScore = await fraudAPI.score(context.payment);
return {
allowed: riskScore < 0.8,
riskScore,
reason: 'Fraud detection analysis',
};
}
}
registry.registerFraudCheck(new CustomFraudCheck());
Hook Types:
- Pre-Validation Hooks: Input validation, business rules
- Fraud Check Hooks: Custom fraud detection, risk scoring
- Routing Strategy Hooks: Custom gateway selection logic
- Event Listener Hooks: React to payment events (notifications, webhooks)
- Lifecycle Hooks: Before/after operations for logging, metrics
Use Case: Integrate third-party services, implement custom business logic, A/B testing.
11. Multi-Gateway Support
Pluggable gateway adapters with unified interface:
// Register multiple gateways
registry.register(GatewayType.STRIPE, new StripeAdapter());
registry.register(GatewayType.RAZORPAY, new RazorpayAdapter());
registry.register(GatewayType.PAYPAL, new PayPalAdapter());
// Switch gateways without code changes
const payment = await service.processPayment({
amount: new Money(100, Currency.USD),
gatewayType: GatewayType.STRIPE, // or RAZORPAY, PAYPAL, etc.
});
Built-in Adapters
