Model Serving, Unity Gateway and Cost
Choose how models are served, put one governed path in front of them and know what every request costs.
Model serving decides how capacity is provided: shared pay-per-token endpoints, a priority variant, or provisioned throughput. Unity Gateway is the governed path for model and tool traffic, with limits, routing, guardrails, logging and budgets. Cost control comes from tags that reach billing records, a cost per successful task and limits enforced before the money is spent.
What you will learn: serving options and how to choose among them, calling models, what a gateway should enforce, fallback design, payload logging, billing tables, tagging, budgets and cost reduction.
Prerequisites: Model Routing, Fallbacks and Gateways and Agent Cost Model and Token Economics.
The example runs in November 2026 with Python 3.13 and only the standard library. It is a toy gateway with invented prices, limits and callers; it is not Unity Gateway. Platform facts come from Databricks documentation checked on November 28, 2026. Several gateway features have preview or beta status that differs by cloud. OneSmartClick is independent of Databricks.
Where an agent's model calls can go
| Backend | You decide | Typical concern |
|---|---|---|
| Platform-hosted foundation models | Model and serving mode | Region support and model retirement |
| External provider models | Provider, contract and routing | Data leaves to another service; separate billing |
| Your own served models | Model, hardware and scaling | Idle capacity and operations |
Foundation Model API modes
The Foundation Model APIs documentation describes these ways of paying for and receiving capacity:
| Mode | Documented intent | Ask before choosing |
|---|---|---|
| Pay-per-token | Getting started and exploration | What happens at peak load? |
| Priority pay-per-token | Latency-sensitive production work needing steadier performance | Which models and regions offer it? |
| Provisioned throughput | High throughput, performance guarantees, fine-tuned models or stricter security needs | How much capacity, on demand or reserved? |
Documentation pages do not all word the production recommendation the same way: some recommend provisioned throughput for production, and a current page also recommends priority mode for latency-sensitive workloads. Read the version for your cloud and test with your own traffic. Compliance certifications are described for provisioned throughput endpoints; confirm which apply to you with your compliance team rather than assuming.
Calling a model
Documentation describes most of these APIs as compatible with the OpenAI client, so existing code often needs only a new base address, credential and endpoint name. Compatible does not mean identical. Check tool calling, structured output, streaming, token limits, reasoning settings and error codes for the specific model. Keep the endpoint name in configuration, record it in traces and handle rate-limit errors with delayed retries and a maximum attempt count, as in reliable execution.
Models change under you
Hosted model lists move quickly. The supported models page has recorded retirements and a period in which calls to one model were temporarily redirected to its successor. A redirect keeps the application running but can change answers, format and length. Subscribe to notices, keep an inventory of which agents call which endpoint and rerun evaluations when anything moves. Promotion, rollback and drift gives the routine.
What Unity Gateway covers
Databricks describes Unity Gateway as its governance solution for enterprise AI, covering model and MCP traffic from a central control plane. Documented capabilities include:
| Capability | What it helps with | Design question |
|---|---|---|
| Permissions | Who may call which service | Which groups and service principals? |
| Rate limits | Capacity and runaway use | Per service, user or group? |
| Traffic splitting and fallbacks | Availability and gradual change | Is the backup truly acceptable? |
| Service policies or guardrails | Control by content and caller | What is blocked, and who reviews? |
| Usage tables and payload logging | Audit, debugging and analysis | Who can read the content? |
| Budgets | Alerts and spend limits | What should stop, and what must not? |
An older gateway configuration for model serving endpoints still appears in documentation, with its own feature support. Names are similar, so confirm which of the two a page describes before relying on it.
Rate limits
For serving endpoints, documentation describes limits in queries or tokens per minute, with defaults for users and specific overrides. Choose limits from measured need with headroom, then watch rejections. A limit set too low looks like an outage to users; one set too high protects nothing. Separate limits for interactive use and batch jobs keep a nightly job from blocking people. Agents need a second limit inside the application: maximum steps, tokens and tool calls per task. See stopping and budgets.
Fallbacks that are safe
A fallback is a different model answering the same request. It can be smaller, from another provider or hosted elsewhere. Before enabling it:
- Run the evaluation set on the backup and record the gap.
- Confirm it supports the same tools and output format.
- Check that data handling terms and region are acceptable.
- Decide which tasks should fail rather than fall back.
- Mark fallback responses in traces so that quality can be compared.
A silent fallback during an outage can turn an availability problem into a correctness problem that nobody notices.
Guardrails
Documentation describes policies that decide how requests and responses proceed based on content and caller, including model-judged guardrails written as a prompt. Model-based checks are flexible and probabilistic: measure how often they miss harmful cases and block good ones, in the languages your users write. Feature support differs between the gateway versions; the serving-endpoint documentation, for example, notes that output guardrails are not supported for embeddings models or streaming. Do not rely on a content filter to stop an unauthorized action. That control belongs in permissions and tool design, as action guardrails explains.
Payload logging
Inference tables store requests and responses as Delta tables in Unity Catalog. They are valuable for debugging, building evaluation sets and audits. They also collect whatever users typed, which may include personal or confidential data. Decide before enabling:
- Who may query the table, and under which approval.
- How long rows are kept and how deletion requests are handled.
- Which fields need masking in views.
- Whether a delay before data appears matters for your alerting, since serving documentation describes delivery within about an hour rather than instantly.
A gateway in miniature
The program applies a token limit per caller, a budget per team and a fallback to a cheaper model. Every decision is recorded.
"""A toy model gateway: per-caller limits, fallback, budgets and cost tags."""
from collections import defaultdict
PRICE = {"large": 8.0, "small": 1.0} # invented price per 1,000 tokens
LIMIT_TPM = {"app-support": 6000, "analyst": 3000}
BUDGET = {"support": 60.0, "finance": 20.0}
class Gateway:
def __init__(self, down=()):
self.down = set(down)
self.used_tpm = defaultdict(int)
self.spend = defaultdict(float)
self.log = []
def call(self, caller, team, tokens, prefer="large"):
if self.used_tpm[caller] + tokens > LIMIT_TPM.get(caller, 0):
return self._record(caller, team, "rate_limited", None, 0)
order = [prefer] + [m for m in PRICE if m != prefer]
for model in order:
if model in self.down:
continue
cost = PRICE[model] * tokens / 1000
if self.spend[team] + cost > BUDGET[team]:
continue # try a cheaper model
self.used_tpm[caller] += tokens
self.spend[team] += cost
status = "ok" if model == prefer else "fallback"
return self._record(caller, team, status, model, cost)
return self._record(caller, team, "blocked_budget", None, 0)
def _record(self, caller, team, status, model, cost):
self.log.append((caller, team, status, model, cost))
return status, model
gw = Gateway()
requests = [("app-support", "support", 2000)] * 4 + [("analyst", "finance", 1500)] * 3
for i, (caller, team, tokens) in enumerate(requests, 1):
status, model = gw.call(caller, team, tokens)
print(f"{i}. {caller:<11} {status:<14} {model or '-'}")
for team, total in sorted(gw.spend.items()):
print(f"{team}: spent {total:.2f} of {BUDGET[team]:.2f}")
print("outage:", Gateway(down={"large"}).call("analyst", "finance", 500))
Output:
1. app-support ok large
2. app-support ok large
3. app-support ok large
4. app-support rate_limited -
5. analyst ok large
6. analyst fallback small
7. analyst rate_limited -
finance: spent 13.50 of 20.00
support: spent 48.00 of 60.00
outage: ('fallback', 'small')
Request six shows a budget causing a fallback: the large model would have exceeded the finance budget, so the small one answered. Requests four and seven hit rate limits. The last line shows the same path during an outage. A real gateway must also handle concurrent requests atomically, reset limit windows over time and settle estimated against actual token counts; this sketch does none of that. It also shows a design question: a cheaper answer for finance may or may not be acceptable, and only the task owner can say.
Where cost appears
The documented cost observability model uses several tables:
| Table | Contains |
|---|---|
system.billing.usage | Databricks consumption records, with gateway details on model serving rows |
system.billing.list_prices | List prices for converting consumption units to money |
system.ai_gateway.usage | Requests through the gateway with requester, tokens, latency and tags |
system.ai_gateway.external_model_spend | Estimated spend for external provider models |
Estimates for external models are based on token usage and published prices and may differ from the provider's invoice. List prices may differ from your contracted rates. Reconcile with invoices before using the numbers for chargeback.
Tags that reach the bill
Documentation distinguishes two kinds of tags. Service tags are set on a gateway service and appear in billing records as custom tags. Request tags are sent in a header with each call and appear in the gateway usage table. For Databricks-hosted models, only service tags reach the billing usage table. Plan accordingly: if finance reports come from billing data, create separate services or tags at the level you need to charge back; use request tags for finer analysis.
| Dimension | Why it matters |
|---|---|
| Team or cost center | Someone is accountable for the spend |
| Application and agent | Finds which product drives cost |
| Environment | Separates testing from production |
| Feature or task type | Shows which uses are worth their price |
Count every component
Model tokens are often only part of the bill. An agent may also use application compute, a SQL warehouse for queries, a search index, a database for state, pipeline jobs, evaluation judges that call models, and stored logs. Managed MCP pricing follows the underlying feature, such as serverless compute for functions or SQL compute for Genie queries. Billing records include identifiers for applications and endpoints that help assign these costs. Build one view per agent that adds the parts, and note which parts are shared and how you split them.
Cost per successful task
Total spend does not say whether the agent is worth it. Divide all cost for a period, including retries, failures and evaluation, by the number of tasks completed correctly. A cheaper model that fails more often can cost more per success once rework is included. Track the figure per task type, next to quality, so that savings that damage quality are visible. Reducing agent costs has a worked method.
Reduce cost in this order
- Remove unnecessary steps, retries and repeated retrieval.
- Shorten context: send relevant passages and compact history.
- Cache stable prefixes and repeated results where safe and supported.
- Route easy tasks to smaller models, proven by evaluation.
- Move work that can wait into batch processing.
- Right-size reserved capacity from measured demand.
- Stop idle compute in development environments.
Capacity planning
Estimate peak tasks per minute, model calls per task and tokens per call, separately for input and output. Multiply, add a margin and load-test with realistic lengths, because short test prompts understate demand. Compare provisioned capacity with per-token cost at your actual utilization: reserved capacity is attractive only when it is busy. Plan what happens beyond the peak, such as queueing, refusing batch work first or falling back. Latency and capacity planning covers the arithmetic.
Budgets and alerts
Documentation describes budgets with per-user thresholds and hard limits for gateway use. Decide which behavior each audience needs: an alert for a production service, a hard stop for experiments. Billing data arrives after use, so budgets based on it cannot stop a fast loop alone. Keep in-application limits, alert on unusual request rates and give on-call staff a switch that disables one agent or route.
A weekly review
- Top agents and users by cost, and changes from the previous week.
- Cost per successful task for the main task types.
- Rate-limit rejections, fallbacks and errors.
- Endpoints or applications with cost and no use.
- Untagged spend, with an owner assigned to fix it.
- Upcoming model retirements or price changes.
An estimate before you build
A rough estimate takes a few minutes and prevents surprises. The numbers below are invented; substitute your measured volumes and current prices.
| Input | Illustrative value |
|---|---|
| Tasks per working day | 2,000 |
| Model calls per task | 4 |
| Input tokens per call | 3,000 |
| Output tokens per call | 400 |
That is 24 million input tokens and 3.2 million output tokens a day. Apply the current input and output rates for your chosen model, then add retries, evaluation judges, search, compute and storage. Repeat the calculation with six calls per task and with context twice as long, because agents tend to grow in both directions after launch. If the pessimistic case would be unaffordable, decide now which limit will prevent it.
Route by task, then verify
Many agents contain steps of very different difficulty: classifying a request, extracting fields, planning and writing a final answer. Giving each step the smallest model that passes its own tests often saves more than any discount. Keep a table of step, model, test set and result, and revisit it when prices or models change. Routing adds a component that can fail, so trace the chosen route and evaluate the router itself. A router that sends hard cases to a weak model can cost more through rework than it saves in tokens.
Common mistakes
| Mistake | Consequence | Instead |
|---|---|---|
| Tagging only per request | Billing reports cannot attribute hosted models | Plan service tags too |
| Untested fallback | Silent quality loss | Evaluate and label it |
| Open payload tables | Sensitive text widely readable | Restrict and set retention |
| Watching only token cost | Surprise from compute and search | Sum all components |
| Relying on delayed budgets | Loops spend before alerts | Limit inside the agent |
| Reserving capacity on guesses | Paying for idle time | Measure first |
Checklist
- The serving mode is chosen from measured load and requirements.
- All model and tool traffic that should be governed passes the gateway.
- Rate limits and in-agent limits are both set.
- Fallbacks are evaluated, labeled and limited to suitable tasks.
- Payload logs have access rules and retention.
- Tags needed for chargeback appear in billing records.
- Cost per successful task is reviewed with quality.
Frequently asked questions
When should I move off pay-per-token?
When load tests or production data show latency, throughput or guarantee needs it cannot meet, and the cost of alternatives at your utilization is justified.
Does the gateway work with models from other companies?
Documentation describes external provider models alongside hosted ones. Check which providers and features are supported for your cloud and how their spend is reported.
Can a guardrail make my agent safe?
It reduces some content risks. Safety also needs least privilege, tool validation, approvals and testing, because filters miss things.
Why does my cost report miss some requests?
Possible reasons include external models billed by the provider, delayed records, traffic that bypasses the gateway and missing tags. Check each before changing the query.
References
- Databricks: Foundation Model APIs
- Databricks: Unity Gateway
- Databricks: gateway features on serving endpoints
- Databricks: gateway cost observability
- Databricks: monitor model serving costs
Where to go next
MLflow Tracing, Evaluation and Monitoring
Connect cost to quality with traces.
Agent FinOps, Budgets and Chargeback
Run cost management as a practice.
Deployment, CI/CD and Troubleshooting
Manage limits and routes as code.