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.
POST /anthropic/v1/messages
model: "claude-opus-5-5"
thinking: { type: "adaptive" }
max_tokens: 32000→ upstream api.anthropic.com
model: "claude-haiku-5-5"
metadata.user_id: "ms_u_8f9a...c21e"
cost: $0.004 instead of $0.160Rewrites 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.
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.
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.
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.
- 01Start the static container with a read-only Stripe Restricted Key.
- 02Point OPENAI_BASE_URL / ANTHROPIC_BASE_URL to /p/<token>/... (no custom SDK).
- 03Once your receipt confirms real leakage, add MS_LICENSE_KEY and set MS_SHADOW_MODE=0.
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# 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
Measured via go test -bench=. on the 64-shard ledger (Apple M2).
Zero heap allocations per request (`0 B/op`) scanning tool call + result turns.
Bounded 64MB global buffer semaphore + `GOMEMLIMIT=200MiB` for 256MB containers.
Zero external Go runtime dependencies on the hot path; non-root UID 65532.
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)
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)
Starter
RecommendedAutomated 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)
Growth
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
Scale
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