1. Define the comparison first: what are you actually comparing?

1.1 The most common mistake: GPU price against token price

The opening line of almost every self-hosting discussion is some version of: how much is one L40S, and how much is a token? That compares two quantities with completely different units, so the conclusion is guaranteed to be wrong, and systematically wrong in one direction: it understates the fixed costs and the labour, because the GPU price is a one-off number on an invoice while the operations cost never appears on any invoice at all.

The only valid comparison object is what one call actually costs. On the self-hosted side that is monthly total cost of ownership divided by monthly call volume. On the API side it is the sum of the input tokens, the cached input tokens and the output tokens, each priced at its own rate. Reduce both to a cost per call and only then are they comparable.

There is a second, subtler error: counting the hardware and ignoring operations. Self-hosting is not a matter of putting weights on a GPU. It is an online service that needs someone on call, versions that need upgrading, faults that need diagnosing, and driver and framework vulnerabilities that need patching. In early proposals this line is routinely omitted, precisely because it does not arrive with a purchase order.

1.2 The four quantities that run through this article

  • C_self: monthly total cost of ownership of the self-hosted setup, equal to hardware amortisation plus electricity plus colocation plus operator time plus everything else.
  • c_api: the price of a single API call.
  • Q*: the daily call volume at which the two are equal, so C_self equals 30 times Q* times c_api.
  • c_self: the cost of one call on the self-hosted side, equal to C_self divided by 30 times the daily call volume.

These close a loop. Use chapter 5 to work out how much VRAM the model needs and how many concurrent sequences that supports, because that decides which machine you can buy. Use chapter 2 to turn that machine into a monthly cost, because that is C_self. Use chapter 4 to solve for Q*. Compare Q* against your real daily volume and you have your answer.

1.3 Why the two cost structures differ

Pay-per-use API pricing is a pure variable cost: no call, no charge, no floor and no scale effect. Self-hosting is a fixed cost plus a marginal cost close to zero: whether you make one hundred calls a day or a million, the electricity, the colocation fee and the management effort are already committed. Graphed, one is a straight line through the origin and the other is a staircase with a fixed intercept.

DimensionPay-per-use APISelf-hosted
Cost shapePure variable cost, linearMostly fixed cost, near-zero marginal cost
Minimum spendZeroA fixed monthly bill whether you use it or not
Scale effectLinear, noneFixed cost dilutes, marginal cost collapses
Capability ceilingWhatever the vendor exposesHard-limited by VRAM and cluster size
Data residencyLeaves your premises by defaultStays inside
Model iterationFollows the vendorYou own upgrades, regressions and asset depreciation
Failure responsibilityThe platformYou

1.4 Sources and assumptions

Every price and parameter here comes from a public source and is labelled with its origin. Anything that cannot be pinned down publicly is flagged as an assumption and must be replaced with your own numbers before you re-run the script in chapter 10.

  • API prices come from the official DeepSeek pricing page at https://api-docs.deepseek.com/quick_start/pricing, retrieved in November 2026. The vendor states that prices may change, so re-check before committing to a budget.
  • Model architecture parameters come from the checkpoint config.json. DeepSeek-V3 is used as the verifiable worked example.
  • Hardware prices are indicative ranges for the channel market at the time of writing. Treat them as ranges: the formulas are linear in these numbers, so change the price and re-run.
  • The exchange rate is taken as 1 USD = 7.10 CNY and operator time as 35,000 CNY per person-month fully loaded.

2. The TCO model: six line items on the self-hosted side

2.1 Hardware and how to amortise it

Hardware is the largest single line item, but the amortisation convention matters more than the amount. Three points. First, use the whole machine price, not the board price: CPU, memory, NVMe, power supply, chassis and networking all count, and for multi-GPU nodes you cannot skip redundant power and PCIe lanes. Second, amortisation periods differ sharply by class: consumer cards have a much steeper residual value curve, so 24 months is the honest number, while datacentre cards are reasonably amortised over 48 to 60 months. Third, include the fabric: the NVLink or high-speed interconnect between cards is a purchase cost too.

2.2 Electricity is not the GPU power number

The full formula is average power times load factor times PUE times 720 hours times the tariff. Every one of those four coefficients can move the result by more than a factor of two. The load factor is the share of the day the card is actually computing: interactive services often sit at 15 to 40 percent, offline batch pipelines can reach 70 percent or more. PUE is the ratio of datacentre overhead to IT load, and it can be 2.0 for a self-built room against 1.2 to 1.4 for a hosted facility. And the tariff differs between an office desk, a retail meter and a colocation contract.

2.3 Colocation and the desk option

Putting a card on a desk in the office is the most underestimated option there is. There is no rack fee, but there is noise, heat, power cuts, fire risk, and the silent cost of waking a colleague up when they are overtime on release night. Such a machine also has no redundancy, no monitoring and no access control. Once you add these up, colocation is usually both cheaper and less painful than the desk.

2.4 Operator time

Operator time is the line item most often left out entirely, and the one most likely to flip the conclusion. It covers routine inspection and capacity watching, model and framework upgrades, CUDA and driver compatibility maintenance, tuning of the inference engine, incident response, and one neglected but expensive thread: regression testing after every model upgrade. A useful rule of thumb: the minimum viable operational load for one card is 0.1 to 0.2 FTE, and a multi-card cluster with a real SLA usually needs 0.5 to 1 FTE.

2.5 Opportunity cost: what the operator could have been doing

When you price operator time, ask one question: if these 0.3 people were not keeping this cluster alive, what would they be doing? If the honest answer is product work, then that 0.3 FTE should be valued at a product engineer's marginal output, not at the low rate of a support engineer. Many teams estimate this as zero because the work is done by someone who says they are just helping out, when in reality the hours were taken from somewhere else and were never free.

2.6 Depreciation and the resale curve

Self-hosting carries a cost the API side does not have: assets that depreciate as the model generation moves. If you bought to a V4-era specification and the next generation needs more memory or different serving features, the resale value of those cards falls well short of the balance-sheet depreciation. The more common pattern is that official API prices keep falling while the unit cost of your cluster rises, because the cards are depreciating and the operational effort is growing. Always run at least one scenario where the official price drops by half.

Line itemHow it is computedAssumption used here
Hardware amortisationMachine price divided by monthsConsumer 24 months, datacentre 36 to 60 months
ElectricityPower times load times PUE times 720h times tariff0.80 CNY per kWh, PUE 1.2 to 1.5
ColocationSlot plus bandwidth plus power, monthlyDesk 0, hosted 2,500 to 12,000 CNY per month
Operator timeFTE times loaded monthly cost plus incidentals35,000 CNY per person-month
Everything elseStorage, backups, monitoring, model distribution300 to 6,000 CNY per month

3. The API side: what one call really costs

3.1 Read the official rate card correctly

Two model names are live: deepseek-flash, which serves DeepSeek-V4.1-Flash-1017, and deepseek-v4-pro, which serves DeepSeek-V4-Pro-0813. The older deepseek-v4-flash and deepseek-v4-flash-vision-exp names are still accepted, but those models are retired and their requests are handled by V4.1-Flash and billed at the Flash rate. The much older deepseek-chat and deepseek-reasoner aliases were retired on 24 July 2026.

ModelWindowInput, cache missInput, cache hitOutput
deepseek-flashOff-peak$0.15$0.003$0.60
deepseek-flashPeak$0.30$0.006$1.20
deepseek-v4-proOff-peak$0.66$0.022$1.98
deepseek-v4-proPeak$1.32$0.044$3.96

All rates are US dollars per million tokens. Peak hours are 01:00 to 04:00 and 06:00 to 10:00 UTC on weekdays, which is 09:00 to 12:00 and 14:00 to 18:00 in Beijing time, and the peak rate is exactly double the off-peak rate. Peak covers only 35 hours of a 168-hour week, so a load spread evenly across the week pays roughly 21 percent more than the off-peak rate. This detail is routinely missed: customer support, online education and internal assistants all peak during Beijing business hours, which means their real bill has to be estimated close to the peak rate. The vendor also reserves the right to change prices, so re-read the page every time you build a budget.

3.2 The price of a single call

A call is not priced as one number per token. It is the sum of three segments, each at its own rate: input that missed the cache, input that hit the cache, and output.

c_api = (T_in * (1 - r) * p_miss + T_in * r * p_hit + T_out * p_out) / 1000000

That number deserves a pause. At 100,000 calls a day with 4,000 input and 600 output tokens per call, the Flash off-peak bill is a little over ten thousand per month. This is why most self-hosting proposals end after the first line of arithmetic: pay-per-use is simply that cheap in absolute terms, and self-hosting has to compete against a very small number.

3.3 Daily volume times per-call cost is the monthly bill

Calls per dayFlash off-peakFlash peakv4-pro off-peak
1,000104 CNY209 CNY381 CNY
10,0001,043 CNY2,086 CNY3,805 CNY
30,0003,129 CNY6,257 CNY11,415 CNY
50,0005,214 CNY10,428 CNY19,025 CNY
100,00010,428 CNY20,857 CNY38,050 CNY
200,00020,857 CNY41,714 CNY76,101 CNY
500,00052,142 CNY104,285 CNY190,252 CNY
1,000,000104,285 CNY208,570 CNY380,503 CNY

3.4 The two levers that move the number

Cache hit ratio. DeepSeek context caching is automatic and needs no SDK change. Put the stable material first in the prompt, namely the system prompt, tool definitions, few-shot examples and long documents, and the variable material last, and the hit ratio can be pushed past 80 percent. The effective off-peak Flash input rate then falls from $0.15 to roughly $0.018, a saving of about 88 percent.

Peak and off-peak placement. Move batch inference, offline jobs and evaluation runs into the night and over weekends and the bill halves at essentially zero cost. Both of these are free lunches on the API side, and both should be exhausted before you evaluate self-hosting, because they push Q* to the right and make self-hosting harder to justify.

Conversely, if your traffic naturally sits in business hours, the peak and off-peak lever is simply unavailable and the surcharge is a cost you must accept honestly rather than assume away with an idealised average price.

4. The break-even point: turning the argument into a number

4.1 Derivation

The self-hosted side spends C_self every month; the API side spends c_api per call. Self-hosting wins wherever c_self divided by 30 times Q is smaller than c_api, and the boundary is:

Q* = C_self / (30 * c_api)

All three terms move, so Q* is a range rather than a point. The table below splits the monthly bill of six representative configurations and gives the break-even volume for each, followed by the actual GPU utilisation at that break-even volume.

4.2 What the monthly bill is made of

ConfigurationAmortisationPowerColocationOperationsOtherTotal per month
S1 single RTX 4090 24GB on a desk1,16729004,1003005,857
S2 single L40S 48GB hosted2,9172802,5006,45080012,947
S3 4 x L40S 48GB7,2228593,50016,5001,50029,581
S4 single A100 80GB3,7503543,00010,2501,00018,354
S5 8 x H100 80GB43,3333,6298,00043,0004,000101,962
S6 16 x H100 80GB for V3 FP886,6677,07612,00064,5006,000176,243

Note the difference in shape between S1 and S2. On the single-card setups amortisation is only a few thousand, but operations run to 4,100 and 6,450: operations are the largest and most underrated line on a self-hosted bill. On the cluster, amortisation reasserts itself: S6 amortises at 86,667 per month, more than all of its operational cost combined.

4.3 Break-even volume, and a counterintuitive result

ConfigurationQ* at Flash off-peakQ* at Flash peakQ* at v4-pro off-peakGPU utilisation at Q*
S1 single RTX 4090 24GB56,163 per day28,082 per day15,393 per day21.7%
S2 single L40S 48GB124,147 per day62,073 per day34,025 per day23.9%
S3 4 x L40S 48GB283,660 per day141,830 per day77,743 per day13.7%
S4 single A100 80GB175,997 per day87,998 per day48,236 per day40.7%
S5 8 x H100 80GB977,728 per day488,864 per day267,967 per day19.3%
S6 16 x H100 80GB1,690,015 per day845,007 per day463,184 per daynot applicable

The last column is the one to stop on. At the break-even point the GPU is only 14 to 41 percent busy. Self-hosting is almost never constrained by compute; it is constrained by amortisation. The converse also holds: if you bought four cards and only ran them 20 percent of the time, you are not close to breaking even, you will never break even, because you pay for the idle time exactly as you pay for the busy time.

The second counterintuitive result is more counterintuitive still: buying a bigger machine does not move the break-even point to the left, it moves it to the right. S1 breaks even at 28 thousand calls a day and S6 needs 845 thousand, a factor of thirty. The reason is simple. The dominant cost of self-hosting is amortisation, and amortisation is linear in the machine you buy. A larger fixed cost is only worth paying when you genuinely need a large cluster to deliver a capability the API cannot provide. Buying more hardware in the hope of being cheaper optimises the cost structure in exactly the wrong direction.

4.4 Sensitivity: which parameter flips the answer

Using S2, with a monthly cost of 12,947 CNY, and moving one parameter at a time:

ParameterValueAPI price per callQ*
Baseline80% cache hit, 600 output tokens, 7.10 FX0.006952 CNY62,073 per day
Cache hit ratio0%0.013632 CNY31,657 per day
Cache hit ratio50%0.009457 CNY45,632 per day
Cache hit ratio95%0.005700 CNY75,713 per day
Output tokens per call2000.003544 CNY121,759 per day
Output tokens per call2,0000.018880 CNY22,857 per day
Exchange rate6.500.006365 CNY67,803 per day
Exchange rate8.000.007834 CNY55,090 per day

Three things to read out of this. First, output tokens are a stronger lever than call volume: halving output from 600 to 200 nearly doubles Q*, while raising it to 2,000 collapses Q* to 23 thousand calls a day. Reasoning-heavy workloads with long generations are structurally better candidates for self-hosting than extraction workloads with short outputs. Second, the cache hit ratio mainly changes the API price and therefore pushes Q* to the right, so the better your caching, the cheaper pure API is and the harder self-hosting is to win. Third, the exchange rate barely matters and can be ignored, unless your revenue is in dollars while your costs are in renminbi, in which case it belongs in the model explicitly.

There is one more sensitivity you must run yourself: official prices falling. DeepSeek has already repriced the V4 generation more than once, and one large V4-Pro cut was made permanent. Halve the API price and the S2 break-even point moves from 62 thousand to roughly 124 thousand calls a day, which means a self-hosting decision taken on today's prices can invalidate itself within six months. That is not alarmism; it is a reminder that the review cycle for a self-hosting decision should be shorter than the price cycle you expect.

5. The VRAM ledger: KV cache decides what you can run

5.1 First bill: the weights

Weight footprint is the easiest number to compute and one of the easiest to get wrong. The formula is plain: parameter count times bytes per parameter. Three corrections are routinely missed. Quantisation adds scale and zero-point metadata, typically another 3 to 8 percent. MoE checkpoints carry the MTP module and extra per-expert metadata on top of the raw parameter bytes. And VRAM is measured in GiB, not decimal GB, so the paper figure and the card figure differ by about 7 percent.

Parameter countBF16, 2 bytes eachFP8 or INT8, 1 byteINT4, 0.5 byte
671B class MoE, DeepSeek-V31,342 GB671 GB336 GB
70B class dense140 GB70 GB35 GB
32B class dense64 GB32 GB16 GB
14B class dense28 GB14 GB7 GB

This table immediately produces a hard constraint: the FP8 weights of DeepSeek-V3 are about 671 GB, while eight 80GB cards provide only 640 GB. The widely repeated idea of running V3 FP8 on eight cards does not survive arithmetic on paper: the weights do not fit, let alone the KV cache and activations. A workable V3 FP8 deployment starts around ten 80GB cards and becomes comfortable at sixteen, and sixteen H100s change the answer in chapter 4 outright. The lesson is that VRAM is the hard constraint and it decides what you can do before the question of how many cards to buy ever arises.

5.2 Second bill: KV cache, and two formulas you must not mix

KV cache is the part of VRAM most likely to run away, because it grows with both context length and concurrency, and neither appears on a model selection sheet. Two different formulas apply and mixing them is wrong by orders of magnitude.

Plain MHA and GQA models, with L layers, n_kv KV heads, head dimension d_h and b bytes per element:

kv_bytes_per_token = 2 * L * n_kv * d_h * b

The factor 2 is one copy of keys and one of values. For a GQA model n_kv is usually far smaller than the attention head count. A 70B class model with 80 layers, 8 KV heads and head dimension 128 uses 320 KiB per token in BF16. Compute the same model as MHA with 64 heads and you get 2,560 KiB, an eight-fold overestimate. Substituting num_attention_heads for num_key_value_heads is the single most common sizing error in this field.

MLA models, the DeepSeek-V2 and V3 line, take a different route. Instead of caching per-head keys and values, they cache a compressed low-rank latent plus a decoupled RoPE key. The DeepSeek-V2 paper states the total as (d_c + d_h^R) times L elements, with no factor of two, because one latent serves both keys and values:

kv_bytes_per_token = L * (kv_lora_rank + qk_rope_head_dim) * b

Plugging in the real DeepSeek-V3 configuration of 61 layers, kv_lora_rank 512 and qk_rope_head_dim 64 gives 61 times 576, or 35,136 elements per token. In BF16 that is 70,272 bytes, which is 68.6 KiB per token. For contrast, applying the MHA formula to the same model gives 3,904 KiB per token, so MLA actually stores about 1.8 percent of that. Amusingly, this 671B MoE model uses less KV cache per token than a small 8B model does.

5.3 Applying the formula to real context lengths

Context lengthBF16 KV per sequenceFP8 KV per sequenceSequences in a 100 GiB budget, BF16
4,0960.27 GiB0.13 GiB370
8,1920.54 GiB0.27 GiB185
32,7682.14 GiB1.07 GiB46
131,0728.58 GiB4.29 GiB11

This table uses the DeepSeek-V3 MLA layout. Look at the bottom row: a single 128K session eats 8.58 GiB of VRAM in BF16. Three workload shapes therefore have completely different economics. For short questions and answers the KV footprint is negligible. For long document summarisation a single sequence consumes half of a 48GB card. And for a high-concurrency long-context agent cluster, KV cache rather than weights becomes your main cost.

5.4 Third bill: activations and runtime headroom

Beyond weights and KV cache you must reserve runtime headroom: the CUDA context at several hundred megabytes per process, operator workspaces, peak activations, and the NCCL communication buffers in multi-card setups. A working rule is 2 to 4 GiB per card, and more for long contexts with large batches. Skipping this reserve is the classic reason a deployment that worked in testing runs out of memory in production, and it never shows up in a single-request smoke test, only once concurrency rises.

5.5 Quantising the cache, and the tensor parallelism duplication trap

Quantising the KV cache from BF16 to FP8 halves the memory at the cost of accuracy you must verify on your own evaluation set. Note that vLLM uses the fp8_ds_mla format for DeepSeek-style models, which stores scales and keeps the RoPE part in BF16, so the real figure is 39.1 KiB per token rather than the theoretical 34.3.

There is also a trap worth knowing: plain tensor parallelism duplicates the MLA latent. The latent is a single shared vector that ordinary TP cannot shard, so every rank keeps a full copy, and the SGLang documentation states directly that DeepSeek-style models on eight-way TP lead to duplicated KV cache. The fix is data parallel attention, which turns duplication into sharding. For long-context high-concurrency self-hosting this single choice decides whether your ceiling is 11 concurrent sequences or 88.

5.6 Put the formula in a script, not in your head

Hand arithmetic on KV cache is dangerous, because field names and attention layouts differ from model to model. This script reads the checkpoint config and the safetensors header, distinguishes MLA from GQA automatically, and reports the concurrency ceiling:

import json, os, glob

def kv_bytes_per_token(cfg, b):
    layers = cfg['num_hidden_layers']
    if 'kv_lora_rank' in cfg:
        # MLA: one latent serves both K and V, so there is no factor 2
        return layers * (cfg['kv_lora_rank'] + cfg.get('qk_rope_head_dim', 0)) * b
    heads = cfg.get('num_key_value_heads', cfg['num_attention_heads'])
    dim = cfg.get('head_dim') or cfg['hidden_size'] // cfg['num_attention_heads']
    return 2 * layers * heads * dim * b

def weight_bytes(model_dir, b):
    total = 0
    for path in glob.glob(os.path.join(model_dir, '*.safetensors')):
        with open(path, 'rb') as f:
            n = int.from_bytes(f.read(8), 'little')
            header = json.loads(f.read(n))
        for name, meta in header.items():
            if name == '__metadata__':
                continue
            count = 1
            for d in meta['shape']:
                count = count * d
            total = total + count * b
    return total

6. Matching hardware to the shape of the workload

6.1 24GB: the entry tier, which runs but scales badly

A 24GB card, typically a consumer flagship, does one useful thing well: hold the INT4 weights of a 32B class model at about 16 GB, leaving roughly 8 GB for KV cache and runtime. After a 2 GB reserve that leaves about 6 GB, and at 256 KiB per token an 8K context costs 2 GiB per sequence, so the concurrency ceiling is about three sequences. At 32K the same sequence costs 8 GiB and nothing fits at all.

The conclusion is clear. 24GB is right for a development machine, for validating a pipeline, and for low-frequency internal tools. It is not right for anything with a concurrency requirement. Its real value is that it lets you prove the pipeline works at zero cost, and many teams should do exactly that, but they should not read a capacity conclusion into it.

6.2 48GB: the sweet spot of the professional cards

A 48GB card such as the L40S, A40 or L20 holds the INT4 weights of a 70B class model at about 35 GB, leaving 13 GB. After a 2.5 GB reserve, 10.5 GB remains. At 320 KiB per token an 8K context costs 2.5 GiB per sequence, so concurrency is about four; at 32K a single sequence costs 10 GiB and concurrency drops to one.

That contrast defines the character of this tier. 48GB is the best answer for moderate context with low concurrency, and it is not an answer for long context with high concurrency. If your business is long document processing, a machine in this class hits its concurrency ceiling immediately.

6.3 80GB: the entry point for capability and long context

An 80GB card such as the A100 80GB or H100 80GB holds the INT8 weights of a 70B class model at about 70 GB, leaving 10 GB. After a 2.5 GB reserve, 7.5 GB remains, and with an FP8 KV cache at 160 KiB per token an 8K context costs 1.25 GiB per sequence, so concurrency is about six. At 32K a sequence costs 5 GiB and concurrency is back to one.

The value of this tier is not concurrency but capability ceiling. It is the threshold at which one card can hold a large model and can hold a long context at all, and it is where the discussion of DeepSeek-V3 begins, even though V3 FP8 needs ten to sixteen 80GB cards to fit.

6.4 Three workload shapes, three different economics

Offline batch. Throughput matters, latency does not, and queueing is acceptable. The GPU can run near 100 percent of the time, so the load factor approaches one and power becomes a smaller share of the bill; long contexts can be drained slowly. This shape suits self-hosting best, because it dilutes fixed cost maximally and it is insensitive to tail latency.

Interactive chat. Latency matters and traffic is bursty. Daytime peaks and near-idle nights push the load factor to 20 or 30 percent, which roughly doubles the unit cost. You also have to reserve VRAM for peak concurrency, and that VRAM sits idle overnight. Interactive is the least suitable shape for self-hosting, because its traffic curve fights the shape of a fixed cost.

Long context and agents. A single sequence consumes a large slice of VRAM, and agent tasks are often multi-turn long conversations where the KV cache keeps growing. This shape has the ugliest memory economics, but it also has the strongest reason to self-host, because it satisfies two conditions at once: the data is sensitive and the context length amplifies the per-call API price.

6.5 The matching table

Memory tierRepresentative cardTypical modelConcurrency at 8KConcurrency at 32KBest fit
24GBRTX 4090 class32B INT4about 30Development, validation, low-frequency internal tools
48GBL40S, A40, L2070B INT4about 41Offline batch, medium-context services
80GBA100 80G, H100 80G70B INT8about 6 with FP8 KV1Long context, capability-first services
141GBH200large model, FP8 shardedsubstantially higher3 to 5Multi-tenant, high-concurrency long context

Note that these concurrency figures assume full context length. In practice most requests are much shorter, so real concurrency is usually higher. The reverse also holds: if every request in your workload is long, size on the worst case, using the P95 context length multiplied by peak concurrency, plus 20 percent headroom.

7. The decision matrix: daily volume against data sensitivity

Combine the break-even volume from chapter 4 with the memory constraints from chapter 5 and you get a table you can take straight into a meeting.

Calls per dayData not sensitiveData sensitive or cannot leave the premises
Below 5,000Pure API. Fixed cost never amortises at this volume, so every self-hosted option loses money outrightPure API with strict sanitisation. If compliance forbids egress entirely, self-host and accept the cost disadvantage
5,000 to 50,000Pure API. Use the Flash off-peak tier with caching and scheduling; the monthly bill stays in the low thousandsHybrid. The sensitive subset runs locally, everything else stays on the API. This is the most common landing point
50,000 to 500,000Borderline. Compare real volume against Q*: below Q* use the API, above Q* consider self-hostingMostly hybrid. Local infrastructure carries the sensitive, high-frequency portion; start with a small cluster
Above 500,000Self-host. Provided throughput testing passes and somebody genuinely owns the operationSelf-host. At this point compliance and stability drive the decision and cost is no longer the main constraint

7.1 Hybrid is the fourth option people forget

Most teams choose between all API and all self-hosted, but the option that actually fits a business is usually a third one: sensitive data goes local, ordinary traffic goes to the API. It lets you solve the hardest problem with the smallest cluster, because the local side only has to carry the 20 percent of requests that are genuinely sensitive and genuinely frequent. One 48GB card may well be enough for that, while the other 80 percent keeps enjoying the zero fixed cost and the elasticity of the API. Routing is usually decided along two axes, data sensitivity and expected context length:

if doc_has_sensitive_fields or est_context_len over 100000:
    route_to_local(model_id, prompt)
else:
    route_to_api(model_id, prompt)

A side effect of the hybrid approach is regularly underestimated: it lets you build the engineering capability gradually. A great many self-hosting failures are not arithmetic mistakes; they are first attempts where the team switched everything at once and had no choice but to roll back. A hybrid architecture lets you build model deployment, memory tuning and monitoring without carrying that risk.

7.2 Signals that it is time to migrate from API to self-hosted

Three signals deserve attention. The monthly API bill has stayed above the monthly cost of the candidate configuration for three consecutive months, and note the word stayed: one expensive month is not a trend. Compliance starts requiring data to land on disk and be auditable, which adds a cost to the API option you were not previously counting. And your output token lengths are growing steadily, because output tokens move the break-even point far more than input volume does, as section 4.4 showed.

8. Failure modes: six ways to get the numbers wrong

Failure modeSymptomRoot causeHow to avoid it
Underestimating KV cache, OOM at launchLoad tests pass, production OOMs as concurrency risesUsing attention heads instead of KV heads, or ignoring that plain TP duplicates the MLA latentUse the script in section 5.6 against the real config.json and reserve 2 to 4 GiB per card
Counting hardware and ignoring operationsThe proposal looks 30 percent cheaper per call and overruns every monthTreating operations as something done on the side, never converted into FTEBudget 0.1 to 1 FTE and list model upgrades and regression testing separately
Asset depreciation after a model generation shiftTwo years later the self-hosted unit cost exceeds the API price and the cards will not sell for muchAmortising on the accounting schedule without reference to the secondary marketUse a conservative period and run the scenario where official prices fall by half
Ignoring peak and off-peak placementThe bill comes in close to double the estimateEstimating the whole period at the off-peak rateWeight by the share of traffic inside the peak window; support workloads sit almost entirely inside it
Ignoring tail latency and queueingThe arithmetic works but users report thirty second waitsCounting aggregate throughput without looking at P99 latency or queue depthLoad testing must report P99, not average throughput
Underestimating the reverse cost of compliance and securityThe cluster is rejected by the security team and the project slips two monthsLeaving access control, audit, patching and key management out of the modelGet a security review before the arithmetic, not after

8.1 The first way to die deserves expanding

Passing load tests and then running out of memory in production is almost always the same cause: load tests used short contexts and production uses long ones. KV cache grows linearly with context, so moving from 8K to 32K quadruples the memory demand, and raising concurrency from 8 to 64 multiplies it again. The sneakier variant is that every test request shares the same prefix, so prefix caching keeps the KV footprint far below reality; the moment prefixes diversify and the hit rate drops, the OOM arrives.

8.2 The second way to die: treating operations as zero

The most common error is estimating operations as one hour a week. The reality is a weekly upgrade cycle, a monthly security patch, a full regression after every model upgrade, every alert that has to be triaged, and the driver incompatibilities that appear without warning. Add those up and you land at 0.1 to 0.4 FTE for a small single-card cluster. If your proposal leaves this line empty, it is not a self-hosting proposal, it is unassigned operational debt.

9. A full worked example

9.1 The setup

A company builds an internal knowledge base assistant. The shape: 30,000 calls a day, 4,000 input tokens per call of which roughly 80 percent is a stable system prompt and knowledge base prefix that can be cached, 600 output tokens per call, traffic concentrated in business hours from 09:00 to 18:00, peak concurrency 15, and data that is sensitive enough that it cannot leave the premises.

9.2 The API bill

Assume Flash, and because the traffic lands inside the peak window, price it as peak. Input that misses the cache is 4,000 times 0.2, or 800 tokens, costing 800 times 0.30 over a million, which is 0.00024 dollars. Cached input is 3,200 tokens, costing 3,200 times 0.006 over a million, which is 0.0000192 dollars. Output of 600 tokens costs 600 times 1.20 over a million, which is 0.00072 dollars. The total is 0.0009792 dollars per call, about 0.00695 CNY, and the monthly bill is 30,000 times 30 times 0.00695, or about 6,257 CNY. Shifting the same volume entirely out of the peak window would cost 3,129 CNY, which is the entire value of the scheduling lever.

9.3 The self-hosted bill

Start with memory. Suppose the local deployment runs a 32B class model in INT4, so 16 GB of weights, an 8K context and 256 KiB per token of KV cache. A 48GB card has 32 GB left after the weights, 29 GB after a 3 GB runtime reserve, 2 GiB per sequence, which gives a concurrency ceiling of about 14 sequences. That just covers the peak of 15, which is a tight fit. At a 32K context each sequence costs 8 GiB and concurrency drops to three, which does not work.

So a single L40S 48GB is the minimum acceptable machine. S2 costs 12,947 CNY per month, which is 0.0144 CNY per call, or 2.07 times the Flash peak price. S1, a single RTX 4090 on a desk, costs 5,857 CNY per month, or 0.0065 CNY per call, which is 0.94 times the API peak price and looks like an exact tie. But the 24GB card supports only about three concurrent sequences and cannot carry a peak of 15, so the comparison that mattered was never affordable.

9.4 The conclusion, and its sensitivity

The answer is hybrid: run two to four L40S cards carrying the sensitive, high-frequency requests, which lands around the S3 figure of 29,581 CNY per month, and let the rest stay on the API. At the same time do three things that cost nothing: restructure the stable prefix so the cache hit rate passes 90 percent, move batch and evaluation jobs to the night, and squeeze output length below 400 tokens.

Then run the sensitivities. If the cache hit rate falls to 50 percent, the S1 break-even point drops from 28 thousand to 46 thousand calls a day and self-hosting loses outright. If output grows from 600 to 2,000 tokens, Q* falls to 23 thousand and self-hosting loses outright. If official prices fall by half, Q* doubles. Any one of those three parameters alone flips the conclusion, which is exactly why this kind of decision has to be recomputed by script on a schedule rather than settled once in a meeting.

10. Scripts and configuration you can reuse

10.1 The cost model as a script

Turn chapter 4 into code and change a few lines at the top to match your own prices, hardware and exchange rate. This version runs as is:

#!/usr/bin/env python3
# Break-even calculator: self-hosted versus pay-per-use API.
USD_CNY = 7.10          # exchange rate, use your own settlement rate
SALARY = 35000.0        # fully loaded senior inference engineer, per person-month
HOURS = 720             # hours per month

# Official rates, https://api-docs.deepseek.com/quick_start/pricing , retrieved 2026-11
# (input miss, input hit, output) in USD per 1M tokens
PRICE = {
    'flash': {'off': (0.15, 0.003, 0.60), 'peak': (0.30, 0.006, 1.20)},
    'pro': {'off': (0.66, 0.022, 1.98), 'peak': (1.32, 0.044, 3.96)},
}

def api_call_usd(model, tier, tin, tout, hit=0.0):
    pm, ph, po = PRICE[model][tier]
    return (tin * (1 - hit) * pm + tin * hit * ph + tout * po) / 1e6

HW = {
    'S1 1x4090 24G': dict(hw=28000, amort=24, gpu_kw=0.45, host_kw=0.25,
                          load=0.60, pue=1.20, kwh=0.80, colo=0,
                          fte=0.10, opsx=600, extra=300),
    'S2 1xL40S 48G': dict(hw=105000, amort=36, gpu_kw=0.35, host_kw=0.25,
                          load=0.60, pue=1.35, kwh=0.80, colo=2500,
                          fte=0.15, opsx=1200, extra=800),
}

def tco(c):
    amort = c['hw'] / c['amort']
    kw = (c['gpu_kw'] + c['host_kw']) * c['load'] * c['pue']
    elec = kw * HOURS * c['kwh']
    ops = c['fte'] * SALARY + c['opsx']
    total = amort + elec + c['colo'] + ops + c['extra']
    return dict(amort=amort, elec=elec, colo=c['colo'], ops=ops,
                extra=c['extra'], total=total)

def break_even_qpd(c, unit_cny):
    return tco(c)['total'] / (30 * unit_cny)

if __name__ == '__main__':
    TIN, TOUT, HIT = 4000, 600, 0.8
    for name, c in HW.items():
        t = tco(c)
        out = [name, 'total=%.0f' % t['total']]
        for key in ('flash_off', 'flash_peak', 'pro_off'):
            m, tier = key.split('_')
            u = api_call_usd(m, tier, TIN, TOUT, HIT) * USD_CNY
            out.append('%s=%.0f/day' % (key, break_even_qpd(c, u)))
        print(' | '.join(out))

10.2 Serving flags must match the memory ledger

The numbers you computed have to map directly onto serving flags. The command below matches the worked example in chapter 9: context reduced from 32K to 8K, INT4 weights leaving room for about 14 concurrent sequences, and memory utilisation set to 0.92.

vllm serve /models/model-int4 --tensor-parallel-size 2 --max-model-len 8192 --gpu-memory-utilization 0.92 --kv-cache-dtype fp8 --max-num-seqs 14 --enable-prefix-caching

After startup, check two lines in the log: the total token count of the KV cache, and the maximum concurrency implied by the configured context limit. Those two lines are the ground truth for your memory ledger and are more reliable than any estimating script. Set the flags too high and vLLM refuses to start, complaining that the maximum sequence length exceeds what the KV cache can hold; set them too low and you leave VRAM on the table.

10.3 Make verification part of the routine

Three checks belong on a monthly cadence rather than in a one-off project. First, confirm the live rate card before each budgeting round:

curl -sL https://api-docs.deepseek.com/quick_start/pricing -o pricing.html
python - <<'PY'
import re
h = open('pricing.html', encoding='utf-8', errors='ignore').read()
print(sorted(set(re.findall(r'[$][0-9.]+', h))))
PY

Second, read the real token consumption from the usage field returned by the API. A break-even point computed from estimated token counts is not a break-even point.

from openai import OpenAI
import os
client = OpenAI(api_key=os.environ['DEEPSEEK_API_KEY'],
                 base_url='https://api.deepseek.com')
resp = client.chat.completions.create(model='deepseek-flash',
                                      messages=msgs)
print(resp.usage.prompt_tokens, resp.usage.completion_tokens)

Third, watch the local side for KV cache pressure and queue depth. A KV utilisation rate pinned near 100 percent means concurrency has already hit the ceiling, and the requests now arriving will queue, taking tail latency with them.

curl -s localhost:8000/metrics | grep -E 'vllm:(gpu_cache_usage_perc|num_requests_running|num_requests_waiting)'

11. Boundary conditions and where this method does not apply

11.1 Where the model breaks down

  • Training and fine-tuning is a different ledger at a different scale, priced in card-hours rather than calls. None of the formulas here apply.
  • Edge and on-device deployment has no colocation, no professional operations and no amortisation period. Every fixed cost line has to be rewritten.
  • If the GPU already exists and was not bought for this project, the amortisation line should become an opportunity cost, meaning what the card could earn rented out. That changes the conclusion materially.
  • When capability cannot be substituted and you need 671B class reasoning quality while the API offers models far beyond what you can afford to host, this is not a cost question. Choose on capability.

11.2 Where the error comes from

Source of errorTypical magnitudeHow to tighten it
Actual hardware purchase priceplus or minus 20%Quote at least three channels
Tokens per callplus or minus 25%Histogram the usage field and take P95
Cache hit ratioplus or minus 20%Measure a week of production traffic
Load factor and PUEplus or minus 15%Take it from the facility invoice or a power meter
Operator timeplus or minus 40%Log actual hours spent each week
Throughput and concurrencyplus or minus 30%Load test. Vendor peak numbers are not a substitute
Amortisation period and residual valueplus or minus 25%Use 24 months as the conservative assumption

11.3 A printable decision checklist

Walk through these ten questions and the answer usually falls out:

  1. For the model we want to host, what are the layer count, the KV head count or the MLA latent width, and how many bytes of KV cache per token?
  2. Adding weights, KV cache and runtime headroom, how much VRAM do we need at target concurrency, and how many cards does that take?
  3. What is the monthly cost of that machine, and how much of it is operations? Who does the work and how many hours a week?
  4. With our current call shape and cache hit ratio, what is the break-even volume Q*, and how far are we from it?
  5. When does our traffic land, and what share of it falls inside the peak window?
  6. If official prices fall by half, does the conclusion survive?
  7. If the model needs to move up a size, will the cards we bought still be usable?
  8. How long can the business tolerate an outage of this machine, and who is on call?
  9. Has this cluster been through our internal security review?
  10. Is there something cheaper than buying hardware: better caching, rescheduling, hybrid routing, or simply not changing anything?

12. Summary

The whole argument compresses into three statements.

First, the only valid comparison between self-hosting and API is the full cost per call. Hardware is one part of that ledger, and operations, colocation, electricity and asset depreciation together usually add up to the same order of magnitude. Any conclusion that skips those lines is not a conclusion.

Second, the break-even point of self-hosting is set by fixed cost, not by compute. Across the six configurations here, GPU utilisation at the break-even point is only 14 to 41 percent. A bigger machine therefore does not make self-hosting pay back sooner, it pushes Q* further to the right and only slows the loss. Self-hosting pays off when you already have a workload large enough to dilute fixed cost and busy enough to keep the hardware warm.

Third, the only things you can actually quantify are the memory ledger and the bill, and they are the same problem. The two KV cache formulas decide how much concurrency you can hold; Q* decides whether holding it is worth it; and three variables, operator time, peak placement and cache hit ratio, push those two numbers in opposite directions at the same time.

So the order of operations should be this. Do the things in chapters 3 and 5 that cost nothing, namely restructure the cached prefix, reschedule batch jobs to the night, and read the real usage figures. Then see where Q* lands. Only when the volume genuinely crosses Q* and the data genuinely cannot leave the premises, or the capability genuinely only comes from hardware you can afford, is self-hosting the right call. Most teams satisfy neither condition, and for them the API plus good caching and scheduling is the optimal answer.

One practical closing note: turn this calculation into a script you re-run every quarter rather than a table that sits in a document. API prices change, models change, hardware residual values change and traffic changes, and only a ledger that updates itself stays valid as they do.