MarginSwitch

Self-hosted Go proxy · Stripe-aware margin control

Keep flat-rate AI subscriptions profitable.

MarginSwitch runs inside your own container between your backend and OpenAI, Anthropic, or Gemini. It reads Stripe subscription revenue read-only to block past_due accounts, auto-downgrade over-budget users without errors, and stop runaway agent loops.

Zero custom SDK·No Stripe webhook server·Prompts stay in your infra
200 OK · Rewritten
cus_whale_91 ($20/mo plan · $10.00 soft cap)active · spent $10.42 / $10.00
Incoming from App
POST /anthropic/v1/messages
model: "claude-opus-5-5"
thinking: { type: "adaptive" }
max_tokens: 32000
Proxy Decision
→ upstream api.anthropic.com
model: "claude-haiku-5-5"
metadata.user_id: "ms_u_8f9a...c21e"
cost: $0.004 instead of $0.160

Rewrites to claude-haiku-5-5, adapts thinking params, streams 200 OK.

Architecture

Three margin leaks standard AI gateways miss

General-purpose proxies route schemas or return blunt rate-limit errors without knowing what each customer actually pays you on Stripe.

01 / STRIPE GATE

Zombie past_due accounts

Missed webhooks let past_due and unpaid accounts keep burning completions. MarginSwitch backfills and polls /v1/events every 2 minutes, merging duplicate customer records by active > trialing > past_due > canceled priority.

02 / MODEL DOWNGRADE

Silent auto-downgrade

When a $20/mo subscriber crosses your target margin ceiling, MarginSwitch rewrites Claude Opus 5.5 → Haiku 5.5, GPT-6.2 Astra → GPT-6 Luna, or Gemini 4 Neon → Flash Lite, strips incompatible thinking/reasoning fields, clamps max_tokens, and streams 200 OK.

03 / LOOP CIRCUIT BREAKER

Agent loop circuit breaker

Stuck tool-calling agents retry the same failing call hundreds of times overnight. A zero-alloc 64-bit SimHash combines ToolCall arguments + normalized ToolResult, blocking the 6th repeat in 60s with HTTP 429 and alerting Slack, Telegram, Discord, or Webhook.

Double Fail-Open reliability

If Redis restarts, your license expires, or a downgraded request gets an upstream HTTP 400 (within hard ceiling), MarginSwitch replays or passes through cleanly so healthy customer traffic never breaks.

Non-chat passthrough & SHA-256 PII masking

/v1/embeddings, multipart audio uploads, /v1/files, and count_tokens stream untouched. Customer emails matched against Stripe are hashed to ms_u_<SHA-256> before leaving your container.

Self-hosted · Zero telemetry

Observe in Free Shadow Mode before blocking anything

Deploy the static Go container in your own Railway (us-east4) or Docker environment. Leave MS_SHADOW_MODE=1 on to receive daily loss receipts via Slack, Telegram, Discord, or the built-in Web UI without modifying a single response.

  1. 01Start the static container with a read-only Stripe Restricted Key.
  2. 02Point OPENAI_BASE_URL / ANTHROPIC_BASE_URL to /p/<token>/... (no custom SDK).
  3. 03Once your receipt confirms real leakage, add MS_LICENSE_KEY and set MS_SHADOW_MODE=0.
docker · ghcr.io/marginswitch/proxy:latest
docker run -d --name marginswitch \
  -p 8080:8080 \
  -e MS_PROXY_TOKEN="tok_replace_with_32_char_secret" \
  -e MS_SHADOW_MODE=1 \
  -e STRIPE_RESTRICTED_KEY="<your-stripe-read-only-key>" \
  -e SLACK_WEBHOOK_URL="<your-slack-or-discord-webhook>" \
  ghcr.io/marginswitch/proxy:latest
app .env · OpenAI / Anthropic / Vercel AI SDK
# Point your existing OpenAI / Anthropic / Vercel AI SDK to your proxy:
OPENAI_BASE_URL="https://your-proxy.up.railway.app/p/tok_.../openai/v1"
ANTHROPIC_BASE_URL="https://your-proxy.up.railway.app/p/tok_.../anthropic"

# Pass the Stripe customer email or ID (raw email is SHA-256 hashed before upstream):
headers: { "x-ms-customer-id": user.email }

Measured in repository

Engineered for 256MB containers and sub-millisecond hot paths

go test -race ./... · 11/11 packages · 5/5 SDK contracts
64-Shard Ledger Reserve + Settle
56.94 ns/op

Measured via go test -bench=. on the 64-shard ledger (Apple M2).

internal/ledger
SimHash Loop Scanner (32KB Tools)
2.16 µs · 0 allocs/op

Zero heap allocations per request (`0 B/op`) scanning tool call + result turns.

internal/loopguard
300x 400KB Concurrent TTFT Heap
17.7 MB HeapAlloc

Bounded 64MB global buffer semaphore + `GOMEMLIMIT=200MiB` for 256MB containers.

marginswitch_design_doc.md
Static Runtime Container
FROM scratch · Go 1.24

Zero external Go runtime dependencies on the hot path; non-root UID 65532.

Dockerfile

Licensing

Flat-rate offline licensing. Observe free forever.

Every paid tier includes +20% burst headroom and a 72-hour Fail-Open grace period. We never break customer traffic over a tier spike.

Free (Shadow Mode)

$0/ month
Observation only · Unlimited

Observe real leakage with zero risk before blocking anything.

  • Unlimited observation in self-hosted Shadow Mode
  • Daily loss receipts via Slack, Telegram, Discord & Webhook
  • Real-time Web UI dashboard (/p/<token>/ui)
  • Stripe read-only sync (no webhook server required)
Deploy Shadow Mode

Starter

Recommended
$49/ month
Up to $5,000/mo monitored

Automated margin protection for early B2B/B2C AI SaaS teams.

  • Up to $5,000/mo monitored LLM spend (+20% / 72h Fail-Open grace)
  • Instant HTTP 402 block for Stripe past_due & canceled users
  • Zero-error auto-downgrade with reasoning parameter sanitization
  • 64-bit SimHash agent loop breaker (HTTP 429 on 6th identical retry)
  • Offline Ed25519 license key (zero calls to our servers)
Get Starter Key

Growth

$199/ month
Up to $25,000/mo monitored

For growing AI products with multi-replica Railway/K8s deploys.

  • Up to $25,000/mo monitored LLM spend (+20% / 72h Fail-Open grace)
  • Multi-replica Redis atomic HINCRBY rolling-deploy sync
  • Multi-currency Stripe normalization (KRW/JPY/USD/EUR + coupons)
  • Signed catalog.json updates + priority email support
Get Growth Key

Scale

$499/ month
Up to $100,000/mo monitored

High-volume flat-rate & agentic workloads at predictable fixed cost.

  • Up to $100,000/mo monitored LLM spend (+20% / 72h Fail-Open grace)
  • Unlimited customer accounts across 64-shard nanodollar ledger
  • Dedicated Stripe account fingerprint binding (fp_...)
  • Custom fallback model profiles & architecture review
Get Scale Key