DEV Community

Jack Ma
Jack Ma

Posted on

Which requests end up on the bill? Tracing usage rows from a Hono app and a FastAPI container

In both tests below, successful word-count requests added billable units. A request that called track() and then returned 422 added zero, and so did rate-limited ones. A health check produced no row at all. I also checked when each SDK sent its last rows during shutdown.

For Hono I used the @usagerail/node usage metering SDK on JSR (0.1.2). For FastAPI I ran the FastAPI starter image on Docker Hub (0.1.0, with Python SDK 0.1.1). For looking up a customer's recorded usage afterwards, the Postman collection for UsageRail's usage-based billing API has a "Get usage" request.

Nothing here talked to the real service. Both SDKs accept a base URL (baseUrl in Node, base_url in Python), so I pointed them at a 36-line local stub. It answers the three endpoints the SDK calls (/v1/sync, /v1/leases, /v1/ingest) with the shapes from the package's protocol module and prints every usage row it receives. The stub knows one customer key, which I generated with the SDK's key-format module, gives that customer a limit of 2 requests per second, and tells the SDK to count units rather than requests.

The Hono app

import { serve } from "@hono/node-server";
import { Hono } from "hono";
import { usageRail } from "@usagerail/node/hono";
import { flushOnExit } from "@usagerail/node/node";

const rail = usageRail({
  appKey: process.env.USAGERAIL_APP_KEY,
  auth: "api-key",
  baseUrl: process.env.USAGERAIL_BASE_URL, // local stub only
});
flushOnExit(rail.engine);

const app = new Hono();
app.use("/v1/*", rail);

app.post("/v1/word-count", async (c) => {
  const { text } = await c.req.json();
  const words = text.split(/\s+/).filter(Boolean).length;
  c.get("usageRail").track(words);
  if (words > 5) return c.json({ error: "too_long" }, 422);
  return c.json({ words });
});

serve({ fetch: app.fetch, port: 3125 });
Enter fullscreen mode Exit fullscreen mode

I put track() before the five-word check to see what the SDK would send when a seven-word request got a 422.

I sent five requests with the generated key: 3 words (200), 7 words (422), then three one-word requests in the same second. The first two of those got 200 and the third got a 429 with Retry-After: 1. About a minute after the server started, the stub received the rows below. My stub prints method and route as one field and leaves out minute:

{"consumer":"cons_local1","route":"POST /v1/word-count","result_type":"2xx","count":3,"units":5}
{"consumer":"cons_local1","route":"POST /v1/word-count","result_type":"4xx","count":1,"units":0}
{"consumer":"cons_local1","route":"POST _unmatched","result_type":"sdk_429","count":1,"units":0}
Enter fullscreen mode Exit fullscreen mode

Each row is one combination of customer, method plus route template, outcome and minute, so the three successful requests (3 + 1 + 1 words) were added up into a single row.

The SDK sent the 422 row with count: 1 and units: 0 even though track(7) ran. The protocol treats only 2xx, 3xx, ws_open and check_allowed as billable outcomes, and anything else settles at zero units, whatever track() said.

The 429 is recorded against _unmatched, not /v1/word-count. The Hono middleware runs before routing, and a rejected request never reaches a route, so there's no template to record. It shows up as sdk_429 with 0 units. A request with no key at all became sdk_401 with an empty consumer, which the source describes as analytics only, never quotas or invoices.

Two more track() rules from the source: the value must be an integer from 0 to 10,000,000, and the last call wins. Anything else is logged as a warning and ignored. If the app is set to count requests instead of units, track() is ignored too and the request counts as the route's weight, or 1.

When the rows leave the process

The SDK keeps these rows in memory and sends them every 60 seconds, or sooner once the table reaches 5,000 keys. If the process exits before its next report, the unsent rows are still in memory.

With flushOnExit in place, I sent a four-word request, then SIGTERM, and the stub got its row in that same second. In a run without the hook, I sent one successful request and then SIGTERM, and the stub saw no row in the three seconds I watched. It hooks beforeExit and SIGTERM and waits up to 5 seconds to report before exiting. If your app registers its own SIGTERM handler, flushOnExit switches the SDK to reporting once a second while you drain connections, and you call engine.close() at the end of your shutdown code.

The same thing in the FastAPI container

The image runs a single main.py with the SDK's UsageRailMiddleware. Its /v1/word-count route calls request.state.usagerail.track(words). To point it at the stub, I copied main.py out of the image, added one argument and mounted it back:

app.add_middleware(UsageRailExceptOpenPaths, app_key=app_key, auth="api-key",
                   base_url=os.environ.get("USAGERAIL_BASE_URL", "https://api.usagerail.com"))
Enter fullscreen mode Exit fullscreen mode
docker run -d --name starter -p 8000:8000 \
  -v "$PWD/main.py:/app/main.py:ro" \
  -e USAGERAIL_APP_KEY=urk_test_placeholder \
  -e USAGERAIL_BASE_URL=http://host.docker.internal:9099 \
  usagerail/fastapi-starter:0.1.0
Enter fullscreen mode Exit fullscreen mode

I sent four successful requests (3, 2, 3 and 1 words), one text of about a million characters, one request over the rate limit and a GET /health, then ran docker stop. The container stopped in about half a second, and the stub received these rows in the same second (same shortened format):

{"consumer":"cons_local1","route":"POST /v1/word-count","result_type":"2xx","count":4,"units":9}
{"consumer":"cons_local1","route":"POST /v1/word-count","result_type":"4xx","count":1,"units":0}
{"consumer":"cons_local1","route":"POST _unmatched","result_type":"sdk_429","count":1,"units":0}
Enter fullscreen mode Exit fullscreen mode

The long text exceeded the model's max_length=1_000_000 and got a 422 before the handler ran. The comment in main.py explains the limit: a million characters is at most 500,000 words, so track() never gets a number above its 10,000,000 cap. /health produced no row at all, because the image sends its open paths (/health, /docs, /openapi.json) around the middleware.

The shutdown report depends on two things in the image. The Dockerfile uses the exec form of CMD, so uvicorn receives SIGTERM from docker stop and runs the lifespan shutdown. And the middleware waits for engine.close() to make one last attempt to send pending usage before it forwards lifespan.shutdown.complete. The docstring in main.py adds a warning if you restructure the app: keep paid routes in the main app rather than a mounted sub-app, because a mounted app gets no lifespan events. Docker's default stop timeout on Linux is 10 seconds before SIGKILL. With the local stub, the container took about half a second to shut down.

Checking against the billing side

Back in the Postman collection, "Get usage" is GET /v1/consumers/{consumerId}/usage?days=7. Its description says it returns usage for the last 1 to 30 days, per day and for the 20 busiest routes. "Get a customer" includes current-period usage. Both use the server API key (urm_...), not the app key, and as GETs they don't need the Idempotency-Key header the collection puts on writes. The requests have no saved example responses, and I didn't call the real API, so I can't show the response format here.

If you log requests individually, add up the billable units for one customer and one day, then compare that total with "Get usage". If they differ, I'd start here:

  • 4xx and 5xx responses, which never carry units even if track() ran.
  • Rejected requests (sdk_401, sdk_429), which are recorded but not billed, and appear under _unmatched.
  • The most recent minute, which may still be in the process's memory.
  • A process killed without flushOnExit or a lifespan shutdown.
  • A long outage. The SDK drops batches older than 10 minutes, and if the queue grows past 100,000 rows it drops the oldest batches first. When reporting resumes, it sends the dropped billable usage as known losses.

The stub took longer to write than either app.

Top comments (0)