Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

AI Billing Bugs: How a Ledger Can Stop Usage Leaks

· 8 min read · Home Tech

In this article
  1. Why AI Billing Is Prone to Errors
  2. How a Ledger Works as a Safety Net
  3. What to Log for Each Request
  4. Common Misconceptions About Billing Bugs
  5. How to Choose a Ledger System
  6. Cost and Safety Considerations
  7. Alternatives to a Full Ledger
  8. Frequently Asked Questions

AI billing bugs can silently turn metered usage into free service, but a well-structured ledger—a detailed, auditable record of every API call and token—can catch and prevent these leaks by providing a single source of truth for reconciliation. When your AI provider's usage dashboard says one thing and your internal records say another, the ledger is what proves which side is wrong, allowing you to dispute charges or fix your own metering errors before they compound.

Why AI Billing Is Prone to Errors

AI services are billed differently from traditional cloud resources. Instead of paying for a fixed server or a gigabyte of storage, you pay for tokens—the chunks of text the model processes. A single API request can involve multiple models, each with its own price per million tokens, plus separate charges for input, output, and sometimes caching. This complexity creates many places for a bug to hide.

Common failure points include:

  • Incorrect token counting: The provider counts tokens differently than your client library, leading to underbilling or overbilling.
  • Retry logic: A network timeout might cause your code to retry a request, but the provider processes both attempts. If your client doesn't log the retry, you see one request while the provider sees two.
  • Streaming interruptions: If a streaming response is cut off, the provider may still bill for the full generated output, while your logs only record the partial text you received.
  • Batch processing: When you send multiple prompts in one API call, a bug in your code or the provider's system can drop some of them from the bill, making usage appear lower than it actually is.
  • Cache confusion: Some providers offer prompt caching at a reduced rate. If the cache key is misconfigured, you might be charged full price for cached content, or conversely, not charged at all for something that should be billed.

These aren't hypothetical edge cases—they're the kind of issues that arise when complex metering systems meet real-world network conditions and code bugs.

How a Ledger Works as a Safety Net

A ledger is essentially a tamper-evident log of every billing-relevant event. For AI usage, this means recording each API request and response with enough detail to independently calculate the expected cost. The ledger doesn't replace your provider's dashboard; it gives you a way to verify it.

Here's the core workflow:

  1. Capture: Every time your application makes an AI API call, log the timestamp, model name, input token count, output token count, and a unique request ID (if provided).
  2. Store: Write these records to a secure, append-only store—like a database table, a log file, or a cloud storage bucket. The key is that records cannot be silently modified or deleted.
  3. Reconcile: Periodically (daily or hourly), compare your ledger's total token usage and cost against the provider's invoice or usage report. Any discrepancy is flagged for investigation.
  4. Alert: Set up alerts for unusual patterns, such as a sudden spike in usage that doesn't correlate with your own deployment activity, or a drop in usage that suggests requests are being lost.

The ledger acts as a neutral third party. If your ledger says you sent 1,000 requests and the provider bills for 1,200, you have concrete evidence to open a support ticket. If the provider bills for 800, you know you have a bug in your own code that's dropping requests—and those dropped requests might be getting processed anyway, creating hidden costs or, worse, missing functionality.

What to Log for Each Request

To make the ledger useful, you need to capture the right fields. A minimal set includes:

  • Request ID: The provider's unique identifier for the call. This is the single most useful field for disputing a charge.
  • Timestamp: When the request was initiated and when the response was fully received.
  • Model name: The exact model version (e.g., gpt-4o-mini vs. gpt-4o).
  • Input tokens: The number of tokens in the prompt, as reported by the API response.
  • Output tokens: The number of tokens in the completion, as reported by the API response.
  • Endpoint: The specific API method used (chat completions, embeddings, etc.).
  • Status code: Whether the request succeeded or failed, and if it failed, why.
  • Your own user/tenant ID: So you can attribute costs to specific customers or departments.

If the provider's API doesn't return token counts in the response (some older endpoints don't), you can estimate them locally using a tokenizer library. This won't be exact, but it's close enough for reconciliation. The provider's own dashboard is the source of truth for actual billing, but the ledger is your source of truth for what you believe you used.

Common Misconceptions About Billing Bugs

One widespread misconception is that billing bugs always result in overcharging. In reality, undercharging is just as common—and potentially more dangerous. If the provider's meter undercounts your usage, you might receive a massive retroactive bill after months of underbilling, or the provider might simply cut off your service when they notice the discrepancy. A ledger that shows higher usage than the provider's dashboard is an early warning sign of this.

Another misconception is that the provider's API response is always accurate. The token counts returned in the API response are generated by the provider's own counting logic, which can itself have bugs. For example, a provider might change its tokenization algorithm between model versions, causing the same text to be counted differently. Your ledger should record what the provider reported, but also note the model version and date, so you can track changes over time.

People also assume that retries are idempotent—that sending the same request twice is harmless. Many AI APIs do not guarantee idempotency, meaning a retry can result in two separate charges. A ledger that logs each attempt, including retries, makes these duplicate charges visible.

How to Choose a Ledger System

You don't need a specialized AI billing tool to start. A simple database table or even a well-structured CSV file can work for small projects. The key requirements are:

  • Append-only: The system should make it difficult to alter or delete past records. This is what makes the ledger trustworthy.
  • Queryable: You need to be able to sum usage by time period, model, or user. A spreadsheet can do this, but a database is more scalable.
  • Automated capture: The logging should happen automatically in your code, not require manual entry. If you have to remember to log, you'll forget.
  • Alerting: The system should be able to notify you when the discrepancy between ledger and provider exceeds a threshold.

For larger organizations, there are commercial and open-source tools that provide AI usage tracking, but they all rely on the same principle: capturing request data and comparing it to the provider's bill. Start with a simple script that logs to a database, then add reconciliation jobs as your usage grows.

Cost and Safety Considerations

Maintaining a ledger has a small cost: the storage and compute needed to log and process requests. For most applications, this is negligible compared to the AI API costs themselves. The bigger cost is the engineering time to build and maintain the system. However, this investment pays for itself if it catches even one significant billing error.

From a safety perspective, a ledger also helps you detect unauthorized usage. If someone gains access to your API keys, they can run up charges. A ledger that shows requests you didn't initiate is an early indicator of a security breach. Additionally, if you're subject to data protection regulations, the ledger itself contains sensitive data (the prompts and responses) and must be secured accordingly. Encrypt the ledger at rest, restrict access, and define a retention policy.

Alternatives to a Full Ledger

If building a ledger feels like overkill, there are lighter-weight alternatives:

  • Provider dashboards: Most AI providers offer built-in usage tracking. This is a good starting point, but it only shows what the provider thinks you used—it doesn't catch their bugs.
  • Proxy services: Some tools act as a gateway between your application and the AI provider, logging all requests and providing a unified dashboard. This is a form of ledger, but it adds a layer of latency and can be expensive.
  • Manual spot checks: For very low usage, you can manually compare your application logs with the monthly invoice. This is error-prone but better than nothing.

None of these offer the same level of independent verification as a ledger you control. If you're spending more than a few hundred dollars a month on AI APIs, a ledger is a worthwhile investment.

Frequently Asked Questions

Can a ledger prevent AI billing bugs from happening in the first place?

No, a ledger cannot prevent bugs in the provider's metering system or in your own code. What it does is detect them quickly, often within hours, so you can fix the root cause before the discrepancy grows. It's a safety net, not a shield.

What if my provider doesn't return a request ID?

Most major providers do return a request ID in the response headers or body. If yours doesn't, you'll need to rely on a combination of timestamp, model name, and token counts to match records. This is less precise but still useful for aggregate reconciliation.

How often should I reconcile my ledger with the provider's bill?

Daily reconciliation is a good practice for any production workload. It catches issues early and makes the investigation easier because the time window is small. Weekly may be acceptable for low-volume applications, but the longer you wait, the harder it is to trace the root cause.

Is the token count in the API response always the same as what I'm billed for?

Not necessarily. The API response token count is typically the same as what's billed, but there are exceptions. For example, some providers bill for cached input tokens at a different rate, and the response may not clearly indicate which tokens were cached. This is exactly the kind of discrepancy a ledger can help you spot.

Can I use a ledger to dispute a charge with my AI provider?

Yes. If your ledger shows a significantly lower usage than the provider's invoice, you can open a support ticket and provide your logs as evidence. Providers are generally willing to investigate, especially if you can show a systematic discrepancy. However, if the provider's metering is correct and your ledger is wrong, you'll need to fix your own logging.