Preventing AI API Costs from Growing Beyond What You Expected
The typical causes of ballooning costs and the safeguards to put on the server side. It also covers how to estimate once before you start, and a setup that lets you find out sooner than the bill does.

Ren

Procura
Typical causes of ballooning costs
Most cost spikes come from the number of calls, not the price per call. A button a person presses has a natural cap on count, but when a program calls the API, there's no brake. If you build it to retry automatically on failure, calls increase most when things aren't going well. If you count "how many times it could be called in the worst case" at design time, you won't be surprised later.
- Sending the entire conversation history every time (the cost per call grows as the exchange continues)
- Automatically retrying on errors, and that repeating
- Calling the API endlessly in an infinite loop (the costliest kind of accident)
- Passing long text whole (often passing only the necessary part is enough)
- Leaving test code running in production
Safeguards to put on the server side

Procura
- Set a cap on calls per day and stop when it's exceeded
- Always limit the number of retries (unlimited retries invite accidents)
- Summarize the old part of the conversation history, or cut it off at a certain amount
- Just returning the same answer to the same question (caching) can cut a lot
- Log usage so you can view it day by day

Ren

Procura

Wilson

Procura
Estimate before you use it

Procura
- Measure the actual cost of one request
- Multiply by the expected number of requests per day
- Multiply that by 30 to get the approximate monthly amount
- If the amount is unacceptable, review the design before going public
Use different models for different jobs

Procura
Make it something you can notice
Finding out for the first time from the bill at the end of the month is the costliest way. Many providers let you set usage notifications, so set those first. If you set it to stop when a limit is reached, you can prevent costs from growing while you sleep.
- In the provider's control panel, set a usage limit and notifications
- Also make daily call counts visible in your own logs
- Add a mechanism that lets you notice a sudden increase
- Separate the key for testing from the key for production (so you can tell which one is being used)

Procura

Ren
This article is translated from the Japanese original. If the two differ, the Japanese version is the one we keep up to date.