You ship a "cost control" PR. Grafana looks quieter. Finance still spikes. Nine times out of ten the middleware was correct β the order was not.
Microsoft.Extensions.AI lets you stack IChatClient layers the way ASP.NET stacks HTTP middleware. Caching, GenAI spans, and a hard token budget only work if the request walks through them in a defendable sequence. This post is the short order checklist. The complete offline-tested project (DistributedCachingChatClient, OpenTelemetryChatClient, TokenBudgetChatClient, rate limit, 56 tests) lives in Tech Skill Builder β $5/month for a very limited time only (normally $10). Grab it now before it goes back to $10.
Mistake 1: Putting the budget outside the cache
A cache hit still "spends" tokens on the ledger. You celebrate fewer provider calls while the budget burns twice for one real completion.
Shape that works: OpenTelemetry β cache β budget β rate limit β provider.
IChatClient client = new ChatClientBuilder ( inner ) .β¦