1. Start by asking the right question: this is not a binary choice

The question "should we self-host DeepSeek or call the API" is almost always framed incorrectly. It sounds like a two-way multiple-choice question, so teams line up the two vendors' price sheets, parameter tables and latency figures, argue for two hours, and let the loudest person decide. The actual question is different: given your data boundary, your workload shape and your resource constraints, which service topology is the default for this stage, and which cases need an exception.

That sounds like semantic hair-splitting, but it changes two very concrete things. First, it turns topology from a one-time choice into a continuous decision that changes with stage: for the same team, the best answer during exploration, during scale-up and during a compliance audit can be three different answers. Second, it moves the discussion away from "whose numbers look better" and towards "what are my constraints" - and the former is vendor marketing while the latter is your own fact.

Three flawed framings

  • Framing one: compare unit prices.Put the API price per million tokens next to the self-hosted depreciation per card and compare. This almost always produces a wrong answer, because the two cost structures are not the same kind of object: the API side is a variable cost that floats with usage, the self-hosted side is a fixed cost you pay whether you use it or not. Dividing one by the other compares a hallucination.
  • Framing two: compare "privacy".Assume that "data must not leave the network" means "we must self-host". That skips the middle ground: sensitive traffic can go down the local path while ordinary traffic goes to the API. Unless every single workload is sensitive, "compliance" usually points at a hybrid, not at a binary.
  • Framing three: compare team preference."Our team already knows the serving stack, so self-hosting is cheaper for us." That is an argument about existing skills, not about constraints. It can be valid, but it has to yield to the data boundary and the workload shape rather than competing with them.

Why this question cannot be answered offline

At least five variables can flip the answer, and not one of them is decided unilaterally by the engineering team: whether data is bound by contract, regulation or customer commitment; daily volume and peak-to-average ratio; available GPU budget and rack power; the operations headcount you can actually commit (especially the person who gets paged at 3am); and where the business is heading over the next six to twelve months. List those five and you realise that "local versus API" is not a technology-selection question at all. It is a constraint-solving problem. An answer that flips when constraints change is normal behaviour, not a sign that somebody was wrong.

What this article delivers

Three artefacts: a three-question decision tree, an executable matrix mapping condition combinations to actions, and a set of hybrid-architecture design rules - how to route, how to keep versions aligned, how to fail over, and how to observe the real cost of both paths. There is also a reverse path that is routinely ignored: migrating from self-hosted to API is often more common than the other direction, because during exploration the model moves fast and API versions and behaviours change under you, whereas the fixed cost of self-hosting only becomes attractive once stability, compliance and concurrency all mature.

2. The three-question decision tree: data, workload, resources

Compress those variables into three mandatory questions, each with a criterion that can actually be answered unambiguously. The order matters and cannot be reordered: ask about data first because it is the hardest constraint and no other answer can override it; ask about workload next because it determines the cost shape; ask about resources last because it determines whether you are even eligible to execute the recommendation the first two questions produce.

Question one: can the data leave the network, and where is the compliance line

This cannot be answered by a discussion about whether your data "counts as sensitive". It has to be answered by listing fields. Decompose the request body into a field inventory and annotate each field: does it contain personal information; does it fall outside the customer's granted scope; is it bound by contract terms such as data-processing agreements or regional restrictions; does it carry regulated-industry information. Once you annotate, the boundary usually becomes visible on its own.

  • Boundary A: everything is sensitive.Any field may trigger an obligation, so the whole path must stay inside a controlled environment. The API side is then only usable for offline evaluation with no real data attached.
  • Boundary B: some fields are sensitive.Only a minority of fields are restricted - ticket bodies, identity data, transaction details - while the rest are free. Boundary B is where hybrid architectures live. The whole point of the routing layer is to separate restricted from free fields before the request reaches any model, rather than sending everything and trusting the provider not to log it.
  • Boundary C: no constraints.No contractual or regulatory obligations, data may leave the network, and compliance is not a blocker. Move straight to question two.

The executable form of the criterion is simple: can you write down the list of fields that must not leave the network? If you cannot, the compliance boundary has not been defined yet, and whichever topology you pick will fail the first audit question - "what exactly did this request send out?" - which is the hardest and least repairable problem in this entire area.

Question two: what are the daily volume and the workload shape

Question two needs four numbers: daily request volume Q, average input length L, average output length O, and the peak-to-average ratio r. Of these, the peak-to-average ratio changes the conclusion more than the total does, because local capacity is bought to cover the peak while API capacity is rented as a function of usage.

  • Shape one: steady.Ratio close to one, volume stable. The fixed cost of self-hosting is spread evenly, which is one of the most favourable conditions for it.
  • Shape two: spiky.The ratio is far above one and the peak may be a multiple of the average. Keeping hardware resident for a few hours of peak is enormously wasteful, and spiky traffic is precisely where pay-per-use wins. Unless "peak-window data must stay on premises" is itself a hard constraint, this shape almost always favours the API.
  • Shape three: long-tail offline.Requests can wait for hours, arrive in large batches and are replayable. This is the shape most suited to self-hosting: the hardware can serve a dedicated batch queue without competing with the online service, and the cost of retrying after a failure is low.

There is one more quantity that is easy to miss: whether requests are replayable. Replayable traffic permits aggressive degradation and retries - even several re-sends after an API timeout. Requests with side effects (writing a database, sending a message, charging a card) are in a completely different category, and the tolerance budget for failure is not the same order of magnitude. That difference changes the failover design in section 9.

Question three: do you have GPUs and people who can operate them

Question three asks about eligibility, not willingness. It has two halves.

  • Hardware eligibility.Can you get cards at all; do their specifications satisfy the weight and quantisation tier you intend to run; how many racks fit; is there power and cooling headroom. These answers must come from the official model card and deployment documentation for memory and parallelism requirements. Do not estimate memory from total parameter count - for mixture-of-experts models the total parameter count and the activated parameter count are different quantities, and planning from the total will produce a flat "this cannot run" verdict.
  • People eligibility.This is the most under-counted factor. Self-hosting means you own: weight and runtime upgrades, driver compatibility, scale-out scheduling, capacity planning, on-call response, and the maintenance of the monitoring and alerting that tells you any of this is broken. If nobody on the team can independently diagnose "the service is up but the output is garbage", the hidden cost of self-hosting dwarfs the visible hardware depreciation.

There is a quantitative way to look at the people factor: split self-hosting into annual labour cost and annual hardware cost and account for them separately. Many teams only count hardware, because hardware has a quote attached; labour usually does not and is therefore implicitly free. That is exactly why self-hosted proposals pass budget review most easily and then overrun most reliably in production.

How the three answers combine

QuestionThe concrete answer you must producePossible valuesWhat it locks inMost common wrong answer
1 Data boundaryA field-level list of what may not leave the networkA all sensitive / B partly sensitive / C unconstrainedWhether the path can be split in two at allSubstituting "we are B2B so we must be compliant" for a field list
2 Workload shapeDaily volume Q, average input L, peak-to-average r, replayabilitySteady / spiky / long-tail offlineWhether fixed cost can be spreadGiving only the daily average and omitting the peak and the P99 length
3 Resource eligibilityCard quota and spec, plus people who can debug a failure aloneHardware yes/no, people yes/noWhether the recommendation is executableAnswering "operations will be easy"
CombinationThe cross product of the threeSee the six combinations in section 3A single actionSkipping question three and announcing a topology anyway

The combinations converge on four action shapes, each with an explicit next step:

  • Boundary A + spiky + no GPUs or no people: do not self-host. Solve compliance through redaction and process, solve capacity through API elasticity.
  • Boundary A + steady + resources available: self-hosting is the natural answer to a compliance problem, and its value here is not only cost - it removes the "data left the building" question from the audit entirely.
  • Boundary B (by far the most common case): go straight to a hybrid architecture; sections 6 through 10 all apply.
  • Boundary C + long-tail offline + resources available: self-host the offline work, keep the API for online traffic. That is a cost optimum, not "go fully local".

3. The decision matrix: from condition combinations to an action

The tree gives direction; the matrix gives an executable action. The table below puts the condition combination, the recommended path, the first concrete step and the typical anti-pattern on the same row. Read it top to bottom, find the row closest to your situation, and execute the "first step" column - rather than picking the "recommended path" that sounds most appealing.

How to read the matrix

Each row has six columns: data boundary, workload shape, hardware and people, recommended path, first step and typical anti-pattern. The first three columns are facts and constraints; the last three are actions. Read the fact columns first and only then the action columns. If you cannot populate the fact columns, you should not cite any row of this matrix - go back to section 2 and measure.

Six typical combinations

Data boundaryWorkload shapeHardware and peopleRecommended pathFirst stepTypical anti-pattern
A all sensitiveSteadyHardware yes, people yesMostly self-hosted; API only for offline evaluationConfirm memory and parallelism from the official model card, then compute the annual fixed costClaiming data cannot leave the network while sending real requests to the API during a canary
A all sensitiveSpikyNo hardwareDo not deploy the model; fall back to rules and small modelsRedact and slice the data so the exfiltratable part is decoupled from the restricted partWorking backwards from "we already bought the cards"
B partly sensitiveSpikyHardware but no peopleHybrid: sensitive traffic to a local small model, the rest to the APIBuild the routing layer and field-level interception first; the local model can start out minimalMigrating the model first and designing the routing later, copying data out on the way
B partly sensitiveSteadyHardware yes, people yesHybrid, with local handling the high-sensitivity and high-reuse trafficCompare unit cost and quality across both paths with shadow trafficBuilding two unrelated systems so that cost cannot be attributed to either
C unconstrainedSpikyEitherFully on API, pay per use, optimise caching and batchingStand up token-usage attribution and a cache-hit-rate dashboardBuying cards now "in case we migrate later"
C unconstrainedLong-tail offlineHardware yes, people yesOffline to local, online to APIRun one cost model for the offline workload and confirm local really is cheaperUsing the online GPUs for batch jobs and starving the online path

Judging borderline cases

Most real situations sit on a boundary rather than in the centre of a cell. Three borderline classes have a definite resolution action:

  • Q sits near the break-even point.Stop arguing and measure. Compute the monthly self-hosted cost and the monthly API cost with the formulas in section 5, take the interval where the absolute difference is smallest, and then run one week of real traffic as shadow traffic so that the quality difference is folded in as well. The value of this step is that it removes two uncertainties at once: the price difference and the quality difference.
  • The data boundary sits between A and B.Ask whether separation is technically possible, not whether the data "feels" sensitive. If the restricted fields can be templated, hashed or dropped so that the request still makes sense, treat it as B. If the restricted field is free-form text that the task genuinely needs, and removing it destroys the task, it is A.
  • People sit between "yes" and "no".Work backwards from recovery time. Ask one question: if the local service dies at 3am, who can bring it back, in how long, and does the business suffer in the meantime? If the answer is "tomorrow morning" with customer impact, the labour cost of self-hosting must be booked as a full year of on-call, not as zero.

The default action when the answers are uncertain

A decision procedure needs a default path, and the governing principle is reversibility first: pick the cheap, low-exit-cost action that buys information. There are three canonical defaults. First, build observability: instrument both paths, which is the cheapest move and yields the most information. Second, run shadow traffic: it changes nothing the user sees, yet it directly compares quality and latency. Third, make routing a configuration layer, so "which path" is a config value rather than something compiled into code. All three share a property - they do not presuppose the conclusion, yet they fill in exactly the information the next decision needs.

Conversely, two actions are irreversible and expensive, and should be deferred while information is thin: buying large-scale compute capacity in one go, because depreciation runs long and exit is costly; and basing the compliance determination on verbal assurances, because a wrong contractual reading is expensive to unwind retroactively.

4. Local versus API, dimension by dimension

The matrix gives direction; this comparison gives dimensions. Most discussions fail because the participants are talking about different dimensions: the hardware vendor talks performance, engineering talks time-to-ship, legal talks data boundary, finance talks the cost curve. The table below flattens seven dimensions into three columns each: what the local topology looks like, what the API looks like, and how the hybrid handles it.

Cost shape: variable versus fixed

This is the deepest difference. The API is a variable cost: you pay for what you consume, and usually with headroom options (quotas, preemptible capacity) so you do not have to reserve for the peak. Self-hosting is a fixed cost: you pay whether you use it or not, and it multiplies once you add the redundancy needed to cover the peak.

Two counterintuitive but reliable conclusions follow. First, the steadier the load, the better self-hosting looks, because fixed cost gets spread evenly. Second, the spikier the load, the better the API looks, because you only pay for the peak instead of buying equipment to survive it. Deciding requires no specific price at all, only the ratio.

Latency and stability

A local path adds a network hop but removes a layer of queueing, so in a same-datacentre setup the time-to-first-token tends to be more controllable; an API path depends on server load, queueing policy and network route, and is therefore more variable. What actually determines user-perceived performance is tail latency, not the mean: P99 is the number users feel.

Stability cannot be judged from averages either. Two properties decide it: whether a degradation path exists (if local dies can you fall back to the API, if the API times out can you fall back to local or a small model) and whether failure is retryable. These two properties decide whether a fault is "the user sees an error" or "the user feels a slowdown" - two entirely different product incidents.

Compliance and auditability

The advantage of local is not only that data stays put, but that you own the logs: you can build your own audit trail of inference inputs and outputs and control retention precisely. On the API side you depend on the provider's data-processing terms, which can change with product revisions.

Note however that self-hosting is not automatically compliant. Logs on your own disks can become a new exposure surface. Without access control, encryption and retention rules, "the data never left the network" is still an unsatisfiable claim at audit time. In other words, self-hosting moves the compliance obligation from someone else onto you - that is both the benefit and the cost.

Operational burden and scalability

Operational burden is not an adjective; it is a list: runtime upgrades, driver compatibility, weight format conversion, quantisation tier validation, scale-out and scheduling, capacity planning, on-call and alert maintenance, incident retrospectives. Each item consumes real human time, and most of them do not scale with business volume - which is precisely what makes them fixed cost.

On scalability the API ceiling is usually set by provider quota, and quota is itself something you apply for and negotiate. The local ceiling is set by your own card count and network: a constraint you control more directly, but also a harder physical one. Control and convenience are different properties: self-hosting gives you control, not peace of mind.

Reproducibility and version alignment

The API side has a long-standing hazard: the name you request is not the service you receive. An alias may be rewritten to a new model, behaviour changes, and your code never changed. The local side has the mirror-image problem: the weight snapshot you pinned slowly diverges from what the business expects, because model upgrades are your responsibility and require your own canary process.

The two drift in opposite directions but produce the same outcome: behaviour changed while your code stayed still. Section 8 gives one alignment mechanism for both.

DimensionSelf-hostedAPIHow hybrid handles it
Cost shapeFixed: hardware, redundant capacity, labourVariable: floats with token usageRoute spikes and long-tail to different paths
Unit cost trendFalls with utilisation, worst when idleRoughly linear in usage; caching and time windows change the slopeSteady load local, fluctuating load to API
LatencyControllable in-DC; tail depends on your own schedulingStable mean; tail affected by server queueingPer-workload timeouts and degradation tiers
Failure surfaceDrivers, runtime, dead cards, OOM, corrupted weightsQuota, network, model retirement, behaviour changesMutual fallback, except sensitive traffic may never cross the boundary
RetryabilityDepends on business idempotencyDepends on business idempotencyAuto-retry only idempotent requests
ComplianceYou control data and logs, and own the liabilityDepends on provider terms and regional policyField-level interception happens in the router, not downstream
AuditabilityYou build the trail: controllable but costlyProvider supplies partial records with limited coverageRequest-level audit fields generated uniformly by the router
Operational burdenHigh, and mostly a fixed investmentLow, but provider changes are outside your controlKeep model operations in one place; decouple business logic
ScalabilityBounded by cards and racks; expansion takes weeksBounded by quota; increases need negotiationExpansion order: raise quota first, add cards second
ReproducibilityPin the weight, run your own canaryAliases may be rewritten; record the served modelBoth paths log the served version into one audit table
Best fitSensitive data, steady heavy load, offline long-tailSpikes, ordinary data, fast experimentationSplit by boundary B from section 2

5. Cost shape and the break-even point: doing the arithmetic with variables

Decisions are hard largely because the arithmetic is hard. This article deliberately quotes no specific price, GPU model or throughput figure, because those numbers change with time, region, SKU and discount, and any number frozen into an article is a time bomb. But the cost structure can be derived exactly, as long as prices are treated as symbols.

The API-side monthly cost function

Define: daily request volume Q, average input length L, average output length O, cache hit rate c, input prices p_in_hit and p_in_miss, and output price p_out. Every price here comes from the official pricing page and billing documentation; this article copies no concrete values. Then:

C_api = 30 x Q x [ (1-c) x L x p_in_miss + c x L x p_in_hit + O x p_out ]

The most interesting variable in that expression is not the price but c. The gap between a hit and a miss is typically an order of magnitude, and the hit rate is determined entirely by engineering choices: keep the system prompt, tool definitions and few-shot examples at the very front of the request and keep them byte-stable, and the hit rate climbs. That lever is far larger than "switch to a cheaper model", and it costs nothing in latency.

The self-hosted monthly cost function

Define: card count N_gpu, card price P_gpu, depreciation years Y, monthly facility cost F_fixed, monthly operations labour S_ops, effective utilisation u (real tokens processed as a fraction of theoretical capacity), and local unit token cost p_local. Then:

C_self = (N_gpu x P_gpu) / (12 x Y) + F_fixed + S_ops + (API cost for traffic local capacity could not absorb)

Note that u is not decoration. At low utilisation the unit token cost multiplies: the same cards running at thirty percent of capacity are more than three times as expensive per token. So "we have cards" and "we have cheap cards" are different claims, and utilisation is the most sensitive variable in the self-hosted model - and the most easily missed, because it depends on workload shape rather than on your purchase order.

Solving for the crossover

Setting the two costs equal gives the critical daily volume:

Q* = C_self / [ 30 x (L x p_eff + O x p_out) ]

where p_eff = (1-c) x p_in_miss + c x p_in_hit is the effective input price. The rule is then trivial: when Q is meaningfully above Q* lean towards self-hosting; when it is meaningfully below, lean towards the API. Two preconditions must hold, or the formula will mislead you.

  • Precondition one: estimate u from real traffic.Provisioning cards for peak QPS implies a structurally low u; provisioning for the mean implies you take on queueing and timeouts. Both provisioning styles inflate C_self, so Q* is usually larger than what you get by assuming ideal utilisation.
  • Precondition two: price in the quality difference.If the local weights are less capable than the API tier you would otherwise use, the same task needs more turns or longer outputs, so the effective cost is C_self divided by per-request completion quality. Ignoring quality differences is the classic optimism bias in self-hosted proposals.

Turning the formula into executable code

The script below keeps every price, card count and utilisation as an explicit input and bakes in no default prices - omit one and it raises. That is deliberate: it forces whoever builds the budget to actually open the official pricing page rather than fill in a number from memory.

def monthly_api_cost(Q, L, O, c, p_in_hit, p_in_miss, p_out):
    """API side monthly cost.
    Read every price from the official pricing page and pass it in; do not hard-code.
    """
    p_eff = (1 - c) * p_in_miss + c * p_in_hit
    return 30 * Q * (L * p_eff + O * p_out)


def monthly_self_cost(N_gpu, P_gpu, Y, F_fixed, S_ops, u, p_local, spillover=0.0):
    """Self-hosted side monthly cost.
    u is effective utilisation; spillover is the API cost of traffic local cannot absorb.
    """
    capex_monthly = (N_gpu * P_gpu) / (12 * Y)
    return capex_monthly + F_fixed + S_ops + spillover


def breakeven_Q(C_self, L, O, c, p_in_hit, p_in_miss, p_out):
    """Solve for the critical daily volume Q* where both topologies cost the same."""
    p_eff = (1 - c) * p_in_miss + c * p_in_hit
    unit = 30 * (L * p_eff + O * p_out)
    if unit <= 0:
        raise ValueError('invalid load parameters: unit cost must be positive')
    return C_self / unit


def recommend(Q, L, O, c, p_in_hit, p_in_miss, p_out,
              N_gpu, P_gpu, Y, F_fixed, S_ops, u, p_local, band=0.3):
    """Return a recommended path.
    band is the tolerance band around the crossover where shadow testing is cheaper than guessing.
    """
    api = monthly_api_cost(Q, L, O, c, p_in_hit, p_in_miss, p_out)
    self_cost = monthly_self_cost(N_gpu, P_gpu, Y, F_fixed, S_ops, u, p_local)
    q_star = breakeven_Q(self_cost, L, O, c, p_in_hit, p_in_miss, p_out)
    if abs(Q - q_star) / max(q_star, 1) <= band:
        return 'borderline: run a shadow comparison before buying anything', api, self_cost, q_star
    return ('lean self-hosted' if Q > q_star else 'lean API'), api, self_cost, q_star


# Self-check notes:
# 1) every price argument must come from the official pricing page;
# 2) u must be derived from real traffic shape, never from an ideal value;
# 3) do not set S_ops to 0 unless someone really can debug at 3am.
# shortcut: quality differences are not modelled here; measure them with shadow traffic

Aligning the accounting: where to look and what to check

Whether or not you use the script, the arithmetic only works if the definitions match. Here are the entries you can verify yourself, and the actions attached to each:

  • Price entry point: the official pricing page and billing documentation. Verify four numbers: cached input, uncached input, output, and whether there is time-of-day variation. Verification method: aggregate your invoice by those four categories and check that it reconciles.
  • Model entry point: call the model listing interface (for example the official API's models listing) to obtain the model IDs and alias mapping actually available to your account. Aliases can be rewritten, so this list must be refreshed periodically rather than frozen once inside a design document.
  • Usage entry point: every response carries a usage field. Accumulate hit, miss and output tokens separately into your own ledger.
  • Local entry point: memory and parallelism come from the official model card and deployment docs; real utilisation comes from your own request logs, never from a synthetic load test peak.

A practical cross-check: recompute your own ledger with the four token categories priced separately and compare it against the invoice. If it does not reconcile, your definitions differ from the provider's, every decision based on that ledger is untrustworthy, and you fix the definitions before discussing topology at all.

6. Hybrid architecture: the default answer for most teams

If sections one to five are compressed into one engineering recommendation, it is this: unless your data boundary is A and your resource eligibility is strong, the default topology should be hybrid. Hybrid is not fence-sitting; it is an architectural position - it demotes "topology" from a compile-time constant to a runtime configuration value, so that when business constraints change you do not have to rebuild the system.

Why hybrid is the default

Three reasons, all of them about reversibility:

  • Constraints change, and migration cost is rigid.Regulatory interpretation, customer contracts and volume all move. If every request rides on one path, any constraint change costs a migration. Split into two paths with configurable routing, a change costs a configuration edit.
  • The two failure modes do not overlap.Local fails on hardware and drivers; the API fails on quota and provider changes. With both paths present, overall availability exceeds that of either alone - provided the fallback path has actually been rehearsed rather than documented.
  • It lets you gather information in parallel.Shadow comparison is the cheapest decision-making tool there is, and it inherently requires both paths to be live. A hybrid is therefore not only a destination but the best observation platform for the decision phase.

The component inventory for two paths

A hybrid is not "two clients". It needs at least six component classes, and missing any one of them degrades the hybrid into two unmaintainable systems:

  • A unified request object.One canonical structure for a business request, carrying field labels, compliance tier, task type, priority and a timeout budget. Both paths consume the same object, which is what prevents definition drift.
  • A field-level policy layer.Before a request reaches any model, decide per field whether it is kept verbatim, redacted, hashed, stripped or routed to the other path. This is where the compliance boundary actually lands.
  • A router.Produces the target path, the degradation tier and the timeout budget. Routing must be configuration-driven; hard-coding it in code forfeits every benefit hybrid is supposed to deliver.
  • A local inference service.Exposes a uniform interface, and internally owns the weight version, quantisation tier, concurrency ceiling and queueing policy, plus a health endpoint.
  • An API client.Wraps authentication, retries, rate limiting, timeouts and error classification, and records the model that actually served the response.
  • A unified observability layer.Emits token usage, latency percentiles, cost, quality and error classification for both paths into one table, using the same field names. Without that you cannot answer "what did this request actually cost".

Where the routing layer belongs

The position of the routing layer determines whether it can genuinely block sensitive data. Three common placements, each with a cost:

  • Inline at every model call site.Simplest to build, but every call site must remember to check, and one omission is a leak. Fine for prototypes, wrong for production.
  • In a middleware layer between the business service and the model clients.Every outbound request passes through it, policy is centralised, and changing routing does not require touching business code. This is the recommended default.
  • At the network egress (gateway or proxy).Catches "someone opened a direct API connection", but has no access to business field semantics and can only distinguish by host and path, so its compliance judgement is the weakest of the three.

The pragmatic answer is layering: the middleware makes the primary decision and the gateway provides the backstop. The middleware knows field semantics; the gateway guarantees there is no bypass route. Dropping either layer leaves the design incomplete.

Four ways a hybrid fails

  • Failure one: routing rules are hard-coded.Changing a rule requires a release, the business cadence becomes hostage to the model team, and the rule history cannot be audited.
  • Failure two: each path keeps its own ledger.Cost is split across two unrelated tables and nobody can answer what a feature actually costs.
  • Failure three: the fallback path has never been rehearsed.The local service restarts and you discover there is no branch that re-sends the request to the API - or that the branch would have shipped sensitive data outward.
  • Failure four: nobody tracks version drift.The local weights and the API alias evolve independently and after six months nobody can say which model is live or why behaviour changed.

A field-based routing middleware fragment

Below is the core shape of the middleware layer. It is deliberately simple: policy comes from configuration, the routing decision is a pure function, and that makes it directly testable with assertions. Sensitive fields are processed before the request leaves the process rather than being trusted downstream.

"""Field-based routing middleware fragment.

Design constraints:
1) All policy comes from configuration; no business logic in code.
2) Sensitive fields are handled before the request leaves the process.
3) The routing decision is a pure function, so it can be assert-tested.
"""

# Field policy table (from the config service; illustrative shape)
POLICY = {
    'fields': {
        'user_id':      {'action': 'hash',   'sink': 'api'},
        'ticket_body':  {'action': 'redact', 'sink': 'local'},
        'query':        {'action': 'keep',   'sink': 'api'},
        'attachments':  {'action': 'strip',  'sink': 'local'},
    },
    'default_sink': 'api',
    'local_only_tasks': ['pii_extract', 'contract_review'],
    'fallback': 'local',
    'allow_cross_border_fallback': False,   # sensitive tasks may never cross
}


def classify(task_type, field, policy=POLICY):
    """Return (sink, processed_value) for one field. Pure function."""
    rule = policy['fields'].get(field)
    if rule is None:
        # Unregistered fields get the strictest treatment by default
        return policy['default_sink'], None

    sink = rule['sink']
    action = rule['action']
    if action == 'strip':
        value = None
    elif action == 'hash':
        value = '__HASHED__'
    elif action == 'redact':
        value = '__REDACTED__'
    else:
        value = '__KEPT__'
    return sink, value


def route(task_type, fields, policy=POLICY, local_healthy=True):
    """Decide which path this request takes, and return the processed fields."""
    if task_type in policy['local_only_tasks']:
        sink = 'local'
    else:
        sinks = {classify(task_type, f, policy)[0] for f in fields}
        sink = 'local' if 'local' in sinks else policy['default_sink']

    if not local_healthy:
        # Degrade, but never cross the compliance boundary
        if sink == 'local' and not policy['allow_cross_border_fallback']:
            raise RuntimeError('local unavailable and cross-border fallback is disabled')
        sink = 'api'

    processed = {f: classify(task_type, f, policy)[1] for f in fields}
    return sink, processed


# Self-check: three assertions that must hold
if __name__ == '__main__':
    sink, _ = route('qa', ['query', 'user_id'])
    assert sink == 'api', 'requests with only exfiltratable fields go to the API'

    sink, _ = route('qa', ['query', 'ticket_body'])
    assert sink == 'local', 'a locally-bound field forces the whole request local'

    sink, _ = route('pii_extract', ['query'])
    assert sink == 'local', 'task-level hard rules win'

    try:
        route('qa', ['ticket_body'], local_healthy=False)
        raise AssertionError('sensitive tasks must not fall back across the boundary')
    except RuntimeError:
        pass
    print('router self-check ok')

7. Designing the routing rules: four orthogonal dimensions

The most common way to get routing wrong is to put every dimension into one rule table until nobody can explain it. A better design splits routing into four orthogonal dimensions, each independently explainable, and then combines them with one deterministic precedence order.

By field: what the data is

The field dimension answers "which parts of this request may not leave the network". It is the physical basis of the compliance dimension and the only mechanism that can genuinely block sensitive data.

  • Disposition actions: keep verbatim, redact (reversible or not - the distinction matters), hash (for correlation rather than reconstruction), strip (never reaches the model), or route separately (send that portion down the local path and merge the results).
  • The critical constraint: unregistered fields must be treated with the strictest policy. Default-allow is the design most likely to cause an incident: the day someone adds a field and forgets to register it, it silently leaves the network. Default-deny costs some extra effort, but its failure mode is "the feature errors out" rather than "data leaked".

By user: who is calling

The user dimension answers "which department, tenant, role or clearance level is this request from". Its value is that it maps compliance policy onto the organisation: only certain departments may use the cloud path, one customer's data-processing agreement forbids leaving the region.

This dimension is particularly good for canaries and isolation: enable the API path for one internal group first, then ramp gradually, turning user-visible differences into a controlled variable rather than a global risk. Implement it as a lookup table, not as an if-statement in business code: a mapping from user group to path, configurable, hot-reloadable and revertible.

By task type: what is being done

The task dimension answers "what kind of job is this": classification, extraction, summarisation, question answering, code generation, complex reasoning. It is usually the main battleground for cost and quality, because different tasks tolerate different model tiers, thinking strengths and retry counts very differently.

The practical value: a high-frequency classification task goes to the cheapest and fastest tier with aggressive caching; a hard reasoning task goes to an expensive tier but tolerates a long timeout; a long-document batch goes to a local offline queue. Running all of them on one model is the primary cause of runaway cost.

By compliance tier: how sensitive is this request overall

The compliance tier is the composite output of the previous three dimensions. The business system already knows the context when it builds the request - which customer's data, which operation, whether it crosses a region - so it can attach the label directly.

Granularity matters: three levels (public / internal / restricted) usually suffice; finer gradations cause combinatorial explosion and eventually nobody maintains them. Labels must be derivable or verifiable automatically, because a tagging scheme that depends on human judgement degrades to uselessness within about six months.

The merge order

The four dimensions can disagree, so the merge order must be fixed and strict. The recommended order is:

  1. Hard constraints first.Field-level and task-level "must not leave" rules; no dimension may override them.
  2. Compliance tier next.A restricted label sends the request local.
  3. User dimension.Determines which paths this caller is even allowed to use, for example a pilot department restricted to local.
  4. Task dimension.Within the permitted set, picks the best path and sets the tier and timeout.

Express this order as a priority array in configuration rather than scattering it across conditionals. Then a rule change is a configuration change, not a code change, and the rule set becomes auditable.

DimensionQuestion it answersData sourceTypical ruleEasiest mistake
FieldWhich data in the request may not leave the networkField policy tableSensitive fields stay on the local path; the rest may leaveDefaulting unregistered fields to allow
UserWho is issuing the requestUser group mapping tableA pilot department may only use the local pathHard-coding user groups into business code
TaskWhat job is being requestedTask type enumerationClassification and extraction use the cheap tier; long-context tasks use the offline queueOne model for every job
Compliance tierHow sensitive the request is overallLabel attached by the business systemRestricted tier always routes localLabels judged by hand with no validation
MergeHow four verdicts become onePriority arrayHard constraint > tier > user > taskPrecedence scattered everywhere, so rules cannot be audited
DegradationWhat if the preferred path is unavailableFallback direction tableSensitive tasks degrade to a local small model, never across the boundaryFallback direction does not distinguish sensitive from ordinary

8. Version alignment: a local weight snapshot and an API name are not the same thing

Hybrid architectures have a problem that is easy to overlook: each path has its own version, and versions move on their own. Locally you pin a weight snapshot; on the API side you write an alias that may be rewritten at any time. The two drift in opposite directions but produce the same outcome - behaviour changed while your code stayed still.

Three kinds of version drift

  • Drift one: the API alias is rewritten.The name you request starts pointing at a different model; server behaviour changes and neither your code nor your configuration moved. The only way to detect it is to read the model that actually served the response and log it.
  • Drift two: the model is retired.The model you depend on reaches the end of its lifecycle and existing requests are automatically absorbed by a successor. Detect it the same way, plus by periodically reading retirement announcements.
  • Drift three: the local weights diverge from expectations.The local model has not moved for three months, but the prompts and the evaluation baseline have, so "local quality got worse" is really baseline drift. Periodic regression evaluation is the only way to tell the two apart.

The alignment mechanism: make version a piece of observable state

Three rules, all of them necessary:

  • Rule one: log the version on both sides of the exchange.Record the requested model identifier and the model that actually served the response. A mismatch is the physical evidence that an alias rewrite happened.
  • Rule two: the local weight version belongs in the deployment manifest and in monitoring labels.It is a first-class citizen, not a hash suffix in a build artefact. Without it, six months later nobody can say which weights are live.
  • Rule three: every version change needs a regression baseline.Whether it is an API alias change or a local weight upgrade, run the same fixed evaluation set and watch the key metrics. With a baseline the change is controlled; without one it is a gamble.

A health check for the local inference service

A health check is not a port ping. It has to answer three questions: is the service listening, which weights is it running, and can it still produce correct output. Only the third distinguishes "the process is alive but the output is garbage", which is the most common catastrophic local failure. The script below uses nothing but the standard library, so it runs anywhere a scheduler or CI job can.

"""Local inference service health check (standard library only).

Three checks:
  1) reachability        -> network and process are alive
  2) version readable    -> deployment manifest matches the running service
  3) minimal generation  -> can it actually produce, not merely stay alive

Usage: python healthcheck.py --endpoint http://127.0.0.1:8000 --expect-version v2026.11-a
"""
import argparse
import json
import sys
import urllib.error
import urllib.request


def http_get_json(url, timeout=5):
    req = urllib.request.Request(url, headers={'Accept': 'application/json'})
    with urllib.request.urlopen(req, timeout=timeout) as resp:
        return resp.status, json.loads(resp.read().decode('utf-8'))


def http_post_json(url, payload, timeout=30):
    data = json.dumps(payload).encode('utf-8')
    req = urllib.request.Request(
        url, data=data,
        headers={'Content-Type': 'application/json', 'Accept': 'application/json'})
    with urllib.request.urlopen(req, timeout=timeout) as resp:
        return resp.status, json.loads(resp.read().decode('utf-8'))


def check_endpoint(base):
    try:
        status, _ = http_get_json(base.rstrip('/') + '/health')
        return status == 200, 'health status=%s' % status
    except (urllib.error.URLError, OSError, ValueError) as exc:
        return False, 'health unreachable: %s' % exc


def check_version(base, expect_version):
    """The running version must match the expectation exactly; mismatch means drift."""
    try:
        _, body = http_get_json(base.rstrip('/') + '/version')
    except (urllib.error.URLError, OSError, ValueError) as exc:
        return False, 'version endpoint unreachable: %s' % exc
    actual = body.get('model_version') or body.get('version')
    if actual != expect_version:
        return False, 'version drift: expect=%s actual=%s' % (expect_version, actual)
    return True, 'version ok: %s' % actual


def check_generation(base):
    """Send a minimal request and confirm a sensible completion comes back."""
    payload = {
        'model': 'local',
        'messages': [{'role': 'user', 'content': 'Reply with one word: ready'}],
        'max_tokens': 16,
        'temperature': 0,
    }
    try:
        _, body = http_post_json(base.rstrip('/') + '/v1/chat/completions', payload)
    except (urllib.error.URLError, OSError, ValueError) as exc:
        return False, 'generation failed: %s' % exc
    try:
        text = body['choices'][0]['message']['content']
    except (KeyError, IndexError, TypeError):
        return False, 'unexpected response shape'
    if not text or not text.strip():
        return False, 'empty completion'
    return True, 'generation ok: %s' % text.strip()[:32]


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('--endpoint', required=True)
    ap.add_argument('--expect-version', required=True)
    args = ap.parse_args()

    checks = [
        ('reachable', check_endpoint(args.endpoint)),
        ('version', check_version(args.endpoint, args.expect_version)),
        ('generation', check_generation(args.endpoint)),
    ]
    failed = False
    for name, (ok, detail) in checks:
        print('%-12s %s  %s' % (name, 'PASS' if ok else 'FAIL', detail))
        failed = failed or not ok
    # Any failure yields a non-zero exit code so the scheduler can drain traffic
    sys.exit(1 if failed else 0)


if __name__ == '__main__':
    main()
# shortcut: real business quality is not probed here; run the fixed evaluation set separately

How drift fails in practice

Drift itself is not the problem; having no record of it is. Three typical failures: an alias is rewritten but the log only holds the requested name, so the behaviour change cannot be attributed and the team starts suspecting its own prompts; local weights are upgraded without a regression run, so a business metric drops and the team blames the business change, and the rollback cannot be reproduced either; the evaluation baseline drifts along with the business, so every version comparison loses its reference point.

9. Failover: what happens when local dies and when the API times out

Failover is the part of a hybrid architecture that is easiest to get wrong and hardest to validate under pressure. One principle governs everything: the fallback direction must match the data boundary. A fallback implementation that does not distinguish sensitivity will ship sensitive data to the API the first time the local service restarts - upgrading an availability incident into a data incident.

Three levels of degradation when local is unavailable

  • Level one: degrade within the same path.Lower the concurrency ceiling, shrink the context window, disable thinking mode to shorten per-request time, and use fewer resources to keep some throughput. This level does not change the data boundary, so it is the safest, and it should be tried first.
  • Level two: fall back to a smaller local model or rules.Degrade to a less capable but steadier local tier, or answer recognisable request types directly from rules or retrieval. Check that the degraded output is acceptable for the business: a classification task can degrade, a reasoning task often cannot.
  • Level three: cross-path fallback.Only when the request contains no restricted fields may the request be forwarded verbatim to the API. The decision must be made at the instant of fallback, not delegated to the upstream caller who was supposed to remember to declare sensitivity.

Failover when the API times out, throttles or runs out of quota

The API side usually does not fail wholesale; it degrades partially: queueing grows until timeouts fire, concurrency quota is throttled, or one model alias becomes temporarily unavailable. The corresponding sequence is:

  • Classify the timeout before retrying.Retry only idempotent requests, with exponential backoff and jitter. Fail non-idempotent requests immediately rather than retrying.
  • Degrade to a lighter tier.Disable thinking, cap maximum output, shorten context. Note that degrading to a cheaper tier changes output quality, so it must only be enabled when the business can accept it.
  • Fall back to local.Only if local has spare capacity and the request is not sensitive. Before switching back, check the current local load: an API slowdown that pushes all traffic onto local will overwhelm local as well. That is a cascading failure, the most common fallback incident.
  • Queue instead of switching.For deferrable work such as batch processing and offline aggregation, the correct fallback is often to enqueue locally rather than to move paths.

Three defences against cascading failure

  • Circuit breaking with a half-open state.After a threshold of consecutive failures a path is opened and no longer attempted, avoiding repeated pressure on an already broken path. A half-open state probes recovery with a trickle of traffic.
  • Reserve capacity for fallback.Keep some capacity free for the fallback direction, for example running local at seventy percent of capacity so the remaining thirty percent can absorb an API outage. Without a reserve, failover merely relocates the outage.
  • Suppress the fallback storm.Rate-limit fallback traffic separately inside the router, and protect sensitive traffic's local capacity first so that low-priority traffic cannot squeeze it out.

Canary switching and failover in code

The snippet below implements proportional canary, automatic rollback on failure, and the ban on crossing the boundary for sensitive traffic. It deliberately uses simple counting rather than a sophisticated consistency protocol, because during a real outage simple, predictable behaviour is worth more than elegant mechanisms that might themselves fail.

"""Proportional canary to the API with automatic rollback to local.

Key constraints:
1) Canary by stable hash so a user stays on one branch.
2) Failure counts above a threshold trigger a rollback, which is a global action.
3) Sensitive traffic never enters the API branch, whatever the canary percentage is.
"""
import hashlib
import time

LOCAL = 'local'
API = 'api'


class Router:
    def __init__(self, rollout_pct=0, error_threshold=5,
                 cooldown_s=60, sensitive_sink=LOCAL):
        self.rollout_pct = rollout_pct      # 0-100 share routed to the API
        self.error_threshold = error_threshold
        self.cooldown_s = cooldown_s
        self.sensitive_sink = sensitive_sink
        self.failures = {}                   # branch -> consecutive failures
        self.backoff_until = {}             # branch -> circuit recovery time

    def bucket(self, key):
        return int(hashlib.sha256(key.encode('utf-8')).hexdigest()[:8], 16) % 100

    def circuit_open(self, branch):
        return time.time() < self.backoff_until.get(branch, 0)

    def choose(self, key, is_sensitive, local_ok=True, api_ok=True):
        if is_sensitive:
            # Hard constraint first: sensitive traffic never goes to the API
            if local_ok:
                return LOCAL
            raise RuntimeError('sensitive request and local unavailable: '
                               'fail closed, never cross the boundary')

        if self.circuit_open(API) and local_ok:
            return LOCAL
        if self.circuit_open(LOCAL) and api_ok:
            return API

        if not local_ok:
            return API
        if not api_ok:
            return LOCAL

        if self.rollout_pct <= 0:
            return LOCAL
        if self.rollout_pct >= 100:
            return API
        return API if self.bucket(key) < self.rollout_pct else LOCAL

    def record(self, branch, ok):
        if ok:
            self.failures[branch] = 0
            return
        n = self.failures.get(branch, 0) + 1
        self.failures[branch] = n
        if n >= self.error_threshold:
            self.backoff_until[branch] = time.time() + self.cooldown_s

    def set_rollout(self, pct):
        self.rollout_pct = max(0, min(100, pct))


# Self-check: three assertions that must hold
if __name__ == '__main__':
    r = Router(rollout_pct=50)
    assert r.choose('u1', is_sensitive=True) == LOCAL
    assert r.choose('u1', is_sensitive=False) in (LOCAL, API)

    r2 = Router(rollout_pct=100)
    try:
        r2.choose('u1', is_sensitive=True, local_ok=False)
        raise AssertionError('sensitive traffic must fail rather than leave when local is down')
    except RuntimeError:
        pass

    r3 = Router(rollout_pct=100, error_threshold=2, cooldown_s=60)
    r3.record(API, ok=False)
    r3.record(API, ok=False)
    assert r3.circuit_open(API), 'the circuit should open after the failure threshold'
    assert r3.choose('u1', is_sensitive=False) == LOCAL, 'rollback to local after the circuit opens'
    print('router rollout self-check ok')

10. Observing both paths: cost, latency and quality in one table

The most common operational accident in a hybrid architecture is not an outage; it is nobody knowing where the money went. Two teams each have dashboards that look fine, they do not add up to the business invoice, and the year-end review cannot answer a single decision-relevant question. This section gives the minimum unified set.

Unified cost accounting: attribute per request, not per path

The attribution granularity must be the request, not "the local service" or "the API client". Generate a trace id per request and record token usage, cache hits, misses and output on both sides into one record, using identical field names.

Three fields are mandatory:

  • requested_model and served_model.The first is the identifier you asked for; the second is the model that actually served the response, or the local weight version. When they differ you have version drift evidence.
  • tokens_hit / tokens_miss / tokens_out.Three separate counters, never a merged total. Computing cost from a merged total is always wrong because the gap between hit and miss is an order of magnitude.
  • route_label.Which path the request took and why, as a rule identifier. The "why" is the most valuable part six months later when you have to explain a cost swing.

Latency decomposition: break it down far enough to attribute

Split end-to-end latency into: queueing (local queue or server-side queue), time to first token, generation time, and network plus serialisation. A single total hides the difference between "the model is slow" and "the queue is long", and those two have opposite remedies - one is a tier change, the other is capacity or queueing policy.

On the local path, record queue duration and batching policy explicitly. The classic local latency problem is not slow computation but insufficient concurrency causing queue growth, while the classic API problem is server-side queueing. Both look identical from the client, but the fix is opposite in each case.

Quality comparison: shadow diffing is the cheapest method

Quality across the two paths must remain comparable, otherwise cost optimisation becomes a quality slide. Send the same batch of requests to both paths, return only the result the user should see, and record and diff the other.

Fix four dimensions for comparison: structured-output validity rate (can the JSON be parsed), key-field agreement rate, output length distribution, and human spot-check pass rate. The first two are binary and will break first after a switch; the latter two track real business value.

Alert design: only alert on what breaks first

Do not give every component its own alerting package; that manufactures alert fatigue until nobody reads anything. Four alert classes are worth having:

  • Availability.Error rate on either path crosses a threshold. On the API side, separate throttling from genuine errors - throttling may simply be a quota issue.
  • Cost.Unit cost per request drifts from its baseline. This class is the most valuable, because cost anomalies usually appear before outages do.
  • Version.requested_model differs from served_model, or the local weight version differs from the deployment manifest.
  • Degradation.The share of fallback traffic rises. This is the earliest "something is wrong" signal and often precedes user complaints by tens of minutes.

Wire alerts to automatic actions - autoscaling, tier switching, degradation - rather than to humans alone, provided the automatic action itself has a rollback.

11. The reverse path: when moving from self-hosted to API is the sensible choice

The default narrative in most articles is "start on the API, migrate to self-hosting once you scale, because it gets cheaper". That direction is sometimes right, but the opposite is frequently more common, especially while the model itself is iterating quickly. Below are the criteria under which each path holds.

Phases where self-hosting is actually the better buy

  • Phase one: exploration, when the model moves fastest.API versions and behaviours change frequently here: aliases are rewritten, models retire, defaults shift. Your behaviour can change without a single committed line. When you need controlled comparisons, a pinned weight snapshot for ablations, or the ability to reproduce one specific defect, pinning a local snapshot is the only way to guarantee reproducibility. At this stage the purchase is not "saving money" but "buying determinism".
  • Phase two: offline evaluation and prompt engineering.Evaluation sets are re-run repeatedly and prompts are tuned iteratively, so stability of results matters enormously. A one-off fixed local cost amortises very quickly under heavy re-runs, and the upstream changing version cannot invalidate your entire evaluation history.
  • Phase three: long-context and unusual workload shapes.If the load is long-document batch processing, needs an extreme batching strategy, or requires inference parameters the API does not expose, the value of self-hosting comes from tunability rather than price.

All three share a property: what you are buying is a more controllable service, not a cheaper one.

Phases where you must move away

  • Trigger one: the stability bar rises.Once the model is in a customer-facing path, the SLA needs a counterparty that can sign it and staff that can be on call. Self-hosting puts that stability responsibility on you, which requires long-term staffed capability.
  • Trigger two: concurrency grows.Self-hosted expansion runs in weeks - procurement, racking, drivers, tuning - while traffic growth runs in days. The weeks waiting for hardware are exactly the weeks when elasticity matters most. API capacity is a quota increase, usually minutes to hours.
  • Trigger three: audit requirements rise.Audits want logs, retention, access control and change records. Self-hosting means producing all of it yourself and having it inspected; using the API means many items come as provider evidence, provided you check the terms cover your case.
  • Trigger four: the version you need is no longer the version in production.If the capability you need only exists in a retired weight snapshot, self-hosting means maintaining a historical version indefinitely, which is a permanent and unsustainable cost.

Hybrid as a transitional state, not a destination

The duration of the two-path state needs an explicit plan, or it becomes a zombie state nobody dares to switch off. The healthy approach is to define the exit condition in advance: when one path's traffic share stays below a threshold for N consecutive weeks and closing it triggers no alert, close it. Writing the closure condition down in advance is the only way a hybrid converges.

A checklist of migration trigger signals

  • Expansion wait time.Days between "we need more capacity" and "the capacity is usable".
  • Recovery time.The median time from failure to recovery, and how many people it consumed.
  • Drift-induced rework.How many times a quarter upstream behaviour changes forced you to redo work. More rework argues for owning the version yourself, that is, for self-hosting; less argues that the cost of pinning exceeds the benefit.
  • Audit preparation days.Person-days needed to assemble evidence for one audit. If that permanently occupies most of one person, compliance work has become heavier than the model itself.

12. The migration path, stage by stage

Whether you are moving from API to self-hosted or the other way, the correct progression is staged. The table below gives the goal, the actions, the entry condition and the exit condition for four stages. The key design is that every stage has a gate you may not pass without, and each gate is explicit.

Stage 0: baseline measurement

Extract the real numbers of the current topology: unit cost per request, P50/P95/P99 latency, a quality baseline, cache hit rate, the error distribution, and the real load's peak-to-average ratio and length distribution. A migration without a baseline is a blind migration - afterwards you cannot prove whether things improved, only accumulate numbers you cannot compare.

Stage 1: shadow traffic

Copy a small share of real requests to the target path, recording results without affecting users. This answers "where does the behaviour differ" and "how much does the cost differ". The metrics that matter in this phase are differences rather than absolutes: structured-output validity gap, key-field agreement, latency percentile gap, unit cost gap. Shadow traffic must cover peak hours; testing only the trough is equivalent to not testing.

Stage 2: proportional cutover

Roll out in stable-hash buckets, with a promotion gate and a rollback condition for every step. Promotion gates must be quantitative - structured-output validity not below baseline, cost not above a set ratio of baseline, P99 under a threshold - rather than "it looks fine". The rollback condition must be written before the promotion condition, because otherwise you will be having that discussion during the incident.

Stage 3: converge on one path and review

Once the target shape is reached, close the other path - or drive its traffic to zero - and run a retrospective: what did the migration really save or cost; which preparation was necessary and which was wasted; which monitoring gaps made problems too slow to detect. Turn the conclusions into executable checklist items added to the next migration's entry criteria.

StageGoalKey actionsEntry conditionExit condition
0 BaselineObtain comparable real numbersInstrument cost, latency percentiles, quality baseline, load distributionUnit cost and peak-to-average ratio can be computedBaseline collected continuously for one full business cycle
1 ShadowSee the differences between the two pathsCopy real traffic to the target path, record onlyBaseline complete and shadow covers peak hoursQuality differences within tolerance and cost differences explained
2 CutoverRoll out proportionally with instant rollbackStable-hash buckets, staged rollout, automatic degradation backstopShadow conclusions confirmed and the rollback condition is fixedTarget share reached and guardrail metrics stable for one cycle
3 ConvergeClose the non-target pathTraffic to zero, keep read-only monitoring, clean up configurationNo alerts and no fallback events for N consecutive weeksRetrospective produced with checklist items for the next round

This stage table works in both directions. When migrating towards self-hosting, stage two is about capacity rather than percentage: validate the local cluster on a small share first, then add cards gradually. When migrating towards the API, stage one is about alias behaviour: log both the requested model identifier and the model that actually served the response, and confirm no silent rewrite happened.

13. Failure mode checklist

Six failure modes dominate this area. Each is given as symptom, root cause and countermeasure, so the list can be used directly as a review checklist.

Failure one: treating a compliance problem as a deployment problem

Symptom: the review circles around "self-hosted or API" for hours and nobody can say which fields may not leave the network. Root cause: a data-boundary question was mistaken for an infrastructure-selection question, so an infrastructure answer was given to a field-policy question. Countermeasure: produce the field-level list first; if that list cannot be produced, do not start selecting a topology.

Failure two: fallback that does not distinguish sensitive data

Symptom: one restart of the local service sends a batch of requests that should never have left the network to the API. Root cause: the fallback logic lives in business code behind a boolean flag instead of being derived from field policy. Countermeasure: the fallback decision and the field policy must consume the same data; sensitive tasks fail closed when local is unavailable, never open.

Failure three: version drift makes cost and quality unattributable

Symptom: the invoice rises while usage does not, or quality degrades and nobody can say when it started. Root cause: logs hold only the requested model identifier, never the model that actually served the response or the local weight version. Countermeasure: store version information from both paths under the same field names and make it part of the health check.

Failure four: each path keeps its own ledger

Symptom: the local team reports "our costs went down" while the API team reports "our costs went up", and the business side has no cost view at all. Root cause: attribution granularity is the path rather than the request. Countermeasure: attribute by request trace id with one field vocabulary on both sides.

Failure five: hidden self-hosted cost treated as zero

Symptom: the budget contains only hardware, the review passes, and production then generates a pile of unplanned work. Root cause: labour and facility costs are missing from the model, and they are the bulk of the fixed cost. Countermeasure: split the self-hosted side into hardware, facility and power, and operations labour, and mark anything unknown as unknown rather than zero.

Failure six: migrating a spiky workload into self-hosting

Symptom: hardware sits mostly idle while capacity is still tight. Root cause: cards were provisioned for the peak, so utilisation is structurally low. Countermeasure: keep the spiky part on the API, move only the steady part local, and smooth the peak with a queue.

Failure modeSymptomRoot causeCountermeasure
Compliance treated as deploymentLong review, nobody can state which data is restrictedAnswering a field-policy question with a topologyField list first, topology second
Fallback ignores sensitivityA local restart sends traffic outwardBoolean flag instead of field policyShare the policy data; sensitive tasks fail closed
Version driftInvoice rises without usage growth; quality drops with no explanationOnly the requested model identifier is loggedLog served_model and the local weight version
Separate ledgersEach side claims it did not get more expensiveAttribution granularity is the path, not the requestUnified attribution keyed on trace id
Hidden cost treated as zeroHardware-only budget, production overrunsLabour and facility cost absent from the modelAccount for hardware, facility, power and labour separately
Spiky load moved localIdle hardware and still tight capacityProvisioning for peak gives very low utilisationKeep spikes on the API, move steady load local, smooth the peak

14. Boundaries, non-applicable cases and self-verification

Every decision guide has scope it does not cover. Stating the boundary is more useful than pretending to cover everything.

Three things this article does not solve

  • Concrete installation and deployment procedure.Downloading weights, choosing a quantisation tier and tuning runtime parameters belong to deployment practice; this article only makes topology decisions. The one relevant reminder: the local weight version must live in the deployment manifest and be readable by the health check.
  • Evaluation conclusions about specific models.This article does not compare the capabilities of particular tiers; that is the job of an evaluation piece. Here we only discuss how to choose a topology given a fixed capability requirement.
  • The complete cost algorithm.What is presented here is the minimum cost structure needed for a decision - expressing cost as a variable plus a fixed part and solving for the crossover. Full pricing models, cache economics and cross-region traffic economics are out of scope.

How to verify everything yourself

This article deliberately quotes no specific price, card model or throughput number, because those change. Every place a number would be needed is expressed as a variable plus a query entry point. The verification method is:

# 1) Prices: open the official pricing page and billing documentation, record four numbers
#    - cached input price       - uncached input price
#    - output price             - whether time-of-day pricing exists
#    Feed these into the functions in section 5; do not type them from memory.

# 2) Available models and aliases: call the model listing interface for the IDs
#    your account can actually use right now
curl -sS https://api.deepseek.com/models \
  -H "Authorization: Bearer $DEEPSEEK_API_KEY" \
  -H "Accept: application/json"

# 3) The model that actually served: send a minimal request and read the model field
curl -sS https://api.deepseek.com/chat/completions \
  -H "Authorization: Bearer $DEEPSEEK_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model":"deepseek-chat","messages":[{"role":"user","content":"ping"}],"max_tokens":16}'
#    requested name != served name; the difference is alias rewriting in the wild.

# 4) Usage definitions: reconcile hit, miss and output token counts in usage
#    Computing cost from a merged total is always wrong: hit and miss differ
#    by an order of magnitude.

# 5) Local side: memory and parallelism from the official model card and deployment
#    docs; utilisation from your own request logs, never from a synthetic peak.

# shortcut: these steps only collect data; judgement belongs to the matrix in section 3

A decision record template

Writing one topology decision on a single page is the cheapest way to make decisions reviewable. Five sections suffice:

  • Constraints.Data boundary (field list), workload shape (Q, L, O, peak-to-average, replayability), resource eligibility (hardware, people).
  • Conclusion.The current topology, plus an explicit statement of which alternatives were excluded and by which constraint.
  • Basis.Where the cost parameters came from, which page you copied them from and on what date, and how version alignment is handled.
  • Trigger conditions.Which signals cause a re-evaluation: expansion wait beyond N days, a change in audit requirements, the peak-to-average ratio moving by some factor.
  • Exit conditions.Under what condition one path is closed.

The fifth section is the one most often omitted and the most important: an architectural decision without an exit condition becomes a permanent state.

A minimum validation checklist: doable in two weeks

If you only do one thing from this article, do this checklist - it covers most of the decision risk:

  • Days 1-3: produce the field-level sensitivity inventory, with a disposition action for every field (keep, redact, hash, strip, local).
  • Days 4-6: extract the router out of business code into a configuration-driven layer. At this point it need not call any model - it can simply print its decisions.
  • Days 7-10: wire the observability fields for both paths (one trace id, one field vocabulary) and run a week of real traffic.
  • Days 11-12: run one shadow comparison and produce the difference list and the unit cost comparison.
  • Days 13-14: use the matrix in section 3 and the formulas in section 5 to write a one-page decision record with trigger and exit conditions filled in.

The value of this checklist is not its rigour. It is that it replaces "should we self-host or use the API" - an unresolvable argument - with a set of facts that each have a deliverable. Once the facts exist, the conclusion usually surfaces on its own; and even if it does not, you have gained the information the next round of decisions needs.

15. Conclusion: topology is a decision, not a preference

Return to where we started: "local or API" is not a binary technology question but a constraint-solving problem. Its inputs are the three questions - data boundary, workload shape, resource eligibility - and its output is an action from a matrix, not a permanent architectural declaration.

If only three sentences survive from this article, I hope they are these:

  • First, list the fields before discussing topology.The compliance boundary determines whether the path can be split at all; it is the hardest constraint and the only one verifiable with a checklist.
  • Second, steady load leans local, spiky load leans API, long-tail offline leans local.None of this needs a specific price, only the peak-to-average ratio.
  • Third, the default architecture is hybrid, but hybrid needs an exit condition.Configuration-driven routing, observable versions, and fallback layered by sensitivity tier - get these three right and a topology switch becomes a configuration change rather than a rebuild.

One practical closing note: everywhere this article needed a price, a card or a throughput figure, it left a variable instead, because those change. What stays stable is the decision structure. Put that structure into your decision record template so every topology choice leaves a trail of why it was made then and what would change it - that matters more than getting one decision right.