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 return402 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
developerAPI key for the sandbox workspace, and thecust_tutorial_1customer. - 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 The
402.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.
4
Test the limit
Start the server:In another terminal, call the endpoint:You should get An exhausted customer gets
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).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 Cached answers are what keep the check fast. See How answers are cached for every source value.
source field returned by orvlin.check:Production checklist
- Create one
Orvlinclient per process, not one per request. - Pick
onUnavailabledeliberately.'deny'is safer for paid features.'allow'may suit low-risk features during an outage. - Use a
viewerkey for read-only services that only check entitlements. - Log the
sourcefield 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.