FORTILABS BUILD LAB
A practical architecture comparison of edge request processing, JWT verification, distributed rate limiting, regional routing, runtime constraints, and network costs.
Cloudflare Workers is the stronger fit when API decisions should execute close to users across a globally distributed edge network. Fly.io is compelling when you need regional application compute, control over the gateway runtime, or software that depends on a conventional Linux environment. They solve overlapping but different infrastructure problems, and a hybrid architecture can be more effective than choosing only one.
1. What an edge API gateway actually does
An API gateway sits between clients and application services. It can authenticate requests, enforce traffic policies, normalize headers, route requests, reject invalid traffic, and forward permitted requests to an origin.
An edge API gateway moves some or all of this work closer to the client instead of requiring every request to reach a central application server first.
This matters because a request that travels to a distant origin just to fail authentication or exceed a rate limit consumes network capacity and application resources unnecessarily. Rejecting it earlier can reduce origin traffic and improve the response path for valid requests.
Traditional centralized API request path
Authentication, policy checks, and routing occur after the request reaches the centralized gateway.
Edge-first API request path
The gateway can reject invalid requests before forwarding them to application infrastructure.
The edge does not automatically make every request faster. If the gateway must contact a distant database, centralized rate limiter, or origin for every decision, those network round trips can offset the benefit of running code near the client.
2. How Cloudflare Workers and Fly.io differ architecturally
The fundamental distinction is the execution model. Cloudflare Workers runs JavaScript and WebAssembly in isolated V8-based execution environments distributed across Cloudflare’s network. Fly.io provides application compute through lightweight virtual machines called Machines, with Fly Proxy handling ingress and routing traffic to them.
Cloudflare Workers: execute gateway logic at the edge
A Worker can inspect an incoming request, verify a token, apply request-specific rules, modify headers, and forward the request using the Fetch API. The code executes within Cloudflare’s distributed infrastructure rather than requiring a conventional application server to run at every edge location.
This model is particularly useful for relatively short request-processing tasks: authentication, lightweight transformations, routing decisions, caching logic, and early rejection of unwanted traffic.
Cloudflare Workers request architecture
Fly.io: route to application compute near users
Fly Proxy is the global ingress and routing layer. It handles responsibilities such as TLS termination and selecting suitable Machines. Applications can be deployed in multiple Fly regions so requests can reach compute closer to their users.
However, Fly Proxy should not be confused with a programmable application gateway. If you want custom JWT verification, tenant policies, request rewriting, or application-specific rate limiting, you implement that logic in your own service running on a Fly Machine.
Fly.io gateway architecture
Architecture comparison
| Dimension | Cloudflare Workers | Fly.io |
|---|---|---|
| Primary execution | V8 isolates running Worker code | Applications running inside Machines |
| Global ingress | Cloudflare edge network | Fly Proxy |
| Custom gateway logic | Runs directly in the Worker | Runs in an application deployed on a Machine |
| Runtime control | Managed JavaScript/Wasm environment | Linux-based application environment |
| Compute placement | Distributed edge execution | Selected deployment regions |
| Persistent coordination | Durable Objects and other storage services | Application-managed databases, caches, and services |
| Best fit | Lightweight globally distributed request processing | Regional services and custom application compute |
3. Request modification and routing
Both platforms can participate in request routing, but the amount of control and where the logic executes are different.
Request processing in Cloudflare Workers
Workers can use standard Request and Response APIs to inspect and transform traffic. A gateway can normalize headers, remove untrusted client-supplied identity headers, enforce allowed methods, validate request paths, and select an upstream service.
For example, the following simplified Worker forwards a request to an origin after removing a header that must never be trusted when supplied by an external client.
export default {
async fetch(request, env) {
const incoming = new URL(request.url);
// Route only to an origin controlled by your application.
const upstream = new URL(incoming.pathname + incoming.search,
env.API_ORIGIN);
const headers = new Headers(request.headers);
// Never trust client-supplied internal identity headers.
headers.delete("X-Authenticated-User");
headers.delete("X-Internal-Role");
const forwardedRequest = new Request(upstream, {
method: request.method,
headers,
body: ["GET", "HEAD"].includes(request.method)
? undefined
: request.body,
redirect: "manual"
});
return fetch(forwardedRequest);
}
};
This is an illustrative transformation, not a complete production gateway. A real implementation must also validate the incoming host, restrict upstream destinations, handle request-size limits, define timeout behavior, and ensure that the origin accepts traffic only through trusted paths.
Request processing with Fly.io
On Fly.io, the custom gateway can run as an ordinary application service. This gives you access to the libraries, networking behavior, and runtime environment supported by your chosen application stack.
Fly.io also provides fly-replay for supported dynamic
routing patterns. It can be useful when an application needs to replay
a request to another application or Machine, subject to its networking
scope and configuration. It is not a replacement for an application
gateway or a general-purpose global routing policy engine.
Fly Proxy chooses and routes to application compute. Your own gateway decides whether a request is authorized, which tenant it belongs to, what headers should be changed, and which application service should receive it.
4. JWT validation before origin access
JWT verification is one of the strongest reasons to introduce an edge gateway. A properly implemented gateway can reject invalid or expired tokens before the request reaches protected application services.
The gateway should verify more than the token’s signature. It should validate the expected issuer, audience, expiration, not-before claim where applicable, and the permitted signing algorithm. The application must also apply authorization rules: a valid token does not automatically mean that its owner can access every resource.
Cloudflare Workers JWT verification
Workers supports the Web Crypto API, which can perform cryptographic verification without relying on a traditional Node.js server runtime. For production systems using a signing provider, a standard JWT library with JWKS support is generally preferable to manually parsing and verifying tokens.
import { jwtVerify, createRemoteJWKSet } from "jose";
const JWKS = createRemoteJWKSet(
new URL("https://identity.example.com/.well-known/jwks.json")
);
export async function authenticate(request: Request) {
const authorization = request.headers.get("Authorization");
if (!authorization?.startsWith("Bearer ")) {
return null;
}
const token = authorization.slice(7);
try {
const { payload } = await jwtVerify(token, JWKS, {
issuer: "https://identity.example.com/",
audience: "my-api",
algorithms: ["RS256"]
});
if (typeof payload.sub !== "string") {
return null;
}
return {
subject: payload.sub,
tenantId: payload.tenant_id
};
} catch {
return null;
}
}
The example uses a remote JSON Web Key Set and an explicit algorithm allowlist. In a real deployment, the issuer, audience, algorithm, identity claims, and key-rotation behavior must match the identity provider’s configuration. Do not accept an arbitrary key URL supplied by a token or request parameter.
JWT verification in a Fly.io gateway
A custom gateway on Fly.io can use the same JWT validation approach through a library supported by its runtime. The difference is not the cryptographic standard; it is where the gateway executes and how requests reach it.
If the gateway and application API are separate services, the gateway can verify the token before forwarding to the internal API. Keep the internal service private where practical, and do not rely on a client-controlled header as proof of authentication.
Security requirements for either platform
- Allow only explicitly configured signing algorithms.
- Validate issuer, audience, expiry, and required claims.
- Support signing-key rotation and safe JWKS refresh behavior.
- Never log complete bearer tokens or sensitive claims.
- Strip externally supplied internal identity headers.
- Prevent direct origin access from bypassing the gateway.
- Keep authorization checks close to the resource being protected.
JWT validation at the edge reduces unnecessary origin work, but it does not eliminate the need for application-level authorization. The application should still verify that the authenticated subject is permitted to perform the requested operation.
5. Distributed rate limiting: local counters versus shared state
Rate limiting sounds straightforward until requests arrive from multiple locations at the same time. A limit of 100 requests per minute for a customer is not necessarily enforced globally just because every edge location has a counter.
Cloudflare Workers Rate Limiting API
Cloudflare provides a Rate Limiting API that can be called from Worker code. It is designed for fast decisions using locally cached counters. The important limitation is that the counters are approximate and apply separately in each Cloudflare location. Updates synchronize in the background, so requests can exceed the configured threshold.
This is useful for abuse mitigation, protecting expensive endpoints, and applying approximate per-user or per-route policies. It should not be treated as a strict worldwide quota or an exact billing meter.
When a strict global limit is required
Cloudflare Durable Objects provide a coordination primitive for stateful workloads. A common design is to assign a stable object identity to each customer or API credential. Requests for that identity are coordinated through the same object, which can serialize updates to the relevant counter.
This gives you a stronger basis for enforcing a shared quota than independent per-location counters. It also introduces a coordination path, so the design must account for the additional network hop, object throughput, storage, and failure behavior.
Rate limiting on Fly.io
Fly Proxy does not automatically provide application-specific, globally consistent user quotas. A gateway running on a Fly Machine needs a state strategy of its own.
Common options include:
- Local in-memory counters: fast, but isolated to a particular Machine. They do not create a reliable global quota across multiple Machines.
- Shared Redis-compatible storage: useful for centralized counters and atomic operations, but network latency and availability depend on where the store is deployed.
- Database-backed coordination: appropriate when durable accounting is important, although database transactions should not be added to every high-volume request without measuring their cost.
- Regional or tenant-sharded limits: can reduce cross-region coordination, but the quota semantics must explicitly account for traffic arriving in multiple regions.
| Requirement | Cloudflare Workers | Fly.io |
|---|---|---|
| Fast approximate checks | Built-in Rate Limiting API | Application-managed local counters or shared store |
| Strict shared quota | Durable Objects coordination | Shared atomic state or a dedicated coordination service |
| Per-user or tenant keys | Supported through application-defined keys | Implemented in gateway logic |
| Cross-region consistency | Requires coordinated state, not local counters alone | Depends on the selected shared-state architecture |
| Operational responsibility | Cloudflare manages the platform primitives | Your team manages the chosen state service and policies |
A rate limiter should be paired with authentication, sensible request
size limits, upstream timeouts, and abuse monitoring. For an external
API quota, also handle upstream HTTP 429 responses and any
Retry-After instructions.
6. Global latency and regional placement
Cloudflare Workers and Fly.io approach global request placement differently. Workers execute across Cloudflare’s distributed edge network. Fly.io lets you deploy application Machines in selected regions, with Fly Proxy routing traffic to suitable Machines.
The practical latency question is not simply which provider has more locations. It is where the work happens, where the data lives, and how many network round trips are required before a response can be returned.
Cloudflare: edge execution close to the request
A lightweight Worker can often complete authentication, header transformation, and routing decisions without first contacting a centralized application gateway. This can shorten the control path for requests that can be handled locally.
However, if every request must contact a distant origin or a centralized database, the origin round trip still dominates the end-to-end latency. A globally distributed Worker does not make a single-region database globally distributed.
Fly.io: regional application compute
Fly.io is attractive when the application itself should run in multiple regions. You can place Machines near important user populations and route traffic to them through Fly Proxy.
This is useful when the gateway needs native application libraries, persistent connections, larger memory allocations, or direct access to regional services. The trade-off is that you must decide which regions to deploy, how much capacity to keep available, and how application state is shared.
What actually determines latency?
- Distance between the client and the gateway execution point.
- Distance between the gateway and the application origin.
- Whether JWT keys or rate-limit state require remote lookups.
- Database location and cross-region replication behavior.
- Connection reuse, TLS setup, and upstream connection pooling.
- Machine startup, queueing, CPU contention, and application work.
Measure client-to-gateway time, gateway processing time, gateway-to-origin time, and total response time separately. Provider location counts alone are not a meaningful substitute for workload-specific latency measurements.
7. Cold starts and runtime behavior
Cold starts matter when a request must wait for an execution environment to become available. The two platforms have different startup models, so comparing them using a single generic cold-start number would be misleading.
Cloudflare Workers isolates
Workers uses lightweight V8 isolates rather than requiring a separate conventional virtual machine to boot for every request. This is a different startup model from a stopped application Machine.
Cloudflare documents a one-second Worker startup-time limit. This is the time allowed for the script’s global scope to parse and execute; it is not a promise that every request has a one-second cold start or a measurement of end-to-end request latency.
Large bundles and expensive top-level initialization can still affect startup behavior. Keep global initialization lightweight, avoid unnecessary dependencies, and measure real deployments.
Fly.io Machines
Fly Machines run application processes in lightweight virtual-machine environments. A continuously running Machine avoids the startup delay associated with waking a stopped instance, but you pay for its running compute time.
Autostop and autostart can reduce idle compute costs. The trade-off is that a request may need to wait for a Machine to resume or start when capacity is not already running. Suspended Machines and stopped Machines have different resume behavior; neither should be assumed to have identical startup latency.
| Factor | Cloudflare Workers | Fly.io Machines |
|---|---|---|
| Execution environment | V8 isolate | Lightweight virtual machine |
| Startup characteristics | Isolate startup and script initialization | Machine start or resume plus application startup |
| Always-on capacity | Managed by the platform | Can be maintained by keeping Machines running |
| Idle-cost trade-off | Usage-based Worker billing | Stopped or suspended Machines can reduce compute usage |
| Main optimization | Small bundles and inexpensive initialization | Warm capacity, sensible autostop policy, and fast application boot |
8. Memory and execution constraints
Runtime limits are especially important for gateways that parse large payloads, process uploads, perform cryptographic operations, or load substantial dependency trees.
Cloudflare Workers memory model
Cloudflare documents a 128 MB memory limit per isolate. That is a meaningful constraint for workloads that buffer large request bodies, build large in-memory objects, or process files entirely in memory.
Workers is well suited to lightweight request processing, but it is not a drop-in replacement for a large, memory-intensive application server. Use streaming APIs where possible, avoid buffering entire payloads unnecessarily, and keep the dependency footprint controlled.
CPU time is also a separate consideration. Network waiting does not count as CPU execution time, but CPU-heavy code does. The paid plan supports configurable CPU limits, subject to the documented maximum.
Fly.io Machine resources
Fly.io provides selectable Machine sizes with different CPU and memory allocations. Its published shared-cpu presets include configurations starting at 256 MB and extending to larger memory sizes. Larger performance-class Machines are also available.
This gives application teams more direct control over the compute environment. It is useful for gateways that need native dependencies, larger in-memory caches, connection pools, or processing that does not fit comfortably inside a constrained isolate.
| Constraint | Cloudflare Workers | Fly.io |
|---|---|---|
| Memory | 128 MB per isolate | Selectable Machine memory configurations |
| Runtime | JavaScript and WebAssembly with supported runtime APIs | Linux application environment |
| Large payload handling | Prefer streaming; avoid unnecessary buffering | More configurable memory, subject to Machine size |
| Native dependencies | Limited to supported runtime and compatible modules | Broader Linux compatibility |
| Scaling responsibility | Managed execution platform | Machine sizing, deployment, and capacity planning |
More memory does not automatically mean better performance. A gateway should still avoid unnecessary payload buffering, oversized caches, unbounded concurrency, and expensive synchronous work.
9. Bandwidth and infrastructure economics
The cost model is not simply Workers versus Machines. You need to account for request volume, CPU execution, compute uptime, memory, storage, public egress, cross-region traffic, and any shared-state service used by the gateway.
Cloudflare Workers pricing
Under the published Standard Workers Paid usage model, the account has a $5 monthly minimum. The included monthly allowance is 10 million requests and 30 million CPU milliseconds. Additional requests are billed at $0.30 per million, and additional CPU time at $0.02 per million CPU milliseconds.
Cloudflare states that Workers Paid does not add separate charges for data transfer egress or throughput. This can be attractive for bandwidth-heavy request paths, although other services involved in the architecture may have their own charges.
Fly.io compute and egress pricing
Fly Machines are billed according to the selected compute resources and how long Machines run. Storage and outbound data transfer are separate cost categories.
The published pricing effective October 1, 2026 lists public Internet egress rates by region group:
| Region group | Public Internet egress | Illustrative cost for 1,000 GB |
|---|---|---|
| North America and Europe | $0.02 / GB | $20 |
| Asia Pacific, Oceania, and South America | $0.04 / GB | $40 |
| Africa and India | $0.12 / GB | $120 |
These examples are simple multiplication of the published per-GB rates. They are not complete monthly bills and exclude compute, storage, taxes, discounts, and any other applicable charges.
Fly.io also documents separate rates for qualifying private cross-region data transfer under its granular bandwidth pricing model. Public Internet egress and private inter-region traffic should therefore be modeled separately rather than treated as one universal bandwidth rate.
Why the gateway’s position matters economically
A gateway that rejects invalid requests before they reach the origin can reduce downstream compute and database work. But if it forwards every valid response through another service, the additional network path and data transfer still need to be included in the cost model.
A useful estimate should include:
- Monthly inbound request volume and average request size.
- Average response size and percentage of requests served from cache.
- Worker request and CPU usage, or Machine runtime and memory.
- Public egress by destination region.
- Private cross-region transfer where applicable.
- Rate-limit storage and coordination requests.
- Origin compute saved by early authentication and rejection.
Do not compare a Cloudflare request bill with a Fly Machine compute bill alone. Compare the total cost of serving the same traffic, including compute, egress, storage, coordination, and origin infrastructure.
10. Which architecture should you choose?
Choose Cloudflare Workers when:
- You need lightweight API logic close to globally distributed users.
- You want to reject unauthorized traffic before reaching the origin.
- Your gateway primarily performs authentication, routing, and transformations.
- You want managed edge execution instead of operating regional gateway Machines.
- You can work within the isolate runtime and its memory constraints.
- Your rate-limit requirements can use approximate local counters or coordinated Durable Objects.
Choose Fly.io when:
- Your gateway needs a conventional Linux application environment.
- You need selectable CPU and memory configurations.
- Your application already runs on Fly.io or benefits from regional Machines.
- You need native dependencies, persistent processes, or application-specific networking.
- You want control over regional compute placement and Machine lifecycle.
- Your team is prepared to operate shared rate-limit state and regional capacity.
Consider a hybrid architecture
The platforms do not have to be mutually exclusive. A Cloudflare Worker can perform lightweight authentication, filtering, and request normalization before forwarding permitted traffic to regional application services hosted on Fly.io.
Hybrid edge-to-regional architecture
This design separates global request policy from regional application execution. It also adds a provider-to-provider network path, which must be measured and secured.
A hybrid design is not automatically faster or cheaper. It adds another layer, another configuration surface, and potentially additional network transfer. Use it when the separation of responsibilities delivers measurable value.
Final decision matrix
| Use case | Stronger starting point | Reason |
|---|---|---|
| Global lightweight authentication | Cloudflare Workers | Edge execution can reject invalid requests before origin access. |
| Regional API application | Fly.io | Machines provide configurable regional application compute. |
| Approximate edge rate limiting | Cloudflare Workers | Built-in location-specific Rate Limiting API. |
| Custom strict quota coordination | Depends on state design | Durable Objects or a suitable shared coordination service. |
| Linux-native gateway dependencies | Fly.io | Conventional application runtime and configurable Machines. |
| Low-cost high-egress gateway | Workload-dependent | Compare total compute, request, egress, and origin costs. |
| Global edge plus regional compute | Hybrid | Separates edge policy from application execution. |
11. Production implementation checklist
Before deploying either architecture, validate the full request path rather than testing only the gateway function.
Security
- Validate JWT signature, issuer, audience, expiry, and required claims.
- Restrict accepted signing algorithms and support key rotation.
- Strip untrusted identity and internal routing headers.
- Restrict upstream destinations to prevent SSRF-style routing abuse.
- Protect the origin against direct access that bypasses gateway policies.
- Apply authorization checks at the resource or service boundary.
Rate limiting and reliability
- Define whether limits are approximate, regional, or globally strict.
- Choose stable keys such as authenticated user, tenant, or API credential.
- Use atomic updates when strict quotas are required.
- Define behavior when the limiter or shared store is unavailable.
- Handle upstream 429 responses and retry instructions.
- Set explicit upstream timeouts and concurrency limits.
Performance and observability
- Measure gateway processing time separately from origin latency.
- Track cold-start or resume delays where applicable.
- Monitor memory use, CPU time, and request-size distributions.
- Track rejected requests, authentication failures, and rate-limit events.
- Measure public egress and cross-region transfer.
- Test regional failures and upstream unavailability.
A gateway is a security and reliability boundary. Its success should be measured not only by average response time, but also by whether it prevents unauthorized work, protects upstream capacity, and behaves predictably when dependencies fail.
12. Frequently asked questions
Are Cloudflare Workers faster than Fly.io?
Neither is universally faster. Workers can execute lightweight request logic close to users, while Fly.io can place application Machines in selected regions. The result depends on origin placement, shared-state lookups, runtime startup, and the complete network path.
Can Cloudflare Workers validate JWTs before requests reach my origin?
Yes. A Worker can verify JWT signatures and claims before forwarding a permitted request. The origin should still enforce appropriate authorization and should not trust client-supplied identity headers.
Does Fly Proxy validate JWT tokens automatically?
Fly Proxy provides ingress and routing capabilities. Custom JWT validation belongs in an application gateway or service that you deploy on Fly Machines.
Is Cloudflare Workers rate limiting globally consistent?
The built-in Workers Rate Limiting API uses approximate, location-specific counters. It is not a strict worldwide quota. Durable Objects can provide coordinated state when strict shared limits are required.
Can Fly.io run an API gateway in multiple regions?
Yes. You can deploy Machines in multiple regions and use Fly Proxy to route traffic to suitable application instances. Your gateway still needs a deliberate strategy for shared state, quotas, and cross-region consistency.
Do Cloudflare Workers have a 128 MB memory limit?
Cloudflare documents a 128 MB memory limit per isolate. This makes streaming and avoiding unnecessary request or response buffering important for memory-intensive gateway workloads.
Does Fly.io charge for bandwidth?
Fly.io publishes regional rates for outbound Internet data transfer and separate rates for qualifying private cross-region traffic. Inbound transfer and some same-region traffic have different billing treatment. Check the current pricing rules for your organization.
Can Cloudflare Workers and Fly.io be used together?
Yes. A Worker can handle edge authentication and request filtering, then forward permitted traffic to Fly.io application Machines. This can combine global edge processing with regional compute, although the additional network path must be measured.
Official documentation and further reading
- Cloudflare Workers documentation
- Cloudflare Workers limits
- Cloudflare Workers Rate Limiting API
- Cloudflare Durable Objects
- Cloudflare Workers Web Crypto API
- Cloudflare Workers pricing
- Fly.io networking and Fly Proxy
- Fly.io dynamic request routing
- Fly.io Machines documentation
- Fly.io resource pricing and bandwidth
- Fly.io pricing update effective October 1, 2026
Pricing reference date: November 11, 2026. Provider pricing, limits, and product behavior can change; verify current documentation before making purchasing or deployment decisions.