Cut AI API Costs: Caching, Batching, Smaller Models
In this article
AI API costs can quietly eat a budget, especially as usage grows. This guide shows three practical ways to reduce spending without sacrificing quality: caching repeated requests, batching multiple inputs into one call, and choosing smaller models for simpler tasks. You'll see exactly how to implement each approach, what to watch out for, and how to fix common problems.
What You'll Need
- Access to an AI API (OpenAI, Anthropic, Google, or similar) with an API key.
- A basic understanding of HTTP requests and JSON.
- For caching: a key-value store like Redis, or a simple in-memory cache in your app.
- For batching: an API that supports multiple inputs in one request (most do, but check docs).
- For smaller models: the ability to switch model names in your code.
Step-by-Step
- Audit your usage. Before changing anything, log every API call for a few days. Record the prompt, response, model, token count, and timestamp. This shows you where the money goes: which endpoints are called most, which prompts repeat, and which tasks really need a large model.
- Implement caching for identical requests. The simplest win is to cache responses for exact duplicate prompts. Use a cache key made from a hash of the model name, the prompt, and any parameters like temperature. Store the response with a TTL (time-to-live) that matches how often the data changes. For example, if you summarize a news article that updates hourly, cache for 30 minutes. For static content, cache for 24 hours.
- Add semantic caching for similar prompts. Exact-match caching misses many opportunities. Use embeddings to compare new prompts to cached ones. If the cosine similarity is above a threshold (e.g., 0.95), return the cached response. This catches paraphrased questions that have the same answer. Store the embedding along with the response in your cache.
- Batch multiple requests into one call. Many APIs let you send an array of prompts in a single request. Instead of calling the API 10 times for 10 questions, send all 10 at once. This reduces overhead and often costs less per token because you're not paying for repeated system prompts or connection setup. Check your API's documentation for the exact format; some use a
batchendpoint, others allow multiple messages in one request. - Use smaller models for simple tasks. Large models like GPT-4 or Claude 3 Opus are overkill for classification, extraction, or formatting. Switch to a smaller, cheaper model (e.g., GPT-3.5-turbo, Claude Haiku, or Llama 3 8B) for tasks that don't need deep reasoning. You can even route requests dynamically: if the prompt is short and has no complex instructions, send it to the small model; if it's long or asks for analysis, use the big one.
- Set up a fallback chain. Start with the cheapest model. If it fails or returns low confidence (e.g., the API returns a
finish_reasonoflengthor a low logprob), retry with a larger model. This ensures quality while minimizing cost. - Monitor and adjust. After implementing, track your cost per day and the cache hit rate. If the hit rate is low, your cache key may be too strict or your TTL too short. If small models are making errors, adjust the routing logic or the confidence threshold.
Common Mistakes
- Caching too aggressively. Caching responses that are time-sensitive (like stock prices or live sports scores) can serve stale data. Always set a TTL and consider invalidating cache entries when underlying data changes.
- Ignoring token limits in batching. Sending too many prompts in one batch can exceed the model's context window. Keep each prompt short, and split batches if needed.
- Using the same model for everything. Even a small model can handle many tasks. Don't default to the largest model out of habit.
- Not hashing the full request. If you forget to include parameters like temperature or max_tokens in your cache key, you might return a response that doesn't match the request.
- Forgetting to handle cache misses. When the cache is empty, you still need to call the API. Make sure your code has a clear path for that.
Tips
- Use a cache library like
cachetoolsin Python ornode-cachein Node.js to avoid reinventing the wheel. - For semantic caching, precompute embeddings for all incoming prompts and store them. Use a vector database like Pinecone or a simple in-memory list for small scales.
- Batch requests that are independent and can be answered in any order. If you need sequential responses, batching won't work.
- Review your API provider's pricing page. Some charge per token, others per request. Batching helps more when there's a per-request fee.
- Consider using a gateway like LiteLLM or Helicone to manage caching and routing across providers.
Troubleshooting
- Cache hit rate is very low. Check if your prompts are truly identical. Whitespace or punctuation differences break exact-match caching. Use semantic caching or normalize prompts (lowercase, trim).
- Batched requests return errors. Some APIs have a max batch size. Split the batch into smaller chunks. Also check that each prompt is valid JSON and doesn't contain characters that break the array.
- Small model gives poor answers. Increase the confidence threshold for routing to the large model, or add a validation step that checks the response for keywords or length.
- Cache returns stale data. Shorten the TTL or add a manual invalidation endpoint that you can call when data changes.
- Costs don't drop. You may be paying for input tokens even when caching. Ensure your cache stores the full response, not just the text, and that you don't re-send the prompt when serving from cache.
Frequently Asked Questions
Will caching affect response quality?
No, as long as the cached response is still valid. The response is identical to what the API would return, so quality is the same. The risk is staleness, which you control with TTL.
How much can I save with batching?
Savings vary. If your API charges per request, batching can cut costs by 50-80% for high-volume tasks. If it charges per token, savings are smaller but still noticeable because you avoid redundant system prompts.
Which tasks are best for smaller models?
Classification, named-entity recognition, summarization of short texts, and simple Q&A. Avoid using them for complex reasoning, code generation, or tasks that require up-to-date knowledge.
Can I use all three techniques together?
Yes, they complement each other. Cache first, then batch what isn't cached, and route to the smallest model that can handle the task.
Do I need a vector database for semantic caching?
Only if you have a large number of cached prompts. For a few thousand, you can compute cosine similarity in memory. For millions, use a vector database.
How do I know if my cache is working?
Log cache hits and misses. A hit rate above 30% is good for most applications. If it's below 10%, revisit your cache key and TTL.