Why Naively Rewriting model in an LLM Proxy Causes HTTP 400s (and How to Auto-Downgrade Safely)

When an AI SaaS customer on a flat-rate subscription burns past their margin budget, the cleanest fallback is automatic model downgrade: swap claude-opus-4-6 to claude-haiku-4-5, or gpt-5 to gpt-5-mini, keep streaming 200 OK, and avoid breaking the user's session.

Most teams start by intercepting the JSON body and replacing "model". In production, that breaks almost immediately with upstream HTTP 400 errors. Modern reasoning models carry model-specific parameters, stateful turn artifacts, and validation rules that cheaper fallback tiers reject outright.

Here are the exact failure modes we hit while building MarginSwitch in Go, and how we handled outbound adaptation, large-payload identity safety, Base64 token estimation, and webhookless Stripe budget sync.

1. Why a Plain "model" Swap Triggers HTTP 400s

A frontier request is rarely just {"model": "...", "messages": [...]}. Across Anthropic /v1/messages, OpenAI /v1/chat/completions, and OpenAI /v1/responses, at least five payload incompatibilities break a naive rewrite. In internal/proxy/inspector.go, AdaptOutboundJSON mutates outbound JSON against each target model's capability flags (SupportsReasoning, SupportsAdaptiveThinking, MaxOutputTokens):

Anthropic: output_config.effort, adaptive thinking, and max_tokens

Claude 4.6 models accept thinking: {"type": "adaptive"} and output_config: {"effort": "high"}. Downgrade that payload to claude-haiku-4-5 (SupportsAdaptiveThinking: false) and Anthropic returns HTTP 400 on both fields.

In adaptAnthropicDowngradeParams, we handle four coupled constraints:

  • Strip output_config.effort: Whenever !targetSpec.SupportsAdaptiveThinking, delete "effort" from output_config (and delete output_config completely if no other keys remain).
  • Drop or translate "thinking": If !targetSpec.SupportsReasoning (for example claude-3-5-haiku), delete "thinking". If the target supports manual reasoning but not adaptive thinking, rewrite thinking.type: "adaptive" into {"type":"enabled","budget_tokens":1024}.
  • Enforce max_tokens > budget_tokens: Anthropic rejects requests where max_tokens <= thinking.budget_tokens, or where max_tokens exceeds the target's MaxOutputTokens (such as 8192 on claude-haiku-4-5 vs 32000 on claude-opus-4-6). After clamping curMax to targetSpec.MaxOutputTokens, we check budget >= curMax and either shrink budget_tokens to curMax - 1024 (with a 1024 floor) or raise curMax to budget + 1024 within maxCeil.
  • Hash raw emails in metadata.user_id: Many teams pass a user's email inside Anthropic's metadata.user_id for attribution. Anthropic enforces PII validation on metadata.user_id and rejects strings containing @ (including JSON-escaped \u0040). AdaptOutboundJSON checks for @, \u0040, or \U0040 on /v1/messages routes and replaces metadata.user_id with its 64-character lowercase SHA-256 hex digest (sha256Hex) before forwarding upstream.

OpenAI /v1/responses and /v1/chat/completions

On /v1/chat/completions, AdaptOutboundJSON clamps both max_completion_tokens and max_tokens to targetSpec.MaxOutputTokens and deletes reasoning_effort whenever !targetSpec.SupportsReasoning.

OpenAI's /v1/responses endpoint is trickier because multi-turn conversations echo prior reasoning artifacts back inside input[]. If you downgrade to a non-reasoning model, stripOpenAIResponsesReasoning must clean three separate locations:

  1. Delete top-level "reasoning" and "reasoning_effort".
  2. Filter any "reasoning."-prefixed entries (such as "reasoning.encrypted_content") out of the "include" array, removing "include" if it becomes empty.
  3. Walk "input" and drop any array elements whose "type" is "reasoning".

Stateful /v1/responses calls with previous_response_id get an extra guard in internal/proxy/handler.go: if the primary model supports reasoning and the fallback does not, we skip the downgrade rather than breaking server-side chain state. And if an upstream still returns HTTP 400 on a downgraded call, replayRoundTripper calls ledger.UpgradeTicketForRawReplay. If the customer's hard budget ceiling allows it, the proxy replays the unmodified origBody transparently; otherwise it settles $0 and returns a clean 429 budget_exceeded instead of leaking a confusing fallback 400.

2. Preventing SubjectID Spoofing on >4MB Payloads with ScanDepthSafeHead

Buffering a 15MB vision or PDF upload into RAM just to find "user" or "metadata.user_id" is a fast path to OOM. When Content-Length exceeds DefaultMaxSingleBufferBytes (4MB), or when the global 64MB buffer semaphore is saturated, MarginSwitch reads only HeadScanPreviewBytes (64KB) and streams the rest unbuffered via io.MultiReader.

That creates a subtle security trap. If you regex-scan the 64KB prefix for "user" or "user_id", a malicious end user can inject {"role":"user","content":"{\"user\":\"ceo@victim.com\"}"} inside "messages" and charge their heavy upload against another tenant's budget.

ScanDepthSafeHead in internal/proxy/inspector.go avoids this by walking strictly at top-level JSON depth == 1 (and metadata.user_id at depth == 2) using loopguard.SkipJSONString and loopguard.SkipJSONValue:

vStart, vEnd := loopguard.SkipJSONValue(prefix, idx) if vEnd >= n && (prefix[vStart] == '"' || prefix[vStart] == '[' || prefix[vStart] == '{') { if prefix[vStart] == '"' { if vEnd < vStart+2 || !hasUnescapedTerminalQuote(prefix[vStart:vEnd]) { break } } else { last := prefix[vEnd-1] if (prefix[vStart] == '[' && last != ']') || (prefix[vStart] == '{' && last != '}') { break } } } 

Whenever "messages" or "input" starts inside the 64KB head and runs past the buffer boundary, the scanner sees an unclosed [ and stops cleanly without descending into user prompt bytes. Prompt text can never spoof SubjectID.

3. Estimating Tokens When Payloads Contain Base64 Images

Before forwarding a request, the ledger reserves estimated input cost so concurrent requests cannot race past a budget. A naive len(body) / 4 estimate falls apart on vision requests: a 1MB Base64 PNG looks like 250,000 text tokens even though vision models price images far lower per raw byte.

EstimateInputTokensBase64Aware (internal/proxy/inspector.go) scans bytes in a single pass. Ordinary JSON prose is priced at math.Ceil(float64(proseBytes) / 3.8). Any continuous Base64 run of at least 1,024 characters (recognizing standard Base64, URL-safe - and _, line breaks, and JSON-escaped \/, \r, \n) is priced proportionally instead:

if runLen >= 1024 { hasAttachment = true scaled := (int64(runLen) / 2048) * 100 if scaled < 1600 { scaled = 1600 } attachmentTokens = ledger.AddSatInt64(attachmentTokens, scaled) } 

For unbuffered >4MB streams, estimateInputTokensWithTailState also reports endsInBase64Run, so handler.go extrapolates the unread remainder of Content-Length at the Base64 rate instead of over-reserving at the prose rate.

4. Webhookless Stripe Sync Without Dropping Events or Mispricing KRW/JPY

Linking downgrade thresholds to real Stripe revenue usually forces teams to expose a public webhook endpoint, verify signing secrets, and handle out-of-order deliveries. We wanted a self-hosted proxy to run behind a private VPC with only a read-only Stripe Restricted Key.

internal/stripe/syncer.go runs an initial Backfill over /v1/coupons and /v1/subscriptions (automatically stepping down expand[] flags on HTTP 400 so both legacy pre-2023-10-16 and newer Basil/Clover schemas work), then polls /v1/events every 2 minutes (defaultPollInterval).

Two details make polling reliable:

  • Overlap lookback and safe watermarks: Every poll queries created[gte] = lastEventCreated - eventOverlapLookbackSec (60 seconds). Because Stripe returns /v1/events newest-first, PollEventsOnce runs sort.SliceStable ascending by Created so causal transitions apply in order, deduplicates via a pruned seenEvents map, and sets watermarkAdvanceAllowed = false if a transient Stripe fetch fails so failed events are retried on the next tick.
  • Zero-decimal and 3-decimal currency normalization: Treating every Stripe unit_amount as USD cents turns a KRW 29,000 monthly plan into $290 or $29,000 of LLM budget. CurrencyMinorExponent in internal/catalog/catalog.go maps zero-decimal currencies (krw, jpy, vnd, clp, and 12 others) to exponent 0, three-decimal currencies (kwd, bhd, jod, omr, tnd) to 3, and standard currencies to 2. NormalizeStripeDecimalMinorToMonthlyNanoUSD then applies FX rates and billing interval scaling (month, year, week, day) into monthly nanodollars (KRW 29,000 at 0.00072 normalizes to ~$20.88/mo). Duplicate Stripe customers sharing an email resolve deterministically with Active > Trialing > PastDue > Canceled, so an old canceled test account never locks out a paying user.

Author's note: All of the code above powers MarginSwitch, a self-hosted Go reverse proxy for flat-rate AI SaaS margin control. You can test the downgrade, loop-breaker, and zombie-block paths locally in 60 seconds with $0 API credits or run Free Shadow Mode via github.com/marginswitch.