When several teams call language models directly, the same problems appear in every codebase: provider keys in application config, retry loops that turn one slow provider into a pile of stuck requests, spending discovered on the invoice, and customer NIKs sent to an overseas API because nobody read the prompt.
Our answer is one internal door. Every application calls an OpenAI-compatible gateway with its own key, and the gateway owns provider adapters, failover, budgets, personal-data policy and metering. Applications keep any OpenAI SDK and only change the base URL.
Below are the decisions inside that door, worked through on our Model Gateway & Evals prototype (TypeScript, Hono, SQLite): which errors may fail over, why failover stops at the first streamed token, how to reserve and settle budgets in integer Rupiah, how to recognise a NIK by structure, and what to log. The prototype runs on a built-in provider simulator with synthetic data.
One door, four wire formats
The public surface is POST /v1/chat/completions in the OpenAI format, streamed over Server-Sent Events or returned whole. Applications name an alias such as chat-default, which resolves to an ordered chain of provider and model pairs, so swapping a model is a config change rather than a deploy in five services.
Each adapter implements two methods: complete returns text, a finish reason and usage, and stream yields delta, usage and finish events. The translation underneath is where silent bugs hide:
| Concern | OpenAI Chat Completions | Anthropic Messages | Gemini generateContent | Ollama chat |
|---|---|---|---|---|
| Stream framing | SSE data: lines ending in [DONE] |
SSE with named events | SSE with CRLF line endings | NDJSON |
| System prompt | A message role | Top-level system field; consecutive same-role turns merged |
systemInstruction |
A message role |
seed |
Sent | Not sent | Sent | Sent in options |
| JSON mode | response_format |
Not mapped | responseMimeType |
format |
| Usage while streaming | Final chunk, when stream_options.include_usage is set |
message_start and message_delta events |
usageMetadata |
prompt_eval_count, eval_count |
Treat this table as a capability matrix the router consults. The prototype already refuses what it cannot honour (tools, functions and audio get 422 unsupported_parameter), but writing this article surfaced a gap: the Anthropic adapter maps neither seed nor JSON mode, and nothing stops a JSON-mode request from failing over to it. The fix is a capability check per target that skips incapable targets or refuses at the door. A fallback that quietly ignores half the request is worse than an error, because the caller only notices when its parser breaks.
Failover: classify the failure before you retry
A gateway that retries everything amplifies every outage. The prototype classifies each failed attempt in one exhaustive policy function:
- Transient (timeouts, 5xx, 429, overload, network errors, a stalled stream): retry the same provider, then fail over, and count it against the provider's breaker
- Provider fault (401 or 403 from the provider, an unparseable response): no point retrying the same provider, but the next one may work; it counts against the breaker
- Stop (a 400 from the provider, a client that hung up): the caller's request is the problem, so another vendor will refuse it too; it never fails over and never counts against the breaker
That last row matters: if a client hanging up counted as a provider failure, one buggy application could open the circuit for everybody.
Retries use full-jitter exponential backoff between 250 ms and 2 s, with Retry-After as the floor. The shipped config allows one retry per hosted provider, and every request has a 30 s deadline by default (capped at 120 s). Watch the layers above, too: the official OpenAI Node SDK retries 408, 409, 429, 5xx and connection errors twice by default. Against chat-default, three hosted providers with 2 tries each, a client making 3 tries can cause 18 upstream attempts per user action. Set maxRetries: 0 in gateway clients and retry in one layer only, as the AWS Builders' Library advises.
A breaker per provider, with one half-open probe
The breaker keeps each provider's last 20 calls and opens when at least 5 were made and half failed. After 30 s it lets exactly one probe through: success closes it, failure reopens it. A sketch in the shape of the prototype's breaker:
export type Verdict = "success" | "failure" | "neutral";
type State = "closed" | "open" | "half_open";
export class CircuitBreaker {
private window: boolean[] = [];
private state: State = "closed";
private openedAt = 0;
private probeInFlight = false;
constructor(
private readonly now: () => number,
private readonly windowSize = 20,
private readonly minimumCalls = 5,
private readonly failureRate = 0.5,
private readonly cooldownMs = 30_000,
) {}
get current(): State {
return this.state;
}
tryAcquire(): boolean {
if (this.state === "closed") return true;
if (this.state === "open" && this.now() - this.openedAt < this.cooldownMs) return false;
if (this.probeInFlight) return false;
this.state = "half_open"; // exactly one probe at a time
this.probeInFlight = true;
return true;
}
record(verdict: Verdict): void {
if (this.state === "half_open") {
this.probeInFlight = false;
if (verdict === "success") [this.state, this.window] = ["closed", []];
if (verdict === "failure") [this.state, this.openedAt] = ["open", this.now()];
return;
}
if (verdict === "neutral") return;
this.window = [...this.window, verdict === "failure"].slice(-this.windowSize);
const failed = this.window.filter(Boolean).length;
const tripped = this.window.length >= this.minimumCalls && failed / this.window.length >= this.failureRate;
if (this.state === "closed" && tripped) [this.state, this.openedAt] = ["open", this.now()];
}
}
The injected clock lets the prototype test cooldowns on a virtual clock instead of sleeping. A neutral result during half-open frees the probe slot without deciding anything, so a cancelled probe cannot wedge the breaker. One subtlety: a slow call that started before the circuit opened can land during half-open and be read as the probe; tag the probe if that bites.
The loop, and why it ends at the first token
The router walks the chain, skips open circuits without spending an attempt, and bounds each attempt by its own timeout or the remaining deadline, whichever is smaller:
// Outcome, ProviderError, Target and POLICY follow the classification above.
// For a stream, `call` resolves on the first event: that is the commit point.
export async function route<T>(
chain: Target[], breakers: Map<string, CircuitBreaker>, deadlineAt: number,
call: (target: Target, signal: AbortSignal) => Promise<T>,
): Promise<T> {
const tried: string[] = [];
for (const target of chain) {
const breaker = breakers.get(target.providerId)!;
for (let retry = 0; retry <= target.maxRetries; retry++) {
const remaining = deadlineAt - Date.now();
if (remaining <= 0) throw new Error(`deadline_exceeded: ${tried}`);
if (!breaker.tryAcquire()) { tried.push(`${target.providerId}:circuit_open`); break; } // no attempt spent
const signal = AbortSignal.timeout(Math.min(target.attemptMs, remaining));
try {
const value = await call(target, signal);
breaker.record("success");
return value;
} catch (error) {
const failure = error instanceof ProviderError ? error : new ProviderError(signal.aborted ? "timeout" : "network");
const policy = POLICY[failure.outcome]; // Record<Outcome, { retrySame, failOver }>
breaker.record(policy.failOver ? "failure" : "neutral");
tried.push(`${target.providerId}:${failure.outcome}`);
if (!policy.failOver) throw new Error(`upstream_rejected: ${tried}`);
const jitter = Math.round(Math.random() * Math.min(2_000, 250 * 2 ** retry)); // full jitter
const delay = Math.max(failure.retryAfterMs ?? 0, jitter);
const retrySame = policy.retrySame && retry < target.maxRetries && breaker.current === "closed";
if (!retrySame || delay >= deadlineAt - Date.now()) break;
await sleep(delay); // node:timers/promises
}
}
}
throw new Error(`providers_unavailable: ${tried}`);
}
For streaming, the prototype's call opens the provider stream and waits for its first event, which makes that event the commit point. Before it, a failed attempt is invisible and the next target takes over. After it, a 200 status and some tokens are already on the wire; a fallback would start its own answer from scratch and the user would see two half-answers glued together. So the prototype ends a broken stream with an in-band stream_interrupted event, counts the failure against the provider, and lets the client decide.
Failing over mid-stream requires restarting transparently, which means buffering the whole answer before releasing any of it. That suits short structured outputs nobody watches, and defeats the purpose of streaming chat. Each provider also has a first-token timeout (6 to 12 s in the shipped config) and an idle timeout (8 to 10 s), so a stalled stream fails instead of holding a connection until the deadline.
Hedging: only for short, idempotent calls
Hedging sends a second copy of a slow request and takes whichever answers first. For a classification call of a few hundred tokens it cuts tail latency cheaply; for a 2,000-token generation it doubles the bill for every hedged request, and both copies need a budget reservation. Our rule: hedge only short, idempotent calls with a tight max_tokens, after a delay near the observed p95, and never a stream. The prototype does not hedge; the breaker and failover chain were the better first investment.
Budgets: reserve the worst case, settle the truth
A budget check after the call is a report, not a control. The prototype reserves the most expensive possible outcome before the call, then replaces the reservation with the actual cost. Amounts are integers in micro-Rupiah and prices are Rupiah per million tokens, so tokens multiplied by price is already micro-Rupiah: no division, and no floating point near a budget comparison.
// Money is integer micro-Rupiah. Prices are Rupiah per million tokens, so
// tokens * price is already micro-Rupiah: no division, no floating point.
export type Price = { inputIdrPerMTok: number; outputIdrPerMTok: number };
export type Reservation = { keyId: string; month: string; amountMicro: number };
const cost = (p: Price, inputTokens: number, outputTokens: number): number =>
inputTokens * p.inputIdrPerMTok + outputTokens * p.outputIdrPerMTok;
export function createLedger(wibMonth: () => string) {
const spent = new Map<string, number>(); // "2026-11/key" -> settled micro-Rupiah
const reserved = new Map<string, number>(); // key -> worst cases still in flight
const add = (map: Map<string, number>, k: string, v: number) => map.set(k, Math.max(0, (map.get(k) ?? 0) + v));
return {
// Hold the most expensive outcome across the whole fallback chain.
reserve(keyId: string, budgetIdr: number, chain: (Price | undefined)[], inputEstimate: number, maxTokens: number) {
const prices = chain.filter((p): p is Price => p !== undefined);
if (prices.length !== chain.length) throw new Error("model_not_priced"); // fail closed, never free
const amountMicro = Math.max(...prices.map((p) => cost(p, inputEstimate, maxTokens)));
const month = wibMonth();
const used = (spent.get(`${month}/${keyId}`) ?? 0) + (reserved.get(keyId) ?? 0);
if (used + amountMicro > budgetIdr * 1_000_000) return { ok: false as const, usedMicro: used, amountMicro };
add(reserved, keyId, amountMicro);
return { ok: true as const, reservation: { keyId, month, amountMicro } };
},
// Swap the hold for what the serving model actually cost.
settle(r: Reservation, served: Price, inputTokens: number, outputTokens: number): number {
const actual = cost(served, inputTokens, outputTokens);
add(reserved, r.keyId, -r.amountMicro);
add(spent, `${r.month}/${r.keyId}`, actual);
return Math.max(0, actual - r.amountMicro); // overrun: the input estimate was too low
},
};
}
The reservation covers the whole chain because the gateway cannot know which target will serve. With illustrative prices of Rp 2,500 and Rp 10,000 per million input and output tokens on the primary, and Rp 45,000 and Rp 225,000 on a premium fallback, a 1,200-token prompt estimate with max_tokens of 512 reserves Rp 169.20. If the primary answers with 1,180 input and 240 output tokens, the settled cost is Rp 5.35. That 30-fold gap is the price of safety: a team near its limit gets refused requests that would have fitted. The levers are honest max_tokens caps per alias and keeping expensive models out of default chains.
Three prototype details are worth copying. A model without a price fails closed with model_not_priced, so a typo in the price table never means free traffic. When a provider omits usage, the gateway estimates it (UTF-8 bytes divided by three, plus a small per-message overhead) and flags the row. And the budget month follows the WIB calendar. JavaScript numbers are exact integers up to 2^53, roughly Rp 9 billion in micro-Rupiah: plenty for a monthly ledger per key, not for an all-time organisation total.
The prototype enforces one hard monthly limit per key (402 budget_exceeded); its console merely colours a meter amber from 80%. In production we add a soft limit that alerts the owning team well before the hard stop, because a hard stop nobody saw coming is an outage.
A PII guard that knows Indonesian identifiers
The guard scans every message before anything leaves, and before the cache lookup, so cache keys and cached text only contain guarded content. Per key, the policy is block (422 pii_blocked), redact (a type label) or tokenise (numbered placeholders such as [PHONE_1], kept in a per-request vault and restored in the answer, even when a placeholder is split across stream chunks).
A 16-digit number is not a NIK just because it has 16 digits; order, card and tracking numbers collide with that rule. A NIK encodes province, regency, district, a DDMMYY birth date in which women add 40 to the day, and a serial, and each part can be checked:
const PROVINCES = new Set(
"11 12 13 14 15 16 17 18 19 21 31 32 33 34 35 36 51 52 53 61 62 63 64 65 71 72 73 74 75 76 81 82 91 92 93 94 95 96".split(" "),
);
const NIK_CANDIDATE = /(?<!\d)(?:\d{4}([ .-]?)\d{4}\1\d{4}\1\d{4}|\d{6}([ .-])\d{6}\2\d{4})(?!\d)/g;
const MOBILE = /(?<![\w+])(?:\+62[ .-]?|62|0)8(?:[ .-]?\d){8,11}(?!\d)/g;
const NIK_KEYWORD = /\b(?:nik|ktp|kk)\b|kependudukan|kartu keluarga/;
export type Finding = { kind: "nik" | "phone"; start: number; end: number; confidence: "high" | "medium" };
// PP KK CC DDMMYY SSSS: province, regency, district, birth date (women: day + 40), serial
export function isValidNik(digits: string): boolean {
if (digits.length !== 16 || !PROVINCES.has(digits.slice(0, 2))) return false;
const field = (at: number): number => Number(digits.slice(at, at + 2));
const [regency, district, month, year] = [field(2), field(4), field(8), field(10)];
const day = field(6) > 40 ? field(6) - 40 : field(6);
const daysInMonth = month === 2 ? (year % 4 === 0 ? 29 : 28) : [4, 6, 9, 11].includes(month) ? 30 : 31;
return regency >= 1 && regency <= 79 && district >= 1 && month >= 1 && month <= 12
&& day >= 1 && day <= daysInMonth && digits.slice(12) !== "0000";
}
export function detect(text: string): Finding[] {
const findings: Finding[] = [];
for (const m of text.matchAll(NIK_CANDIDATE)) {
if (!isValidNik(m[0].replace(/\D/g, ""))) continue; // 16 digits alone prove nothing
const before = text.slice(Math.max(0, m.index - 48), m.index).toLowerCase();
const confidence = NIK_KEYWORD.test(before) ? "high" : "medium";
findings.push({ kind: "nik", start: m.index, end: m.index + m[0].length, confidence });
}
for (const m of text.matchAll(MOBILE)) {
findings.push({ kind: "phone", start: m.index, end: m.index + m[0].length, confidence: "high" });
}
return findings;
}
// "0812-0000-1234", "62812 0000 1234" and "+62 812 0000 1234" are one number, one placeholder
export const canonicalPhone = (value: string): string =>
"+62" + value.replace(/\D/g, "").replace(/^(?:62|0)/, "");
How much does structure buy? For uniformly random 16-digit numbers, simple arithmetic says the checks pass about 2.2%, roughly 1 in 46, against 100% for a length-only rule. Real order numbers are not uniformly random, so read that as an order of magnitude: the difference between masking every invoice number in a ticket and masking a few.
The prototype's other detectors follow the same idea. NPWP matches its dotted 15-digit format, or 15 or 16 digits after an NPWP keyword. Cards need a Luhn pass plus an issuer prefix or a card keyword. Bank accounts are only matched as 8 to 18 digits after words such as rekening or virtual account, because bare 10-digit numbers are too common. Overlaps resolve by confidence, then kind, then length, so a number that is both a valid NIK and a valid card is labelled a card unless a NIK keyword precedes it.
That rule shows the real trade-off. Some province codes collide with card prefixes (51 to 53 with Mastercard, 62 with UnionPay) and about 1 in 10 digit strings passes Luhn, so some genuine NIKs get labelled as cards. That is fine: both are masked, and a wrong label is cheap while a miss is not. A false positive costs answer quality, because the model sees [NIK_1] where an order number should be; a false negative is a personal-data transfer you cannot take back. We bias towards over-masking anything that leaves the country, and the prototype's status document is explicit that names and street addresses are not detected.
Log metadata, not content
UU PDP (Law 27 of 2022) treats personal financial data as a specific category of personal data, alongside health and biometric data, and it regulates how personal data is processed and transferred, including transfers outside Indonesia. A gateway helps here only if its own logs do not become the largest copy of customer data in the company.
Structured JSON logs carry a request id and event metadata; the redactor removes authorisation headers, secrets and any field named like a prompt, message body, email, phone, NIK or NPWP, then runs the PII guard in redact mode over the remaining strings. The SQLite request row holds what operators need (key, alias, provider, status, tokens, cost, latency, time to first token, attempts, guard counts) plus previews of the guarded prompt and answer, never raw text, so the console shows [EMAIL_1] rather than an address. The tokenise vault lives only for the request. Retention and archiving are not implemented yet, and production needs both; our UU PDP guide covers the organisational side.
Observability per provider, not per gateway
A gateway-wide error rate hides one failing provider behind two healthy ones. The prototype labels its Prometheus metrics accordingly: gateway_provider_attempts_total by provider and outcome, gateway_time_to_first_token_seconds by provider, gateway_tokens_total by provider, model and direction, gateway_cost_rupiah_total by team and provider, and gateway_circuit_state per provider. Each request row records its attempts and whether a fallback served it, and headers such as x-gateway-provider and x-gateway-cost-micro-idr give calling teams the same facts. Alert on fallback-served traffic climbing, not just on errors: failover hides incidents from users, and therefore from you. For the alerting maths, see our burn-rate alerting guide.
FAQ
Does the PII guard make a cloud provider safe for any data?
No. It lowers what leaves, it does not certify the transfer. Names, addresses and unfamiliar formats pass through, so the legal basis for sending data abroad still has to exist; for the most sensitive flows, route to a local model instead.
What happens to budgets when the gateway restarts?
In the prototype, settled spend is reloaded from SQLite for the current WIB month, while in-flight reservations, rate-limit buckets and breaker windows live in memory and reset. Running more than one instance needs a shared store for those, which the prototype documents but does not yet implement.
Checklist
- Expose one OpenAI-compatible endpoint and route by alias, not vendor model name
- Keep a capability matrix per adapter; skip or refuse targets that cannot honour a request
- Classify failures first; a caller's fault never fails over
- Retry in one layer only, with client SDK retries set to zero
- One breaker per provider, one half-open probe, cancellations neutral
- Treat the first streamed token as the commit point
- Hedge only short idempotent calls, reserving budget for both copies
- Reserve the chain's worst case in integer micro-Rupiah, settle to reported usage, fail closed on missing prices
- Validate NIK by structure and bias egress towards over-masking
- Log metadata and guarded previews, never raw prompts
Primary references
- Microsoft Azure Architecture Center: Circuit Breaker pattern
- AWS Builders' Library: Timeouts, retries and backoff with jitter
- OpenAI API reference: Chat Completions, including
stream_options.include_usage - OpenAI Node SDK README: default retries and
maxRetries - UU No. 27 Tahun 2022 tentang Pelindungan Data Pribadi (JDIH BPK)
Related reading
- Choosing an LLM for Your Business: Open-Source vs Commercial APIs
- UU PDP and App Design: Prepare the Technical Workstream
The full prototype, with its evaluation gate, is described in our Model Gateway & Evals case study, and our AI solutions team builds gateways like it for companies running models across several teams.
