Engineering PayArk: Building High-Integrity Payment Rails at the Edge
1. The "Pain" of Financial Integration in Nepal
Digital payment integration in Nepal has historically been an exercise in technical debt. Developers integrating legacy providers like eSewa and Khalti frequently find themselves mired in messy XML/form logic and manual verification flows. These systems often function as bespoke wrappers rather than unified services, forcing engineers to write fragmented verify logic for every individual carrier.
PayArk was built to solve the integration headache by providing a single, high-integrity API layer that abstracts this complexity into a deterministic, developer-first experience. We identified three primary friction points currently stifling innovation in the region:
- Documentation Fragmentation, Outdated integration guides and non-standardized API behaviors lead to inconsistent production environments.
- Lack of Type Safety, Relying on unstructured data and manual form-handling introduces runtime failures that are nearly impossible to debug at scale.
- Inconsistent Callback Mechanisms, Variations in how transactional responses are handled create a state of "try/catch hell," threatening the transactional integrity required for serious financial systems.
2. The Hyper-Scale Edge Mesh: Cloudflare, Hono, and Bun
To achieve the performance required for modern commerce, PayArk utilizes an Edge Gateway architecture. By moving logic to the global perimeter, we achieve sub-10ms latency, ensuring that orchestration occurs as close to the user and the financial provider as possible.
Core Infrastructure Stack
| Layer | Technology | Purpose | | -- |, | --- | | Edge Execution | Cloudflare Workers | Global execution layer for low-latency routing and session management | | API Framework | Hono | High-performance middleware and request routing at the edge | | Runtime & Tooling | Bun | Fast development runtime and automated CI/CD security gates | | Realtime Hub | Durable Objects | State management and WebSocket coordination for live event streams |
Every successful response is wrapped in a standardized envelope providing a trace_id and timestamp. To ensure industrial reliability, we implement RFC 7807 for machine-readable error specifications. Our gateway returns specific error types, such as validation-error, unauthorized, rls-violation, and rate-limited, to allow both human developers and AI agents to handle failures with precision.
3. The Industrial Specification: Functional Orchestration via Effect-TS
Internal orchestration at PayArk is governed by Effect-TS. This transition from "try/catch hell" to functional orchestration treats failures as first-class citizens, providing three core benefits:
- Unified Error Handling, Every failure is a strongly-typed value, eliminating ambiguous catch-all exceptions.
- Micro-Retries with Idempotency, We utilize an
Idempotency-Keyheader on all mutating requests. This ensures that even during jittered retries, payments are never accidentally duplicated. - Traceability, Every
Effectis tagged with a uniqueTrace-ID, providing 100% observability from the edge gateway through to the transaction layer.
To prevent Thundering Herd scenarios where simultaneous retries DDoS a carrier's API, we implement a jittered exponential backoff strategy:
const retrySchedule = Schedule.exponential(100, 2).pipe(
Schedule.jittered,
Schedule.compose(Schedule.recurs(5)),
);
4. Zero-Trust Security: Defense-in-Depth at the Application Layer
PayArk operates on a Defense-in-Depth principle, securing the application layer with the same rigor as the network perimeter.
- App-Layer Encryption (ALE), Sensitive provider secrets are never stored in cleartext. They are sealed via
AES-256-GCMbefore database insertion. The Master Pepper key is isolated as a Cloudflare Worker Secret, ensuring it is never exposed in the database or source control. - Postgres Row-Level Security (RLS), We enforce strict multi-tenant isolation at the database level. Every query automatically verifies the
project_idagainst the authenticated user's scope. - Audit Logs, All platform activity is logged to Supabase, providing a persistent, observable integrity trail.
- SSRF Egress Validation, Merchant-defined
return_urlvalues are resolved through a strict allow-list and checked against RFC 1918 private IP ranges before any outbound connection is established.
5. NRB-Compliant Push-Based Subscriptions
In Nepal, regulatory directives from the Nepal Rastra Bank (NRB) restrict automated "Pull" deductions for local wallets. PayArk solves this for the SaaS ecosystem through a Push-Based Subscription model.
Subscription Lifecycle
- Customer Initiation, Customers explicitly authorize each period's payment via a hosted portal.
- Edge Cron Orchestration, Our engine generates renewal reminders and manages status transitions across tiers:
active,past_due, andcanceled. - Permanent Links, Every subscription includes a permanent hosted link (
payark.io/sub/:id) where users can self-serve renewals at any time.
From this stream, we derive precise enterprise analytics. MRR is calculated as the sum of all active subscription amounts normalized to 30 days, while ARR and churn rates are generated directly from the Postgres transaction stream.
6. AI-Native Developer Experience & The Model Context Protocol (MCP)
PayArk is built for engineers who value a high-end IDE experience. We have eliminated the Webhook Tunneling Tax by utilizing Cloudflare Durable Objects to map edge event streams directly to a developer's local endpoint.
The PayArk CLI and the payark listen command forward live webhooks to your local machine with sub-10ms latency, eliminating the need for external tools like ngrok.
We are also the first platform in the region to support the Model Context Protocol (MCP), allowing AI agents like Claude or Cursor to interact directly with your infrastructure via tools like:
list_projects, Identify project scopes and IDs.list_payments/get_payment, Analyze transaction states and failure reasons.create_payment_link, Generate checkout URLs via natural language.
Our Zero-Dependency SDK is isomorphic and tree-shakeable, built to run flawlessly across Node 18+, Bun, and Deno.
7. Heuristic Resilience: Solving the "Double-Question-Mark" Bug
A prime example of our Resilient Orchestration is how we handle carrier-side protocol violations. The eSewa callback mechanism frequently appends ?data=PAYLOAD to merchant return URLs without checking for existing query parameters. This creates malformed URIs (e.g., ?payment_id=abc?data=xyz) that violate RFC 3986 and break standard database lookups.
We implemented a defensive sniffer in the Edge Gateway to normalize these violations before they reach the business logic:
// Detect and correct eSewa's URI violation (RFC 3986)
if (!dataParam && payment_id?.includes("?data=")) {
const [cleanId, cleanData] = payment_id.split("?data=");
payment_id = cleanId;
dataParam = cleanData;
}
8. Conclusion: The Future of Fintech in Nepal
The PayArk mission is to move financial infrastructure in Nepal away from legacy integration headaches and toward a system that feels like high-end AI-native infrastructure, transparent, predictable, and resilient. By bridging the gap between fragmented local systems and modern edge-native standards, we are providing the high-integrity rails required for the next generation of SaaS in the region.
PayArk is built for engineers, by engineers, because the future of money depends on systems that just work.
Links:
- Site: payark-public-demo.vercel.app
- GitHub: github.com/Payark-Inc