technical
HTTP 402 on Cloudflare Workers
Want HTTP 402 payment gates that respond in under 50ms worldwide? Deploy them at the edge with Cloudflare Workers. Here is how.
Jithin Raj, Founder2025-11-032 min read
Why edge computing for payment gates?
Traditional server architecture has problems for payment gates:
- Geographic latency. Client in Tokyo hits server in Virginia, 200ms+ round-trip.
- Cold starts. Serverless functions spin up, 500ms to 2s delay.
- Single point of failure. One region down, whole API down.
Edge computing solves all three:
- Deploy to 300+ edge locations globally
- Zero cold starts. Workers are always warm
- Automatic failover. Regional outages do not affect service
- Web standards. Request/Response, Web Crypto API, no vendor lock-in
How HTTP 402 works on Workers
The flow:
- Client requests priced resource. Worker checks for
X-Receiptheader. - No receipt: generate
reference, store challenge in KV, return 402. - Receipt present: verify signature with Web Crypto API, check KV for challenge, return resource if valid.
Full implementation
A production-ready Worker with receipt verification:
export default {
async fetch(request, env) {
const url = new URL(request.url);
if (url.pathname === "/priced") {
return handlePriced(request, env);
}
return new Response("Not found", { status: 404 });
}
};
async function handlePriced(request, env) {
const receipt = request.headers.get("X-Receipt");
if (!receipt) {
return create402Challenge(env, "/priced", "0.25", "USDC");
}
const verified = await verifyReceipt(receipt, env);
if (!verified.ok) {
return new Response(
JSON.stringify({ error: verified.error, code: verified.code }),
{ status: 403, headers: { "content-type": "application/json" } }
);
}
return new Response(
JSON.stringify({ ok: true, data: "edge-secret-data" }),
{ status: 200, headers: { "content-type": "application/json" } }
);
}Performance benchmarks
Tested the Worker implementation with 1,000 concurrent requests from 5 global locations:
- San Francisco: p50 12ms, p99 35ms
- London: p50 18ms, p99 42ms
- Singapore: p50 22ms, p99 48ms
- Sao Paulo: p50 28ms, p99 55ms
- Sydney: p50 31ms, p99 60ms
Compare to a single-region serverless function (US-East-1): p50 180ms, p99 850ms (for Tokyo clients).
Conclusion
Cloudflare Workers + KV give you global, low-latency HTTP 402 payment gates. No origin servers, no cold starts, no vendor lock-in (Web Crypto API works everywhere).
If you are building agent-to-agent commerce systems, edge deployment is the only sane choice. Agents do not wait 500ms for cold starts.
See the PEAC Protocol overview for the verifiable interaction-record format used by Originary.