AiCredits
TCO guide

Self-Hosting vs API Gateway: Total Cost of Ownership for Small Teams

A practical TCO framework for small teams choosing between self-hosted DeepSeek and an API gateway, with runnable code to measure, model, and route.

Published 2026-10-19 Updated 2026-10-19 7 min

Every self-hosting pitch starts the same way: stop renting tokens, buy a GPU, and the marginal cost of inference collapses to the price of electricity. For a small team shipping on a single API key, that arithmetic rarely survives contact with a real traffic curve — not because the hardware is bad, but because the cost structure is inverted. A gateway bills you for what you use. A GPU bills you for what you could use, every hour of every day.

The useful answer to "should we self-host DeepSeek?" is a single derived number: the average utilization your hardware would see over a month. Operations time, model upgrades, and high availability are multipliers stacked on top of it. Below is how to compute that number from your own logs, how to model the break-even, and why most small teams end up with a hybrid.

The four cost buckets that actually decide it

Self-hosting and per-token billing fail in opposite directions. One is cheap when you are saturated and expensive when you are quiet; the other tracks demand exactly, including the demand you cannot forecast. Four buckets separate them:

  • Fixed compute, accrued hourly. GPU rental or amortized purchase, power, cooling, and rack space cost the same at 3 a.m. on Sunday as at Monday peak. This is the bucket that punishes small teams, because demand is never flat.

  • Idle capacity is the default state. Staging, evaluation runs, night-time troughs, and weekend lulls all sit on the same reserved capacity. If you provision for peak, your average utilization is far below the peak you sized for.

  • Operations labour. Serving stacks need driver and CUDA alignment, quantization choices, out-of-memory debugging, autoscaling policy, metrics, and security patching. A few hours a week is still a recurring line item, and it lands on your most expensive engineer.

  • The upgrade treadmill. Every new checkpoint means re-quantizing, re-running your evaluation set, and redeploying. Through a gateway that is a model string change; on your own box it is a release with a rollback plan.

  • The redundancy tax. Production high availability means at least two nodes. That doubles fixed cost and halves the effective utilization of your real demand.

When self-hosting genuinely wins

Self-hosting is not wrong — it is conditional. It wins when the hardware is busy for reasons you control:

  • Throughput-bound, queueable work: overnight embedding backfills, batch classification, synthetic data generation, log triage. You keep the GPU busy by scheduling jobs, not by waiting for users.

  • A residency or sovereignty requirement that a contract cannot satisfy, such as regulated data that may not leave your network.

  • Custom weights, custom kernels, or a fine-tune that no hosted endpoint exposes.

  • Air-gapped or offline operation, where a network call is simply not an option.

  • Existing GPU infrastructure you already run, so the fixed cost is shared with other workloads.

When the gateway wins

The gateway wins in the mirror image of those conditions. If demand is spiky, unproven, or dominated by interactive product traffic, reserved capacity is the wrong shape for it. Pre-product-market-fit usage is the worst possible fit: you pay for a peak that lasts twenty minutes a day.

It also wins on the constraint small teams feel most — engineer attention. Every hour spent debugging a serving stack is an hour not spent on the product. And a gateway lets you move between a fast default and a stronger model per request without a redeploy.

That trade is what AiCredits is built around. It exposes an OpenAI-compatible endpoint where deepseek-v4-flash handles high-volume work and deepseek-v4-pro is there when a request needs more reasoning. Off-peak usage costs less than peak, cache hits cost less than misses, and pro costs more than flash — current rates are on aicreditsapi.com/pricing. Top-ups take an international card or PayPal, with no Chinese phone number or bank account required.

Step 1 — log your real workload

Cost arguments go wrong when they use vendor throughput figures instead of your own token distribution. Log every call for two weeks: model, prompt and completion tokens, cache hits, and a feature tag. That log becomes the shared input for both sides of the comparison — and it is the only way to know what your average request actually costs.

import json
import os
import time

from openai import OpenAI

client = OpenAI(
    api_key=os.environ["AICREDITS_API_KEY"],
    base_url="https://api.aicreditsapi.com/v1",
)
LOG = "llm_usage.jsonl"


def tracked_chat(prompt: str, model: str = "deepseek-v4-flash", tag: str = "general") -> str:
    resp = client.chat.completions.create(
        model=model,
        messages=[{"role": "user", "content": prompt}],
        temperature=0.2,
    )
    usage = resp.usage
    row = {
        "ts": int(time.time()),
        "tag": tag,
        "model": model,
        "prompt_tokens": usage.prompt_tokens,
        "completion_tokens": usage.completion_tokens,
        "cache_hit_tokens": getattr(usage, "prompt_cache_hit_tokens", 0) or 0,
    }
    with open(LOG, "a", encoding="utf-8") as fh:
        fh.write(json.dumps(row) + "\n")
    return resp.choices[0].message.content


def report(path: str = LOG) -> None:
    with open(path, encoding="utf-8") as fh:
        rows = [json.loads(line) for line in fh if line.strip()]
    if not rows:
        print("no calls logged yet")
        return
    tokens = sum(r["prompt_tokens"] + r["completion_tokens"] for r in rows)
    print(f"{len(rows)} calls, {tokens} tokens, {tokens / len(rows):.0f} tokens/call")
    by_tag: dict[str, int] = {}
    for r in rows:
        n = r["prompt_tokens"] + r["completion_tokens"]
        by_tag[r["tag"]] = by_tag.get(r["tag"], 0) + n
    for tag, n in sorted(by_tag.items(), key=lambda kv: -kv[1]):
        print(f"  {tag:<12} {n}")


if __name__ == "__main__":
    tracked_chat(
        "Write a Python function that retries an HTTP request with jittered exponential backoff.",
        tag="codegen",
    )
    report()

Step 2 — compute your break-even utilization

Break-even is not a price comparison; it is a utilization threshold. Divide your fixed monthly hardware cost by the product of your blended gateway cost per token and your measured monthly token capacity. The result is the average utilization you must sustain for self-hosting to be the cheaper option — after which you add the HA multiplier and ops hours. Pull every input from your own logs and your own benchmark, never from a vendor slide.

import os

# Every input comes from your own logs and your own benchmark.
FIXED_MONTHLY = float(os.environ["SELFHOST_MONTHLY_COST"])   # GPU + power + rack, amortized
TOKENS_PER_SEC = float(os.environ["MEASURED_TOKENS_PER_SEC"])  # your prompts, your stack
GATEWAY_SPEND = float(os.environ["GATEWAY_MONTHLY_SPEND"])
GATEWAY_TOKENS = float(os.environ["GATEWAY_MONTHLY_TOKENS"])

HOURS_PER_MONTH = 730
CAPACITY = TOKENS_PER_SEC * 3600 * HOURS_PER_MONTH
UNIT = GATEWAY_SPEND / GATEWAY_TOKENS
BREAK_EVEN_UTIL = FIXED_MONTHLY / (UNIT * CAPACITY)
CURRENT_UTIL = GATEWAY_TOKENS / CAPACITY

print(f"hardware capacity : {CAPACITY:,.0f} tokens/month")
print(f"your demand       : {GATEWAY_TOKENS:,.0f} tokens/month ({CURRENT_UTIL:.1%} of capacity)")
print(f"break-even at     : {BREAK_EVEN_UTIL:.1%} average utilization")

if CURRENT_UTIL < BREAK_EVEN_UTIL:
    print("verdict: gateway wins — you would be paying for idle silicon")
else:
    print("verdict: worth a pilot, but re-run with two HA nodes in FIXED_MONTHLY")

Step 3 — route per request, not per company

The hybrid most small teams converge on: default everything to the cheap, fast model and escalate only when a request shows signals of difficulty — long context, multi-step reasoning verbs, debugging. Then fall back to flash if the escalation fails, so a stronger-model incident never becomes a product outage.

import os
import re

from openai import OpenAI

client = OpenAI(
    api_key=os.environ["AICREDITS_API_KEY"],
    base_url="https://api.aicreditsapi.com/v1",
)

HARD = re.compile(r"\b(prove|derive|why does|debug|root cause|architect|migrate|trade-?offs?)\b", re.I)
SYSTEM = "Be concise and concrete. Show code when it helps."


def pick_model(prompt: str) -> str:
    if len(prompt) > 6000:
        return "deepseek-v4-pro"
    if HARD.search(prompt):
        return "deepseek-v4-pro"
    return "deepseek-v4-flash"


def _chat(model: str, messages: list[dict]) -> str:
    resp = client.chat.completions.create(model=model, messages=messages, temperature=0.2)
    return resp.choices[0].message.content


def ask(prompt: str) -> str:
    model = pick_model(prompt)
    messages = [{"role": "system", "content": SYSTEM}, {"role": "user", "content": prompt}]
    try:
        return _chat(model, messages)
    except Exception:
        if model == "deepseek-v4-flash":
            raise
        return _chat("deepseek-v4-flash", messages)


if __name__ == "__main__":
    print(ask("Draft a three-line release note for a fix that stops duplicate webhook deliveries."))

Two practical notes. Keep the routing rule in one function so you can A/B it against always-pro on a labelled evaluation set before you trust it. And keep the model string at the call site, not buried three config layers down, so moving between gateway and self-hosted stays a one-line change in either direction.

TCO at a glance

DimensionSelf-hosted DeepSeekAPI gateway (AiCredits)
Upfront commitmentReserved GPU, setup, and validation workNone — pay for tokens used
Marginal cost at low volumeHigh, because fixed cost is spread over little trafficLow, and it tracks traffic exactly
Marginal cost when saturatedLower per tokenFixed per-token rate
Time to first requestDays to weeksMinutes
Model upgradesRe-quantize, re-validate, redeployChange the model string
Peak handlingProvision for peak and idle off-peakBurst within rate limits
Ops burdenOngoing, and entirely yoursVendor-managed
Best fitBatch, regulated, saturated workloadsProduct teams with spiky or unproven traffic

The right question is not what a token costs. It is what fraction of the month your GPU spends doing paid work — and what you pay an engineer to keep it that way.

A pre-commit checklist

  • Run the token log for at least two weeks, covering both your worst traffic day and your quietest.

  • Benchmark throughput on the exact serving stack and quantization you would deploy, using your own prompt lengths rather than a generic throughput claim.

  • Add the HA node multiplier and an honest ops-hours estimate before comparing totals.

  • Define the evaluation set now — it is the only way to prove a migration did not quietly degrade quality.

  • Keep the call site model-agnostic (base URL plus model string) so the decision stays reversible.

FAQ

Is self-hosting DeepSeek cheaper at low volume?

Almost never. At low volume the fixed hourly cost of reserved hardware dominates, and you also pay setup and operations time. Run your logged token volume through the break-even script before assuming otherwise.

What utilization should trigger a move to self-hosting?

Your own break-even number, not an industry rule of thumb. It depends on your hardware cost, your measured throughput with your prompt mix, and your blended gateway rate. If your sustained average sits comfortably above that threshold with headroom for peaks, pilot it.

Do I need two GPUs for production?

For anything with an uptime commitment, yes — a single node is a single point of failure. Budget the second node into the fixed cost, and remember it halves the effective utilization of your demand.

Can I start on a gateway and self-host later?

Yes, and that is usually the right order. Keep an abstraction at the call site, keep logging tokens, and keep an evaluation set. The migration cost is mostly re-validation, not code.

Does prompt caching change the maths?

It changes the variable side only. Cache hits are cheaper than misses, so keeping stable prefixes — system prompt, retrieved documents, tool schemas — at the front of the message list lowers cost per call. The fixed-versus-variable structure of the decision stays the same.

How does AiCredits fit into this?

It is an OpenAI-compatible gateway for DeepSeek models: deepseek-v4-flash as the default, deepseek-v4-pro for requests that need more reasoning, with card or PayPal top-ups and no Chinese phone number or bank account. Rates are listed at aicreditsapi.com/pricing.

Try Lint in 2 seconds

Wrote something? Paste it here for a free grammar check. No account needed.

More Tools →

Related Tools

💻Code Explainer

Was this article helpful?

| Share on X Reddit Copy link

服务器宕机了?别等用户告诉你

Wakeless 梦哨 帮你 30 秒监控网站 / API / SSL 证书,宕机秒级告警到邮箱、飞书、Slack。免费档 30 个监控,永久免费,无需信用卡。

免费开始监控 →
💬
反馈意见 / Feedback ×