AI & Data18 November 202610 min read

From AI Prototype to Production — Part 5 of 10

AI gateways, model routing and integration: an engineering guide

Once a second team, a second model or a shared privacy rule arrives, every AI call needs the same access, limits, redaction, routing, fallback and telemetry. Part 5 of From AI Prototype to Production treats the gateway as an engineering build: what each component does, when to build it, how it fails, and where MCP and the enterprise event layer fit instead.

#AI Gateway#Model Routing#MCP#Integration Architecture#AI Engineering
A workbench holding a few loose glass blocks, connected by a cyan line to a large, orderly frame of lit modules with a small yellow status light, in a dark workshop over a faint map of southern Africa.

Swartberg Health Administrators, a fictional South African medical scheme administrator, reached its gateway decision by accident. The member-query assistant for contact-centre consultants called one model provider through a small internal library. Then the claims team built a pre-assessment agent with its own provider key, and the complaints team started a nightly job that summarised case notes with a cheaper model. Within a quarter there were three keys, two providers, three different ways of masking ID numbers and no single place to answer the privacy officer's question: which member data left the building last Tuesday, and to whom?

The architecture board agreed that Swartberg now needed an AI gateway. The harder question was what to build inside it. A gateway is a shared runtime on the critical path of every AI feature: each component in it must be configured, tested and operated, and each one left out must be handled elsewhere or accepted as a gap.

CloudNala has covered the gateway's place in the estate before. The Model Gateway Is Not the AI Platform sets out the requirements that justify one, and AI gateway, API gateway and agent gateway separates the three jobs. Who owns which control in an AI request assigns ownership across the boundaries. This part is the engineering companion: component by component, what to build, when, and how it fails.

Direct integration is a real option

Before the components, the base decision. There are two honest patterns for calling models in production.

Direct integration through a thin clientShared AI gateway
What it isA small library every application uses to call the providerA separate runtime all model traffic passes through
Where policy livesIn each application's releaseIn gateway configuration, changed without app releases
New failure domainNoneYes: it needs its own availability target
Cross-application controlOnly for applications that use the libraryEvery consumer, if bypass paths are closed
Cost attributionProvider reporting plus tagsPer key, per team, per route
Good fitOne or two consumers, one provider, policy stableSeveral teams, several models, shared privacy or budget rules

A thin client is a real architecture; do not add a gateway without a requirement describes what it must handle. Swartberg's library stopped being enough because three teams needed one redaction rule and one budget view, and two had already gone around it.

Six components, in request order

AI gateway decision architecture: the model path and the action pathMODEL PATHAssistant,agent harnessor batch jobAI GATEWAY (SHARED RUNTIME)1 Key andidentity2 Redact andprompt policy3 Token limitsand budgets4 Cache(optional)5 Route bytask class6 Fallback andcircuit breakerApproved modelprovidersACTION AND INTEGRATION PATH (OUTSIDE THE AI GATEWAY)Agent harnessproposes a tool callMCP tool serverwraps a capabilityApplication APIchecks permissionClaims and membersystems of recordmodel callsBusiness evente.g. claim capturedEvent layer:topics and queuesIngestion, analyticsand other servicesShared telemetry: route, model version, tokens, cost, cache hit,policy decision and latency (metadata, not content)
The top half is the model path. A request passes through six gateway functions in order, and the cache is optional: build it only when the scorecard says repeated, non-personal questions justify it. The bottom half never passes through the AI gateway. Tool calls go through MCP servers that wrap application capabilities, the application checks permission, and business events travel on the enterprise event layer. Telemetry from both paths records metadata, not content.

A model request through a production gateway passes six functions. The order matters because each step should see only what the previous one has allowed through.

1. Key and identity. Each consumer gets its own credential, mapped to an application, team and cost centre. Swartberg issued separate keys to the assistant, the agent and the batch job. The gateway authenticates to providers with its own managed identity or vaulted keys, so applications never hold provider credentials. Virtual keys are an accountability mechanism explains why a key identifies an application, not a person: the member's identity still travels in the request context for the application to check.

2. Redaction and prompt policy. This is where shared data rules run before anything leaves the organisation. Swartberg masks 13-digit South African ID numbers, scheme membership numbers and banking details in prompts bound for external providers, and blocks requests from consumers not approved for health information. Pattern-based masking catches structured identifiers. It misses a member's name in free text or a diagnosis described in plain words. Redaction reduces exposure; it does not make a prompt anonymous. Test it on real samples and record its miss rate.

3. Token limits and budgets. OWASP lists LLM10:2025 Unbounded Consumption among its top risks for language-model applications and recommends rate limiting, quotas, timeouts and monitoring of resource use. A gateway enforces per-key token rates and period budgets. It cannot see that one agent run has made forty model calls for a single claim. That limit belongs in the agent harness, as Part 2 explains. Set both, and make the gateway's response to a breached budget explicit: reject, queue or downgrade the route.

4. Cache (optional). A response cache returns a stored answer instead of calling the model. Exact-match caching is simple. Semantic caching compares the meaning of a new prompt with earlier ones, which needs an embedding call and a vector-capable store. As a dated example, Microsoft's documentation for AI gateway capabilities in Azure API Management, checked on 18 November 2026, describes semantic caching that uses an embeddings API and an external Redis-compatible cache. Whatever the product, a cache is a second copy of answers with its own retention, access and invalidation rules.

5. Route by task class. Routing maps a task to an approved model. Route by task class (summarise case notes, draft a member reply, pre-assess a claim) rather than letting a classifier pick a model per request. Each route names a model version, pinned, and an evaluation result for that task. Swartberg runs the nightly summaries on a smaller model because its evaluation set showed acceptable quality at lower cost. The claims agent stays on the model it was evaluated against.

6. Fallback and circuit breaker. A circuit breaker stops sending traffic to a provider that is failing; fallback sends it to an alternative. Both are per route. A fallback model that has not passed the same evaluation is a silent change in behaviour, and failover can damage consistency explains when to fail closed instead. Agree one retry owner across client, gateway and provider SDK, or a short outage becomes a retry storm. Who owns the retry sets the rules.

Across all six, telemetry records route, model version, tokens, cost, latency, cache result and policy decision per call. Record metadata by default; do your observability tools store the prompt covers content. OpenTelemetry publishes semantic conventions for generative AI that give these fields common names. When we checked on 18 November 2026 they were still marked as in development and had moved to their own repository, so pin the version your instrumentation follows.

The gateway decision scorecard

The architecture board at Swartberg used one scorecard to decide which components to build now. Score each row on evidence you have today, not on the architecture you expect.

ComponentBuild it whenDefer it whenSwartberg decision (illustrative)
Shared gatewayTwo or more of: several consumers, several models, a shared policy, a cost split finance needs, a fallback that is safeOne consumer, one model, policy stableBuild: three consumers and a shared health-data rule
RouterDifferent tasks have evaluated, different best modelsEvery task uses the same modelBuild: summaries on a smaller model
CacheMany repeated, non-personal questions and a tested invalidation ruleAnswers depend on the member, or source rules change oftenDefer: see worked example
Central policyA rule must apply to every consumer, such as redactionOne consumer can implement it in codeBuild: redaction and consumer approval for health data
Provider diversityA tested route can move without breaking quality or data termsNo second provider has passed evaluation and contract reviewPartial: second provider for summaries only

"Defer" is a decision with a review trigger, not a refusal.

A worked example: is the cache worth it?

These figures are illustrative for a fictional organisation, not benchmarks. Swartberg's contact-centre assistant answers about 30,000 questions a month. A sample of 500 showed about 20% were general benefit questions with no member data, such as what an option covers for optometry. Of those, a replay test found about 40% were close enough to an earlier question that the cached answer was correct.

  • Eligible questions: 30,000 × 20% = 6,000 a month.
  • Correct cache hits: 6,000 × 40% = 2,400 a month.
  • Share of all model calls avoided: 2,400 ÷ 30,000 = 8%.

Against that 8%, the cache adds an embedding call to every eligible request, a store that must be secured like the answers in it, and an invalidation job for every benefit change. Scheme benefit rules change at the start of each year, and a stale cached answer about cover is a complaint waiting to happen. The board deferred the cache and wrote down the trigger: revisit if eligible repeat questions pass 25% of volume or model cost per question doubles. Change the assumptions and the answer may flip.

If you do build one, cache only answers that do not depend on who is asking. A semantic cache that returns one member's answer to another member is a data leak with good latency.

Tools go through MCP, integration goes through the enterprise layer

The bottom half of the diagram never passes through the AI gateway, and that is deliberate.

MCP for tools. The Model Context Protocol (MCP) standardises how an AI application discovers and calls tools and reads context from servers. The current specification (version 2026-07-28, checked on 18 November 2026) states that tools represent arbitrary code execution, that hosts must obtain user consent before invoking any tool, and that descriptions of tool behaviour should be treated as untrusted unless they come from a trusted server. It adds that the protocol cannot enforce these principles itself. At Swartberg, the pre-assessment agent reaches the claims system through an MCP server that wraps one application capability, "fetch claim summary", and the claims application checks that the consultant behind the request may see that claim. See the enterprise MCP gateway for the tool-side control point.

An API and event layer for enterprise integration. MCP connects a model's application to tools. It is not an integration bus. When a claim is captured, a pre-authorisation approved or a member's option changed, that business event belongs on the organisation's existing APIs and event streams, where other systems already consume it with their own contracts. CloudEvents, a Cloud Native Computing Foundation graduated specification (version 1.0.2, checked on 18 November 2026), gives events a common envelope. The agent can consume an event and propose an action through a tool. It should not become the place where systems learn about each other's changes. API, function calling and MCP are different layers draws the line.

A gateway does not make this governed. Model access, tool authority, business permission and event contracts are four different controls with four owners. The gateway holds one of them well.

Failure modes to design for

FailureWhat it looks likeDesign response
BypassA team calls the provider directly with its own keyProvider keys held only by the gateway; egress to provider endpoints blocked elsewhere
Gateway outageEvery AI feature fails at onceAvailability target set by the most critical consumer; tested fail-open or fail-closed per policy
Silent model changeFallback or a provider update changes answersPinned versions; fallback only to evaluated routes; alert on route change
Retry stormA brief provider error multiplies trafficOne retry owner; bounded backoff; circuit breaker
Stale cacheA cached answer outlives the rule it describedInvalidation on source change; time limit; no member-specific entries
Redaction gapAn identifier in free text reaches the providerMeasured miss rate; data classification limits on which consumers may send what

The South African version

Three local factors shape Swartberg's design. This is general information, not legal advice.

First, health information is special personal information under section 26 of the Protection of Personal Information Act (POPIA), and section 72 restricts transfers to a foreign country unless a listed ground applies, such as adequate protection by law or binding agreement. Routing rules in the gateway can enforce which consumers may send which classes of data to which endpoints. They cannot decide whether a transfer is lawful. That decision, and the record of it, belongs to the information officer and the business owner.

Second, provider pricing is often quoted in US dollars, so a rand budget moves with the exchange rate. Set gateway budgets in tokens, report them in rand, and review the conversion monthly.

Third, many model endpoints sit outside South Africa. Measure the added latency per route before promising response times, and budget for it in agents that make several calls per task.

Gateway build checklist

  1. Write down which requirements justify a gateway today, or keep the thin client.
  2. Issue one key per consumer; hold provider credentials only in the gateway.
  3. Test redaction on real samples and record the miss rate.
  4. Set token budgets in the gateway and per-run limits in the harness.
  5. Pin a model version and an evaluation result to every route; fall back only to evaluated routes.
  6. Build a cache only with a worked case and an invalidation rule.
  7. Send tool calls through MCP servers backed by application permission checks, and keep business events on the enterprise event layer.
  8. Close bypass paths and test the gateway's failure behaviour.

Scorecard contribution

This part adds evidence to five rows of the Production Readiness Scorecard. States are Swartberg's, illustrative.

DomainEvidence from this partSwartberg state
ModelRoute table with pinned versions, evaluation per route, approved fallbackstested
Agent/toolsMCP servers wrap application capabilities; permission checked by the applicationhypothesis
ObservabilityPer-call telemetry of route, version, tokens, cost and policy decisiontested
ResilienceCircuit breaker, evaluated fallback, single retry owner, gateway outage testhypothesis
EconomicsPer-key budgets, rand reporting, worked cache casetested

Previous: Part 4, RAG at real scale. Next: Part 6, Secure the whole AI supply chain. All parts are on the series page.

How CloudNala can help

CloudNala runs gateway design reviews for organisations moving from one AI feature to several. We score each component against your current evidence, design the route table and fallback rules, test redaction on your own data samples, work out the cache case with your volumes, and separate model access from tool and event integration. You leave with a component-by-component decision record, the triggers that should reopen it, and a gateway configuration your platform team can operate.


Work with CloudNala

CloudNala helps organisations move from technology ambition to practical execution across cloud, AI, data, platform engineering and digital services.

Whether you are exploring AI, modernising your cloud environment, building a public-sector digital service, or turning an idea into a working MVP, we can help you shape the roadmap and deliver the next step.

Book an AI Gateway Design Review or write to us at consult@cloudnala.co.za

Found this useful?

Share