DEV Community

DevSignal Engineering
DevSignal Engineering

Posted on Originally published at adpulselabs.hashnode.dev

How We Built a 0-Alloc SimHash Agent Loop Breaker and 86ns Sharded Token Ledger in Go

Flat-rate AI SaaS pricing breaks in three predictable ways: a customer with a past_due Stripe subscription keeps calling your /v1/chat/completions endpoint, a runaway coding or research agent gets stuck retrying the same failing tool call 80 times in a minute, or a heavy user burns more in frontier model tokens than their monthly subscription brings in.

Putting a reverse proxy in front of OpenAI, Anthropic, or Gemini sounds simple until you try to inspect multi-megabyte JSON payloads (with embedded screenshots, 32 KB tools definitions, and SSE streams) on the hot path without blowing up latency or container memory.

Here is how we engineered the hot path of MarginSwitch (GitHub), a self-hosted Go reverse proxy that ties Stripe subscription state to real-time token spend.


1. Why json.Unmarshal Fails on the LLM Proxy Hot Path

A naive proxy unmarshals every incoming request body into map[string]any to extract the model, customer ID, and recent messages. When an agent sends a 32 KB JSON schema in tools plus a 1.5 MB base64 screenshot in messages, encoding/json allocates thousands of heap objects per request and pushes GC pause times through the roof.

Instead of unmarshaling the whole body, we wrote a zero-allocation byte scanner (internal/loopguard/simhash.go) that walks the raw []byte payload directly:

  • SkipJSONString jumps over quoted strings using bytes.IndexByte(body[idx:], '"') while correctly handling odd/even trailing backslash escape counts.
  • SkipJSONValue skips over massive "tools" arrays without allocating a single byte, locating only the trailing turn group (up to 4 KB of the head tool-call arguments + 4 KB of the tail tool result, MaxTurnGroupWindow = 8 * 1024).
  • Short human acknowledgments (SimHashMinNormBytes = 20 — e.g., "yes", "ok", "continue") bypass the loop guard so legitimate users are never false-positived.
  • Over the normalized turn window, we compute a 64-bit SimHash mixed with splitMix64 and compare Hamming distance against a 10-slot ring buffer inside a 60-second window (LoopRingSlots = 10, LoopWindowDuration = 60s, LoopTriggerHits = 6).

Measured on Apple M2 (go test -bench=. -benchmem ./internal/loopguard):

BenchmarkSimHashTurnGroup_32KBTools_ZeroAlloc-8         474234   2507 ns/op   0 B/op   0 allocs/op
BenchmarkSimHashAnthropicOpusSignature_ZeroAlloc-8      292202   5351 ns/op   0 B/op   0 allocs/op
BenchmarkHasTrailingAssistantToolThinking_ZeroAlloc-8   399798   3648 ns/op   0 B/op   0 allocs/op
Enter fullscreen mode Exit fullscreen mode

Skipping a 32 KB tools block and fingerprinting the active agent turn takes 2.51 µs with 0 B/op and 0 allocs/op.


2. Tracking Real-Time Spend in 64 Shards of int64 Nanodollars

Floating-point dollars (float64) accumulate rounding drift across millions of sub-cent token settlements, and a single global sync.Mutex becomes a bottleneck under high concurrency.

In internal/ledger/ledger.go, we made three deliberate choices:

  1. Integer nanodollars (int64) with saturating arithmetic: addSatInt64 and mulSatInt64 clamp at [math.MinInt64, math.MaxInt64] so malformed or huge token counts can never overflow and wrap negative.
  2. 64-shard partitioning (LedgerShards = 64): Each tenant hashes deterministically to a shard with bounded per-shard eviction (maxUnmappedTenantsPerShard = 512, maxLoopRingsPerShard = 1024) so unmapped traffic cannot cause unbounded memory growth.
  3. Billing-period anchoring (periodAnchorUnix): Tracks each customer's actual Stripe billing period start instead of naive YYYY-MM calendar resets, preventing double-dip budget resets across mid-month billing cycles.

Benchmarked on Apple M2 (go test -bench=. -benchmem ./internal/ledger):

BenchmarkResolveCanonicalID_FastPath-8       258423274    5.171 ns/op    0 B/op   0 allocs/op
BenchmarkLedgerReserveAndSettle_64Shards-8    17488737   86.04  ns/op   96 B/op   1 allocs/op
Enter fullscreen mode Exit fullscreen mode

Sub-100 nanosecond reserve-and-settle lets the proxy make real-time allow / downgrade / 402 / 429 decisions without adding measurable overhead to LLM calls.


3. Preventing OOMs & Vision Token Mispricing with ByteSemaphore

When 200 concurrent requests carry large PDFs or base64 screenshots, buffering every body blindly OOM-kills a small 256 MB container.

In internal/proxy/inspector.go:

  • ByteSemaphore uses a lock-free atomic.Int64 CAS loop (DefaultMaxSingleBufferBytes = 4 MB, DefaultGlobalBufferCapBytes = 64 MB) to cap aggregate buffered request bodies across the entire process. Oversized bodies stream through after inspecting a 64 KB head preview (HeadScanPreviewBytes).
  • EstimateInputTokensBase64Aware distinguishes normal prose (~3.8 bytes/token) from contiguous base64 runs (>= 1024 base64 chars, handling JSON-escaped \/, \r, \n, and URL-safe -/_) so a 2 MB PNG image isn't mispriced as 500,000 text tokens before the upstream response returns exact usage.

4. Fail-Open Reliability & Zero-Webhook Stripe Sync

A margin guard must never break healthy paying customers:

  • No Stripe webhook server required: MarginSwitch polls /v1/events with a read-only Stripe key (internal/stripe/syncer.go) and normalizes zero-decimal currencies (JPY, KRW) alongside standard currencies.
  • Fail-open Redis sync: Optional internal Redis RESP2 synchronization shares spend across replicas, falling back gracefully to local sharded state if Redis is unreachable.
  • Free Shadow Mode: Teams can deploy the proxy in shadow mode first to receive per-customer Slack loss receipts without blocking or downgrading a single request until thresholds are calibrated.

You can explore the source, interactive margin calculator, and Docker/Railway quickstart at marginswitch.dev or github.com/marginswitch/marginswitch.

Top comments (0)