Essay

I load tested my LLM gateway with a fake LLM, and D1 was the limit

A staging environment, a mock provider and 235,000 requests from a home PC. Four scenarios passed with zero lost usage. The ramp found a wall at 180 requests a second, and the cause was the one component I had stopped worrying about.

OpenPike is a bring-your-own-key LLM gateway on Cloudflare Workers. A request comes in with an OpenPike virtual key, gets authenticated, checked against budgets, sent to the customer’s own provider key, streamed back, and logged for spend reporting.

Not long ago I moved the usage log out of D1 and into Durable Objects, because D1 was going to fill up. That change made a prediction: the limit on one organization would now be a Durable Object, not the database. I had a cost estimate too, about $5 per million requests, built from published prices and arithmetic. Neither was measured.

So I wrote a load test: a brief as a GitHub issue, a coding agent to build the harness, and me to run it against my own Cloudflare account. This post covers how it was built, what it found, and how I found out why. The short version: four scenarios passed with zero lost usage, one found a wall at about 180 requests a second, and one I chose not to run. The cause of the wall was D1, and the Durable Objects I’d been worried about never failed.

The request path

Everything below depends on this, so here it is:

client
  -> Worker (Hono)
       auth     hash the virtual key, look it up            D1 read
       key      load the provider key, decrypt in memory    D1 read
       gate     WorkspaceGate (one per workspace)           DO call: admit
       route    pick provider and model
       connect  open the upstream request
       stream   pass the response through, no buffering
       record   WorkspaceGate: add spend                    DO call: record
       usage    UsageLog (one per org per month)            DO call: append

Each response carries a Server-Timing header with the time spent in each step. That header turned out to matter more than any dashboard.

The harness

I don’t want to point a load test at a real provider. It costs money, and the provider’s latency would drown the number I care about: what the gateway itself adds. So the first piece was a fake provider.

The mock provider is a separate Worker that speaks OpenAI chat completions, streaming and not, with a realistic usage block. Its behavior is set through the model name:

mock/mock-chat?ttft=300&tps=50&out=200&err429=0.1&err500=0.1

That’s time to first token, tokens a second, output length, and the chance of a 429 or 500. The same settings work as x-mock-* headers.

Staging is a second set of everything: its own Workers, D1 database, R2 bucket, Durable Object namespaces and rate-limit namespaces, all on workers.dev, with no cron trigger and no production route. A staging bug can’t answer on the production hostname.

The Worker-to-Worker call is the part I expected to break. A Worker that fetches another Worker on the same account through its workers.dev address gets Cloudflare error 1042. So the gateway reaches the mock through a service binding, which has the side benefit that production has no binding at all. It worked on the first request. The error I’d planned for never appeared.

The seed creates 221 organizations: 200 regular ones (70% Team, 20% Business, 10% Free), one hot organization for a single-tenant ceiling test, and small groups for budgets, loop detection and fallback. Each gets a workspace, a mock provider key, three virtual keys and a budget row. The script refuses to run against any host that isn’t staging.

The load generator is k6 on my Windows PC. Six scenarios, with ramp steps cut from 15 minutes to 2 to keep the request count down:

Scenario Shape Requests
Steady 50 a second for 5 minutes 15,000
Fallback 50 a second, 20% 429 or 500 from the mock 15,000
Budget and loop crosses soft and hard limits, trips loop detection about 10,000
Long streams 1,000 concurrent 30 second streams 10,000
Ramp 50, 100, 200, 300, 400, 500 a second, 2 minutes each 186,000
Hot organization 100 to 600 a second on one organization 156,000

How to count what you lost

A load test that only reports latency can pass while losing data. The part of this gateway that matters most is that every request leaves a usage row, because that row is the customer’s bill. So each run reports:

  • Requests sent by k6, against usage rows recorded in the UsageLog objects for the run’s time window. The difference is lost usage.
  • Gate counters snapshotted before and after: how many requests the WorkspaceGate admitted. Rows minus admitted is the number of requests the gate didn’t count.
  • Overhead per step from the Server-Timing header, recorded by k6 as trends.

What it costs

A load test against metered infrastructure should have a budget before the first request. The plan was about 400,000 requests in total, expected to land well inside the included amounts of the Workers Paid plan. I wrote down the expected Worker requests, Durable Object requests and rows written for each run, ordered the runs cheapest first, and read the real numbers from the dashboard afterwards.

Four scenarios that passed

Steady, 50 a second

14,980 requests sent, 14,980 usage rows, zero lost, all 200. (k6 dropped 21 iterations on its own side; the gateway never saw them.) Gateway overhead was 77 ms at p50, 107 at p95, 140 at p99. That’s the baseline for everything else.

Fallback

Half the traffic uses a key with two targets where the second is healthy, so a failure on the first recovers. The other half uses a key with two failing targets. Each target fails 20% of the time (10% 429 and 10% 500), so both failing is 4% of that half, which is 2% of all requests, about 300 of 15,000.

301 failed: 143 429s and 158 500s, all coded upstream_error. Every request with a healthy second target recovered. I like this kind of check, because the expected number comes from arithmetic and not from the first run.

Budget and loop

Five organizations each had a $0.10 hard limit and the test sent traffic until they hit it. Each request cost 450 micro-dollars, so the limit is first crossed on request 223 (222 requests is $0.0999, 223 is $0.1004). Four organizations were blocked after 223 or 224 served requests, and one after 225: two requests were already in flight when the limit tripped. The worst spend at the first block was 1.25% over the limit.

Each budget got exactly one soft-limit event and one hard-limit event, even with about 500 blocked requests behind each. Five loop organizations tripped loop detection after 62 to 86 requests, and kept blocking. 4,719 requests were served and 5,183 were blocked with 429, and the gate counters matched: 4,719 admitted.

Long streams

1,000 connections, each held 30 seconds, for 5 minutes. My PC and home connection held all 1,000 with no errors and no interrupted requests, 10,000 rows for 10,000 requests. I’d planned a GitHub Actions fallback in case the PC couldn’t; it wasn’t needed.

One number I can’t explain yet: gateway overhead was 701 ms at p50 and 1,579 ms at p99, nine times the steady baseline, at only about 33 new requests a second. There were no errors, so it isn’t the failure described below. I didn’t sample the per-step timing during that run, so I don’t know which step grew. That’s an open issue.

The ramp, and a 35% loss

The ramp raises the rate every 2 minutes. At the end, the report said:

Requests sent (k6)               184,986
Usage rows recorded              118,868
Lost usage                        66,118  (35.742%)
Rows by status                   200: 105,643   500: 13,225
Gateway overhead p50/p95/p99     101 / 305 / 379 ms

A 35.7% loss of usage rows is the worst thing a billing path can report, and my first reading was a hole in the usage log. The per-step counts in the k6 results file said something different:

Step Planned 200 500
50/s 6,000 5,978 0
100/s 12,000 11,962 0
200/s 24,000 21,006 2,869
300/s 36,000 22,671 13,171
400/s 48,000 22,268 25,452
500/s 60,000 21,758 37,851

Stacked bars of the 200 and 500 responses returned at each ramp step. The 200 bars stop growing at about 22,000 from the 200 a second step onward; the 500 bars take the rest.

The successful count flatlines. From 200 a second onward, the gateway completes about 22,000 requests per 2 minute step, roughly 180 a second, whatever the offered rate. The rest come back 500.

Then the arithmetic. k6 saw 105,643 responses with status 200, and the usage log has exactly 105,643 rows with status 200. Every successful request has a row. k6 saw 79,343 responses with status 500, and the log has 13,225 rows with status 500. The difference is 66,118, the entire reported loss.

The gate counters agreed: 118,868 admitted, equal to the rows. So the failures happened before the gate admitted anything.

Finding the cause

What the step timings said

The Server-Timing data, taken per ramp step, shows which part of the request slowed down.

Line chart of p95 time per step against ramp rate. Gateway overhead climbs from 105 to 376 ms, key lookup from 54 to 231 ms, and auth from 54 to 191 ms. The gate stays flat at about 56 ms.

The gate, a Durable Object call, stays at 56 ms p95 from 100 requests a second to 500. The two lookups that read D1, auth and key, are what grow: key lookup goes from 54 ms to 231 ms at p95. That already pointed away from my prediction. The Durable Objects weren’t struggling. Something else was.

What the dashboards said

Nothing. The Cloudflare Worker page showed 0 errors across the whole run. The D1 pages showed no errors. This is the trap in handled failures: the gateway catches the exception and returns its own 500 with a JSON body, so to Cloudflare it’s a successful invocation. “Errors: 0” is true and useless.

What the logs said

I tailed the staging Worker during a short cut-off ramp. Cloudflare’s tail samples under load, so I got about 8,000 events out of roughly 30,000 requests. In them, 191 responses were 500s, and 191 gateway error log lines. A match, but this was the line:

gateway error request_id=req_... error=Error

The class name and nothing else. That’s deliberate: my rule is that errors never log anything that could carry a key. But Error doesn’t tell you what failed.

The same tail showed two other log lines I hadn’t known to look for: last_used_at write failed and provider status write failed, 163 and 9 of them. Both are D1 writes.

The staging-only debug build

I wanted the message. The rule against logging secrets exists to protect customers’ keys; the thing I was about to log was the message of an exception from a database client, on a staging copy with fake keys, to a local file I’d delete afterward. I decided that was acceptable, got a yes to “as long as it’s on staging”, and did it narrowly:

  1. A throwaway branch from master, never pushed.
  2. One change: the catch block also logs the first 200 characters of err.message.
  3. Deployed with --env staging only. Production untouched.
  4. The same short ramp, tail open.
  5. Revert, delete the branch, redeploy staging from clean master, delete the log file.

The log, 87 gateway errors:

gateway error ... error=Error DIAG=D1_ERROR: D1 DB is overloaded.
  Too many resources consumed within a 10 second window.

All 87 of them. D1 rejects queries when one database is asked for too much work in a 10 second window, and returns an error that the gateway turns into a 500.

Why D1, when the hot path “had no D1 in it”

My architecture doc said a request writes no D1 rows in steady state, and it had a table to back that up. The test contradicts that in two ways.

Every request reads D1 at least twice. Auth looks up the hashed virtual key. The key step loads the provider key. At 180 requests a second that’s at least 360 reads a second against one database, and the reads got slower as the database got busier.

The throttled writes aren’t rare under load. last_used_at and provider status are written at most once a minute per key or provider, tracked in a Map in memory. That’s per isolate. My working theory, which I haven’t measured: at low load there are a few isolates, so the throttle holds, and at 500 requests a second Workers spin up many more, each starting with an empty map and writing on its first request for every key it sees. The throttle is correct and the number of throttles is the problem. What I did measure is the write errors in the tail and the totals below.

The full-window dashboard numbers say the same: 164,830 D1 rows written and 1.59 million read over about 300,000 requests, about 0.55 writes and 5 reads per request, counting the seeding. The documented answer was zero writes.

What it costs, measured

The Cloudflare dashboard gave per-object totals for the whole window (the gateway, the mock, both Durable Object classes, and D1). Dividing by the 230,000 requests that produced a usage row:

Horizontal bars for seven line items, each with a documented and a measured cost per million requests. The Worker CPU, Durable Object duration and D1 writes lines are higher than documented.

Line item Per request Per million Documented
UsageLog rows written 1.0 $1.00 now, $2.00 once retention deletes them $2.00
Gate rows written 1.88 $1.88 $2.00
Durable Object requests 2.96 $0.44 $0.45
Worker requests about 1 $0.30 $0.30
Worker CPU about 7 ms about $0.14 about $0.06
Durable Object duration about 13,000 GB-s per million about $0.16 about $0.01
D1 rows written about 0.55 about $0.55 none

The total is still about $5 per million, as predicted. The mix isn’t what I wrote. Two lines were wrong by more than I’d have guessed.

Durable Object duration was off by 16 times. I assumed “a few milliseconds a call”. Measured wall time is about 37 ms per call on both objects, with CPU time of 0.3 to 0.5 ms. A call spends almost all of its time waiting on storage, and billed duration counts the waiting. It’s still small money: the 400,000 GB-s included cover roughly 30 million requests a month at that rate.

Worker CPU was higher than the 3 ms I’d assumed. The CPU chart shows a p50 of about 7 ms on the gateway. The headline figure on the same page said 2 ms, which can’t be true of the same data, so I used the chart and flagged it. The Billable usage page gives the exact total.

The counts also reconciled, which I find reassuring: 230,000 UsageLog rows written against 231,000 UsageLog requests and about 449,000 gate calls. That’s the count I expected from the design: one append per request, and an admit and a record on the gate.

The whole run, about 300,000 requests, stayed inside every included amount of the plan. Idle staging costs nothing worth mentioning, and I tore it down anyway: both Workers, the D1 database and the R2 bucket, by their exact names, so there was no chance of touching production.

What I didn’t run

The hot organization scenario, 100 to 600 requests a second on a single organization, is meant to find the per-organization Durable Object ceiling. I skipped it. Every request also reads D1 for auth and the key, so it would have hit the 180 a second wall first, and a Durable Object limit sitting above that wall would have stayed invisible. The measurement is only worth taking once the D1 reads are gone. That’s why the follow-up is a rerun.

What I’m changing

Six items, in the order I’d do them.

  1. Stop reading D1 for auth and the key on every request. A short-lived per-isolate cache, or the Workers Cache API. The constraint is revocation: a disabled key has to stop working within a stated delay, so the delay goes in writing and a test holds it.
  2. Move the throttled writes off D1. last_used_at and provider status don’t need D1 on the request path. A flush from a Durable Object, or a much longer interval, makes the per-isolate problem go away.
  3. Rerun the ramp, then the hot organization scenario. Only then does the second one measure what it was written for.
  4. Correct the architecture doc. The “no D1 writes” claim, and the duration and CPU lines.
  5. Log a safe error message. A bounded message for known error families, scrubbed of anything key-shaped, so the next failure doesn’t need a debug deploy.
  6. Find the long-stream overhead. Sample the per-step timing while 1,000 streams are held open.

I’ll also ask Cloudflare whether the D1 10 second window is a limit that can be raised for my plan. I don’t know, so I’m not designing around the answer.

What I’d tell myself a week ago

  1. Write the prediction down before you measure it. I’d predicted Durable Objects would be the limit. Having it on paper is what made the D1 answer surprising instead of just a number.
  2. Make the tool show you the subtraction. A “lost usage” figure that mixed failed and unrecorded requests nearly sent me looking for a bug in the wrong place. The fix was one line: count the 500s k6 saw and subtract the 500s the log has.
  3. “Errors: 0” on a dashboard means unhandled errors. If your code catches failures and returns its own 500, the platform never counts them. Count status codes yourself.
  4. A guard on a per-isolate variable isn’t a guard on the system. The once-a-minute throttle is correct in a single process and meaningless across a few hundred.
  5. Rules about logs deserve a deliberate exception path. My “never log more than the error’s name” rule is right for production, and it hid the answer for an afternoon. A staging-only, reverted, deleted-afterwards debug build is the exception path. Write it down before you need it.
  6. Check the doc against the system after a big move. The “no D1 writes in steady state” line was true when I wrote it, and I never checked it again.
  7. Teardown is part of the test. Delete by exact name, check each name before the command runs, and leave production out of reach by construction.

All writing