Skip to main content
Time: about 25 minutes · Level: intermediate · You’ll build: an Express middleware that checks entitlements before each request and records usage only for allowed requests.

Scenario

Your plans include a monthly allowance of search requests. When a customer uses it up, the API should return 402 Payment Required with a link to upgrade, without slowing down the requests that are allowed. This tutorial uses the setup from Meter your first API. Complete that first.

Prerequisites

  • A developer API key for the sandbox workspace, and the cust_tutorial_1 customer.
  • Node.js 20 or later.
1

Create the Orvlin client once, at startup

Create one client and reuse it. The client keeps the entitlement cache, so each request doesn’t open a new connection or wait for the network.
onUnavailable: 'deny' is the safe default. A customer you’ve seen recently still gets through on a stale answer. A customer the cache has never seen is refused until Orvlin responds.
2

Write the middleware

The middleware reads the customer from a request header, checks the feature, and either passes the request on or returns 402.
The amount is how much this request uses. Use 1 for one request, or the real cost for variable-cost requests.
3

Record usage only for allowed requests

Record the event after the work succeeds. A failed request shouldn’t count toward the allowance.
track is awaited here so a failed usage write is visible. In production, you may prefer to queue it and not block the response. If you queue it, keep the same idempotencyKey.
4

Test the limit

Start the server:
In another terminal, call the endpoint:
You should get 200 OK and a remaining count.To test the 402 path, use a customer whose allowance is used up. Check the allowance for that customer and feature first with GET /v1/customers/:id/entitlements/:featureName, then send a request as that customer. The SDK caches answers for 30 seconds, so wait for the cache to expire or call orvlin.invalidate(customerId).
An exhausted customer gets 402 Payment Required.
5

Check the cache behaviour

Call the endpoint twice in a row. The second check should come from the cache, which you can see with the source field returned by orvlin.check:
Cached answers are what keep the check fast. See How answers are cached for every source value.

Production checklist

  • Create one Orvlin client per process, not one per request.
  • Pick onUnavailable deliberately. 'deny' is safer for paid features. 'allow' may suit low-risk features during an outage.
  • Use a viewer key for read-only services that only check entitlements.
  • Log the source field so you can see how often checks fall back.

Next steps

Sell prepaid credits

Let customers pay in advance for AI generations.

Entitlements reference

Every cache setting and what it does.