Rate Limits, Errors and Cost Awareness

Handle 429s and overloads gracefully and know what every feature costs before your bill tells you.

Beginner · about 3 hours · difficulty 2/5

Learn first: Messages APIs and Provider SDKs, Async I/O and Concurrency

Model APIs enforce rate limits on requests per minute, input tokens per minute and output tokens per minute, often by usage tier. Exceed them and you get HTTP 429. Providers also return overloaded or server errors under heavy load.

Handling limits

  • Retry 429 and 5xx with exponential backoff and jitter; respect retry-after headers. Official SDKs do some of this for you.
  • Cap concurrency with a semaphore or queue sized to your limits.
  • For large offline jobs use batch APIs instead of hammering the live API.
  • Have a fallback model or provider for critical paths (covered in production).

Understanding cost

Cost per request is roughly: input tokens x input price + output tokens x output price, minus caching discounts. Things that quietly inflate it:

  • Resending long chat histories every turn.
  • Big tool definitions and verbose tool results.
  • Reasoning tokens.
  • Retry storms and agent loops that never terminate.

Habits

  • Log usage per request with a feature name and user ID so you can attribute spend.
  • Set budget alerts and hard spending limits in the provider console.
  • Estimate cost per user action before launching ("each search costs about X").

Good enough to move on

You can explain your app's cost per request, survive a burst of 429s without crashing, and have spend alerts configured.

Key concepts

  • RPM and TPM limits and tiers
  • Backoff with jitter
  • Cost per request math
  • Usage logging and attribution
  • Budget alerts and spend caps

Mini project

Add a middleware or wrapper around your model client that retries with backoff, enforces a concurrency cap, and writes per-request usage and cost to a SQLite table; build a one-page report of cost by feature.

Check yourself

Your chatbot's cost per conversation grows quadratically with the number of turns. Explain why and name two fixes.

Free resources