
Per-Token Monetization of AI Traffic with AWS WAF and Amazon CloudFront
AWS WAF can charge AI bots for content access - priced per request. This post extends the negotiation to value: charge by the tokens (or bytes) actually served, drop-in at the edge, with zero origin changes.
The third negotiation
This is the third post in a series about what your CDN can negotiate on your behalf.
In Content Negotiation at the Edge with Amazon CloudFront and AWS WAF , the edge negotiated format: AWS WAF classified the client, and CloudFront served AI agents markdown instead of HTML - no origin changes.
In Monetize Any HTTP Application with x402 and CloudFront + Lambda@Edge , the edge negotiated payment: HTTP 402 and the x402 protocol turned any endpoint into a paid one. Since then, AWS WAF added native AI traffic monetization - the pattern from that post is now a managed capability.
But content negotiation has more forms than format. This post adds a third axis: value. Not just what representation the client gets, and not just whether it pays - but how much, in proportion to what it actually consumes. Tokens and content-length are measures of content, just like media type is - and they can be negotiated at the edge the same way: drop-in, zero origin changes.
Flat prices meet metered consumption
AWS WAF's native monetization prices content per request. The web ACL's
MonetizationConfig sets a base price in USDC, and each Monetize rule scales it with a PriceMultiplier . The price is fixed at request time - before the response exists.That's the right default for uniform content. But AI traffic doesn't consume uniformly. Everything downstream of your content - context windows, inference costs, agent budgets - is metered in tokens. A 300-token snippet and a 30,000-token reference document are two very different transactions, and a flat price misprices both: it overcharges the small fetch and gives away the large one.
If agents pay per token to use content, it follows that they should pay per token to acquire it. The question is where the token count comes from - and who does the counting.
The chicken-and-egg of response pricing
Here's the tension:
- WAF quotes the price at request time, before the response exists.
- The token count exists only at response time, after the content is known.
You could push the pricing into your origin - but then you're modifying backends, which is exactly what this series refuses to do. You could maintain a lookup table of every URI's size - but now you own a sync pipeline and its staleness bugs.
The resolution is simpler: let the response price itself.
The first request measures the content and answers with a redirect to a priced path - carrying no content. The second request, on that path, gets a WAF-native x402 quote scaled to the measurement. Quote, then serve:

Every moving part runs at the edge. The origin - an S3 bucket, a Lambda Function URL, anything behind CloudFront - never changes and never learns that payments exist.
Tier paths: making a per-request engine metered
WAF gives us one pricing knob per rule:
PriceMultiplier . So we give it something to multiply: tier paths. Content weighing up to 500 tokens lives (logically) under /t1/ , up to 1,000 under /t2/ , up to 2,000 under /t3/ , and everything heavier under /t4/ - with one Monetize rule per tier:{ "Name": "monetize-t4", "Statement": { "ByteMatchStatement": { "SearchString": "/t4/", "FieldToMatch": { "UriPath": {} }, "PositionalConstraint": "STARTS_WITH" } }, "Action": { "Monetize": { "PriceMultiplier": "8" } }}Four rules with multipliers 1/2/4/8 turn a flat per-request price into a step function of token count. The sample uses four tiers to stay readable; production can afford eight or more - the granularity is a tuning choice, not an architectural one.
No content actually lives under those paths. They are virtual pricing lanes, minted and dissolved at the edge.
The response prices itself
A CloudFront Function on viewer-response does the measuring. It reads the token count from the response itself -
x-amz-meta-token-count object metadata when you've precomputed exact counts at upload, or a content-length / 4 heuristic when you haven't - maps it to a tier, and rewrites the response into a redirect:// viewer-response (abridged - full code in the repo)if (!request.headers['x-amzn-waf-bot']) { return response; // unmarked = human = free}var tokens = meta ? parseInt(meta.value) : Math.ceil(parseInt(contentLength.value) / 4);var tier = tierFor(tokens); // 1..4var sig = sign(tier, contentPath); // HMAC-SHA256, base64url
response.statusCode = 302;response.headers['location'] = { value: '/t' + tier + '/' + sig + contentPath + query };response.body = { encoding: 'text', data: '' }; // empty - no content leaks unpaidThat first check is a decision WAF already made, not one the function makes. Bot Control (v6+, running in Count mode) labels bot traffic, and a label-match rule inserts the
x-amzn-waf-bot marker header. No marker means a human - the response passes through free and untouched. WAF decides who pays; the edge decides how much.If you deployed the format-negotiation pipeline from the first post, you already have exact token counts: the generator writes them into object metadata alongside the markdown it produces. The two patterns compose - negotiate the format, then price by its measured weight.
One detail cost us a day of debugging, so you get it for free: AWS WAF evaluates before CloudFront Functions. A viewer-request function that rewrites the URI in place is invisible to WAF - the Monetize rule never sees the tier. The move onto a priced path must be a real 302, a genuinely new request that passes through WAF from the top.
Paying the right price for the right bytes
Plaintext tier prefixes would be an invitation: nothing stops a bot from hand-crafting
/t1/content/large-doc and paying the t1 price for t4 content. The signature in the path closes this. It is an HMAC-SHA256 over both the tier and the exact content path - crypto.createHmac is available in the CloudFront Functions JavaScript 2.0 runtime, so signing and verifying are sub-millisecond edge operations with no origin round-trip.The viewer-request function (which runs after WAF has verified the payment) recomputes the HMAC and refuses to serve on any mismatch:
- Tier-downgrade (
/t1/<sig>/large-docwith a t4 signature) → 403, no content.
- Content-swap (valid t1 signature paired with a different object) → 403, no content.
- Valid signature → the function strips
/t<n>/<sig>/, so the cache key and origin path stay clean and tier-agnostic.
WAF settles the payment only on a 2xx response, so a forged path 402s at the gate and 403s at serve time - it never yields content at the wrong price. The signing secret lives with the edge functions (in production: a CloudFront KeyValueStore, read via
cf.kvs() , rotated with a dual-key window); viewers can see signatures all day and mint none.The full request lifecycle, integrity gate included:

Watch it negotiate
Three requests against the deployed sample (TEST currency mode - quotes are real, payment is on the Base Sepolia testnet):
# 1. Bare path: the response measures itself and redirects - no content served$ curl -s -D- -o /dev/null https://<DISTRIBUTION_DOMAIN>/content/large.txtHTTP/2 302location: /t4/mKa8dmTGyuBBK879mSCPzet3l52C-nijPPtWmOTJnyg/content/large.txtcache-control: no-store
# 2. Signed tier path: WAF Monetize fires with the tier-scaled x402 quote$ curl -s -D- -o /dev/null https://<DISTRIBUTION_DOMAIN>/t4/mKa8dm.../content/large.txtHTTP/2 402payment-required: eyJhY2NlcHRzIjpb... # base64-encoded x402 quoteDecode the quote and the per-token pricing is visible - 8,000 micro-USDC, the 0.001 USDC base price × the t4 multiplier:
{ "accepts": [{ "amount": "8000", "extra": { "name": "USDC", "version": "2" }, "network": "eip155:84532", "payTo": "0xYourWalletAddress", "scheme": "exact" }], "resource": { "url": "https://<DISTRIBUTION_DOMAIN>/t4/mKa8dm.../content/large.txt" }, "x402Version": 2}# 3. Pay and retry with an x402 client: WAF verifies the PAYMENT-SIGNATURE,# the edge verifies the path signature, the cache serves, WAF settles on 2xx.A word on humans: the sample ships this split rather than leaving it as an exercise. AWS WAF Bot Control labels the traffic, the edge self-prices only marked responses, and humans browse every bare path free - they never see a 402. A priority-0 rule blocks client-supplied
x-amzn-waf-* headers, so the marker can't be spoofed from outside. It's also why curl makes a good demo client: Bot Control labels it an http_library bot, so it gets marked, redirected, and quoted.Dynamic content: the cache is the receipt
Static objects can carry token counts in metadata. But what about API responses that don't exist until they're generated? Generating twice - once to measure, once to serve - would double your compute and could even produce a different response the second time.
The answer is already sitting in the architecture: CloudFront's cache is the receipt store.
- The first request reaches the origin - a Lambda Function URL locked behind Origin Access Control (
AuthType: AWS_IAM, invokable only by this distribution; never publicly accessible). The generated response lands in the CloudFront cache under a short-TTL, path-keyed cache policy - and the same viewer-response function measures it and answers with the signed 302. Content identity here is path-only: the demo endpoints take no query parameters. If your API varies by query string, add the query to both the cache key and the HMAC, so a paid path can't be replayed onto different content.
- The paid retry walks the tier path: WAF quotes, verifies, the edge strips the prefix - and the URI collapses back to an identical cache key. Cache hit. The exact body that was measured is the body that is served, with no second generation.

No Lambda@Edge, no receipt database, no bookkeeping - the cache TTL is the payment window. (POST bodies can't join cache keys, so request-body APIs need a heavier Lambda@Edge variant - the repo discusses the trade-off.)
Notes from the edge
Field observations from building this, in case they save you the same hours:
Finding | Detail |
|---|---|
WAF runs before CloudFront Functions | An in-place URI rewrite in a CFF is invisible to WAF. Moving a request onto a priced path requires a real 302. |
crypto.createHmac works in CFF JS 2.0 | Path signing and verification are sub-millisecond at the edge, no origin round-trip. |
Monetize works without Bot Control | A bare URI match + Monetize action returns 402. Bot Control's job here is shielding humans, not enabling payment. |
WAF-inserted headers are visible to CloudFront Functions | A Count rule with InsertHeaders puts x-amzn-waf-bot on the request, and both viewer functions can read it. Pair it with a rule that blocks client-supplied x-amzn-waf-* headers, or the marker is spoofable. |
Beyond tokens
Step back from the mechanics and the shape is simple: the edge measured content, expressed the measurement as a price, and negotiated the exchange - without the origin participating.
Format was one axis. Payment was another. Quantity is the one shown here. But the negotiation space is wider than that, and the same three primitives - classification (WAF labels), state (KeyValueStore, cache, metadata), and programmable routing (CloudFront Functions) - keep applying:
- Freshness - price real-time data above cached data; let the quote decay with
age.
- License terms - embed usage rights in the quote; training rights priced differently from inference-time retrieval.
- Client tiers - verified agents with Web Bot Auth credentials get preferred pricing; anonymous scrapers pay list price.
- Quality of service - pay for the un-throttled lane; the free tier rides the rate limiter.
Each of these is content negotiation in some form. Each can live entirely at the edge, in front of an origin that never changes.
And one primitive on that list is quietly doing more than it looks. The production home for the signing secret is the CloudFront KeyValueStore (the sample bakes a per-deployment secret into the functions at deploy time; KVS is the rotating upgrade) - and KVS is a globally-replicated key-value store, read in sub-millisecond time from every edge location. Treat it as a distributed database at the edge and the variables it can hold open a new level of customization: dynamic tier tables you can retune without a deploy, per-client pricing and entitlements, license state, feature flags, rolling quotas - all resolved per request, in front of an unchanged origin. That’s a big enough idea to be the fourth post in this series.
Treat this post as a vision of what’s possible when WAF and CloudFront Functions price traffic together - not a prescription. Tokens and content-length are the axis I built; the one that fits your business might be a different measure, or a different mechanism for this same one.
This is where you come in. What would you negotiate at the edge? Share the pattern in the comments, or reach out on LinkedIn - the best part of publishing the first two posts was what readers built sideways from them.
Try it
The full sample - the two edge functions, the WAF web ACL with its Monetize and Bot Control rules, both content variants, and the CDK app that wires them together - is on GitHub:
It runs in WAF's TEST currency mode against the Base Sepolia testnet, so you can watch real 402 quotes scale with token counts without moving real money. The README covers deployment and teardown - the stack creates billable resources (CloudFront distribution, WAF web ACL with Bot Control, Lambda, S3), so clean up when you're done exploring.
Conclusion
Your content has a weight, and now it has a price that tracks it. The origin still serves exactly what it always served - the edge measures, signs, quotes, and settles around it.
That's the through-line of this series: keep a single source of truth at the origin, and let the edge negotiate everything else about the exchange - the format, the payment, the value. When the next axis of negotiation shows up, it should be a WAF rule and an edge function away.
What's your next axis? Tell me in the comments.
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article