Cost Control for LLMs: Token Counting and Budgeting in Production

We design and deploy artificial intelligence systems: from prototype to production-ready solutions. Our team combines expertise in machine learning, data engineering and MLOps to make AI work not in the lab, but in real business.
Showing 1 of 1All 1564 services
Cost Control for LLMs: Token Counting and Budgeting in Production
Simple
~2-3 days
Frequently Asked Questions

AI Development Areas

AI Solution Development Stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1358
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1251
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    957
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1188
  • image_logo-advance_0.webp
    B2B Advance company logo design
    646
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    929

How Not to Lose Your Budget on LLMs: Token Counting and Budgeting

Picture this: a development team integrates GPT-4 for processing customer requests, and a month later the API bill hits $5,000 instead of the expected $500. The reason—every request included a 2,000-token system prompt, and duplicate requests were never cached. Token counting and budgeting are not optional; they are a necessity for any production system using LLMs. Without them, you risk a bill 5–10 times higher than anticipated.

We implemented a cost management system for a SaaS platform handling 10,000 daily requests to GPT-4 and Claude. The result: a 35% cost reduction in the first month, saving over $1,500 per month. Below we break down how we did it and how you can replicate the success. Our certified MLOps engineers guarantee a minimum 20% cost reduction for most clients, backed by a proven track record with over 50 successful projects.

Why Budgeting LLM Requests Matters

LLM request costs are unpredictable: output token length varies, and system prompts often bloat unchecked. Without budgeting, it's easy to get a bill 5–10 times higher than expected. Budgeting solves three problems:

  • Preventing overspend: alerts when daily or monthly limits are exceeded.
  • Cost optimization: identifying inefficient prompts and models.
  • Transparency for teams: dashboards with breakdowns by user, feature, and model.

Principles of Token Counting in Production

Token counting estimates the number of tokens in a request before sending. For OpenAI we use the tiktoken library (OpenAI Tokenizer documentation), for Anthropic the built-in counter. Example calculation:

import tiktoken

def count_tokens_openai(text: str, model: str = "gpt-4") -> int:
    enc = tiktoken.encoding_for_model(model)
    return len(enc.encode(text))

def estimate_request_cost(prompt: str, max_completion: int = 1000, model: str = "gpt-4-turbo") -> dict:
    input_tokens = count_tokens_openai(prompt, model)
    total_tokens = input_tokens + max_completion
    prices = {
        "gpt-4-turbo": {"input": 10.0, "output": 30.0},
        "gpt-4o": {"input": 5.0, "output": 15.0},
        "gpt-4o-mini": {"input": 0.15, "output": 0.60},
        "claude-3-5-sonnet": {"input": 3.0, "output": 15.0},
    }
    price = prices.get(model, {"input": 10.0, "output": 30.0})
    estimated_cost = (input_tokens / 1_000_000 * price["input"] + max_completion / 1_000_000 * price["output"])
    return {"input_tokens": input_tokens, "max_output_tokens": max_completion, "estimated_cost_usd": estimated_cost}

Cost estimation allows rejecting requests that exceed a user's or team's limit. The tokenizer vocabulary and encoding method are critical for accurate counting.

Model Cost Comparison Table

Model Input per 1M tokens Output per 1M tokens
GPT-4-turbo $10.00 $30.00
GPT-4o $5.00 $15.00
GPT-4o-mini $0.15 $0.60
Claude 3.5 Sonnet $3.00 $15.00

Methods to Reduce LLM Costs

One effective method is automatic model routing. For example, for simple tasks (data extraction, basic classification) we use GPT-4o-mini, which is 10x cheaper than GPT-4-turbo yet yields comparable results. For complex generations we keep the top-tier models. In our case study, this reduced the average request cost from $0.03 to $0.008.

We also implement caching: duplicate requests (e.g., repeated user questions) are served from Redis cache, saving up to 40% of the budget. We use an LRU cache with a 24-hour TTL. System prompt optimization can further cut input tokens by half, significantly reducing API cost management overhead.

Budgeting System with Redis and Middleware

We use Redis to store limits—it's fast and supports atomic operations. Our Redis budgeting system stores daily and monthly limits per user and globally. Budget structure:

from dataclasses import dataclass, field
import threading

@dataclass
class TokenBudget:
    daily_limit_usd: float
    monthly_limit_usd: float
    per_user_daily_limit_usd: float = 1.0
    spent_today: float = field(default=0.0)
    spent_month: float = field(default=0.0)
    _lock: threading.Lock = field(default_factory=threading.Lock)

class LLMBudgetManager:
    def __init__(self, redis_client, budget: TokenBudget):
        self.redis = redis_client
        self.budget = budget

    def check_and_reserve(self, user_id: str, estimated_cost: float) -> bool:
        """Check budget before request"""
        daily_spent = float(self.redis.get(f"budget:daily") or 0)
        if daily_spent + estimated_cost > self.budget.daily_limit_usd:
            raise BudgetExceededError(f"Daily budget ${self.budget.daily_limit_usd} exceeded")
        user_spent = float(self.redis.get(f"budget:user:{user_id}:daily") or 0)
        if user_spent + estimated_cost > self.budget.per_user_daily_limit_usd:
            raise BudgetExceededError(f"User daily budget ${self.budget.per_user_daily_limit_usd} exceeded")
        pipe = self.redis.pipeline()
        pipe.incrbyfloat(f"budget:daily", estimated_cost)
        pipe.expire(f"budget:daily", 86400)
        pipe.incrbyfloat(f"budget:user:{user_id}:daily", estimated_cost)
        pipe.expire(f"budget:user:{user_id}:daily", 86400)
        pipe.execute()
        return True

    def record_actual_cost(self, user_id: str, actual_cost: float, estimated_cost: float):
        correction = actual_cost - estimated_cost
        if abs(correction) > 0.001:
            self.redis.incrbyfloat("budget:daily", correction)
Middleware for automatic cost tracking
import functools

def track_llm_cost(model: str = "gpt-4o"):
    def decorator(func):
        @functools.wraps(func)
        async def wrapper(*args, **kwargs):
            result = await func(*args, **kwargs)
            if hasattr(result, 'usage'):
                cost = compute_cost(result.usage.prompt_tokens, result.usage.completion_tokens, model)
                analytics.record(function=func.__name__, model=model, cost=cost, input_tokens=result.usage.prompt_tokens, output_tokens=result.usage.completion_tokens)
            return result
        return wrapper
    return decorator

Typical result of implementation: 20–40% reduction in LLM costs by identifying inefficient requests (long unnecessary system prompts, duplicate uncached requests) and choosing the right model for each task. Budget alerts via Slack or Telegram ensure no surprises.

Practical Results of Token Counting

Without token counting, you don't know how much you spend per request. We implemented dashboards in Grafana showing cost by user, model, and function. This allowed the client to discover that 30% of queries were repeats with the same prompts. After enabling caching, savings reached $1,500 per month. LLM model selection and system prompt optimization further cut costs. Want similar savings? Contact us for a cost audit.

Common Mistakes in LLM Budgeting

We often see the same mistakes: ignoring system prompt tokens, lack of caching, using expensive models for simple tasks, no per-user limits, and no monitoring. Each can increase costs 10–50 times. The solution: implement token counting, budget alerts, and model routing. Our Redis budgeting system also tracks per-user limits to prevent abuse.

Step-by-Step Token Counting Setup

  1. Integrate the tiktoken library.
  2. Implement a token counting function for your model.
  3. Estimate request cost using model pricing (see table above).
  4. Add budget check before API calls.
  5. Set up logging and dashboards.

Scope of Work for Budgeting System Implementation

We offer turnkey implementation of token counting and budgeting systems. The project includes:

  • Audit of current architecture and request profile.
  • Integration of tiktoken and Anthropic SDK into your codebase.
  • Redis setup for storing limits and statistics.
  • Implementation of middleware for automatic cost tracking.
  • Monitoring dashboards (Grafana + Prometheus).
  • Team training and documentation.

Our MLOps experience spans over 5 years; we have implemented budgeting systems for companies handling up to 1 million requests per day, serving 20+ enterprise clients with a proven methodology. Implementation timelines: 2–4 weeks for a basic system, up to 6 weeks for complex architectures. Contact us for a project assessment and request an LLM cost audit. We guarantee a minimum 20% cost reduction or your money back.

MLOps: Infrastructure for Training, Deploying, and Monitoring ML Models

The model is trained, metrics — F1 0.94 on validation. Three months later in production, quality drops by 12%. No one knows when — there is no monitoring. It's impossible to retrain quickly — the training script is in a Jupyter notebook of a data scientist who has already left. Data for retraining is collected manually from three disparate systems. About half of the projects come to us with this pain. We build a turnkey MLOps platform: from experiment tracking to automatic deployment and data drift monitoring. We will assess your infrastructure in 1–2 weeks, and in 4–6 weeks you will get a basic MLOps core running in production. Our team has 10+ years of experience in ML infrastructure, over 50 implementations.

How does MLOps infrastructure benefit your ML projects?

Experiment Tracking and Reproducibility

Without tracking, an ML project turns into chaos: it's unclear which checkpoint is better, which hyperparameters were used, which dataset. Reproducing a result a month later is a quest.

Why is experiment tracking the foundation of reproducibility?

MLflow is an open source standard for tracking. It logs parameters, metrics, artifacts (models, graphs), and code. MLflow Model Registry is a centralized model storage with versioning and lifecycle stages (Staging → Production → Archived). Deployment via MLflow Serving or integration with external systems.

Typical initialization in code:

import mlflow

mlflow.set_experiment("fraud-detection-v2")
with mlflow.start_run():
    mlflow.log_params({"learning_rate": 3e-4, "batch_size": 64, "epochs": 10})
    mlflow.log_metric("val_f1", val_f1, step=epoch)
    mlflow.pytorch.log_model(model, "model")

This is the minimum. In production, we add logging of system metrics (GPU utilization, memory), dataset (hash, version), code (git commit hash). Weights & Biases — richer UI, collaboration features, sweep for hyperparameter optimization. MLflow — for on-premise deployment without external dependencies.

DVC (Data Version Control) — versioning of data and models on top of git. Data is stored in S3/GCS/Azure Blob, only metadata (hashes) in git. dvc repro reproduces the entire pipeline from raw data to metrics.

To ensure reproducibility of training, fix random seeds (torch.manual_seed, numpy.random.seed, random.seed) and record them in experiment metadata. Without this, debugging irregular results is painful. Log the dataset version (DVC hash) and git commit — then any experiment can be reproduced down to the byte.

Pipeline Orchestration: Kubeflow, Airflow, Prefect

A pipeline orchestrator becomes necessary when: A 100-line training script in cron is fine for simple tasks. But as soon as you have a multi-step pipeline (data loading → preprocessing → feature engineering → training → validation → deployment if quality above threshold), you need an orchestrator with retry logic, visualization, and alerts.

Kubeflow — Kubernetes-native orchestrator for ML (see Kubeflow). Each step is a Docker container. Supports parallel steps, conditional branches, artifacts between steps. Integrates with Katib (AutoML), KServe (serving), Feast (feature store).

Apache Airflow — more general DAG orchestrator. Wide ecosystem of operators (S3, Spark, DBT, Kubernetes). Easier to deploy if Airflow already exists in the company.

Prefect / Metaflow — less boilerplate. Prefect 2.x with @flow and @task decorators — quick start for small teams.

Typical training pipeline architecture on Kubeflow:

  1. Data ingestion component — fetches data from S3/DB, validates schema via Great Expectations
  2. Preprocessing component — transformations, normalization, train/val/test split
  3. Training component — training on GPU, logging to MLflow
  4. Evaluation component — metric calculation, comparison with baseline in Model Registry
  5. Conditional deployment — deploy only if new model is better than current by >2% F1

Each component is a separate Docker image. Pipeline is versioned in git. Scheduled run (retraining once a week on new data) or manual.

Model Registry and Lifecycle Management

Model Registry is not just a checkpoint store. It is a centralized system that knows:

  • Which model is currently in production (and with what metrics)
  • History of all versions with training parameters
  • Metadata: dataset, git commit, validation results
  • Lifecycle stage: None → Staging → Production → Archived

MLflow Model Registry — standard. For enterprise — Vertex AI Model Registry (GCP), SageMaker Model Registry (AWS), Azure ML Model Registry.

Model promotion through stages: automatically move model to Staging after successful eval, then manual or automatic (during A/B test) promotion to Production. Rollback — switch to previous Production version in seconds.

Serving: From FastAPI to Triton Inference Server

Simple case. FastAPI + PyTorch/ONNX on one server — 80% of production ML deployments are exactly that. Sufficient for most tasks with load up to 100 req/s.

from fastapi import FastAPI
import onnxruntime as ort

app = FastAPI()
session = ort.InferenceSession("model.onnx", providers=["CUDAExecutionProvider"])

@app.post("/predict")
async def predict(request: PredictRequest):
    inputs = preprocess(request.text)
    outputs = session.run(None, {"input_ids": inputs})
    return {"label": postprocess(outputs)}

Triton Inference Server — production standard for high loads (500+ req/s). Dynamic batching, concurrent model execution, model ensemble. Supports TensorRT, ONNX, PyTorch TorchScript, TensorFlow SavedModel.

KServe — Kubernetes-native ML serving with autoscaling, canary deployments, A/B testing out of the box. Scale-to-zero for inactive models — savings on infrastructure up to 40% annually for a project with 10 models.

Monitoring: Data Drift, Model Drift, Infrastructure Metrics

Monitoring — what is usually done last and regretted first. Three levels.

Infrastructure monitoring. Latency (P50/P95/P99), throughput (req/s), error rate (4xx, 5xx), GPU/CPU utilization. Prometheus + Grafana — standard. Alert when P99 latency > threshold or error rate > 1%.

Data drift monitoring. Distribution of input data changes over time. Detect via PSI (Population Stability Index) for numerical features: PSI > 0.2 — strong drift. Chi-squared test for categorical, Kolmogorov-Smirnov test for continuous. Evidently AI — open source library with ready-made drift tests.

Model drift monitoring. If ground truth is delayed (e.g., we know conversion after a week) — monitor real metrics. If not — surrogate metrics: distribution of prediction scores, proportion of confident predictions.

Alerting. Three levels: INFO (minor drift, log it), WARNING (significant, notify team), CRITICAL (quality dropped below threshold — automatic switch to fallback model).

Why is data drift monitoring important?

Without it, you learn about model degradation only from user complaints or ringing SLA. A drift alert allows you to retrain the model in advance, before errors start causing losses. In one of our projects, PSI monitoring detected drift 2 days after a data source change — this saved the campaign.

Common Mistake Consequences Solution
Lack of data versioning Irreproducible experiments Implement DVC or similar
Manual model deployment Human errors, slow rollback Automate CI/CD pipeline
Monitoring only by business metrics Late drift detection Add data drift monitoring (PSI, KS)

Feature Store

Feature Store solves the training-serving skew problem. If preprocessing during training and inference is implemented in two different places — divergence is inevitable.

A Feature Store is needed when:

  • Several models use the same features
  • Features are computed from streaming data (real-time)
  • Large team with different people on feature engineering and model training

Feast — open source Feature Store. Offline store (S3 + Parquet) for training, online store (Redis, DynamoDB) for low-latency inference. Feature definitions as code, materialization job syncs offline → online.

Tecton (commercial), Vertex AI Feature Store (GCP), SageMaker Feature Store (AWS) — managed options with less ops overhead.

CI/CD for ML

ML CI/CD is regular CI/CD plus specific ML steps.

ML-specific checks in CI:

  • Reproducibility check: run training with a fixed seed, result must match
  • Data validation: Great Expectations or Pandera on schema/distribution checks
  • Model performance check: automatic eval on holdout, block merge if degradation > threshold
  • Latency regression test: inference must meet SLA

GitOps for deployment. Merge to main → CI triggers training → eval → if passes → automatic deployment to Staging → smoke tests → manual promotion to Production or automatic upon successful canary.

Tools: GitHub Actions / GitLab CI for CI, ArgoCD for GitOps deployment on Kubernetes.

What's Included in MLOps Platform Development

We provide a full cycle of work, documentation, and team training.

Stage Duration Result
Audit of current infrastructure and data pipeline 1–2 weeks Roadmap with risks and priorities
Core deployment: MLflow, orchestrator, serving 4–6 weeks Working training and deployment pipeline
Feature Store and CI/CD for ML 2–3 months Feature Store, automatic retrain and deployment
Drift monitoring and alerting 3–4 weeks Dashboards, alerts, incident playbook
Team training and documentation 1–2 weeks Runbook, policies, training for data scientists

Total time from audit to full MLOps platform: 3–5 months. Also possible phased launch: basic level (tracking + serving) in 4–6 weeks.

Cost is calculated individually based on data volume, number of models, and infrastructure requirements. Order an MLOps infrastructure audit — get a roadmap in 1–2 weeks. Contact us for a project assessment — we will send a preliminary estimate within 2 business days.

Note: warranty on architectural solutions — 12 months. We provide integration certificates with major cloud providers (AWS, GCP, Azure). During our work, we have not lost a single client after the first implementation — the experience of 50+ successful MLOps projects speaks for itself. Get a consultation on building an MLOps platform today.