How We Built a 0-Alloc SimHash Agent Loop Breaker and 56ns Sharded Token Ledger in Go A developer building MarginSwitch, a self-hosted Go 1.24 reverse proxy that ties Stripe subscription revenue to real-time OpenAI and Anthropic token spend, described a zero-allocation SimHash loop breaker and sharded token ledger for LLM proxy hot paths. The loop detector fingerprints only the final logical turn group using a 64-slot stack ring buffer and escape-safe head/tail splitting, benchmarking at 2.16 µs/op with 0 B/op and 0 allocs/op on an Apple M2 for a 32KB tools array. The work targets GC pauses and OOM kills when 300 concurrent tool-calling sessions hit a 256MB container. An LLM reverse proxy sits on a strange latency boundary. Upstream tokens can take 800ms to arrive, so it is tempting to assume proxy CPU and allocations do not matter. That assumption breaks when 300 concurrent tool-calling sessions hit a 256MB container. Multi-turn agent payloads routinely carry 20KB to 100KB of JSON tool schemas, thinking signatures, and conversation history. Running json.Unmarshal into map string any on every request spikes GC pause time and RSS. Holding full request bodies in memory while waiting on upstream Time To First Token TTFT will OOM-kill a small container during an upstream slowdown. While building MarginSwitch a self-hosted Go 1.24 reverse proxy linking Stripe subscription revenue to real-time OpenAI and Anthropic token spend , we kept hot-path loop detection and budget accounting near zero heap and a few microseconds of CPU. Here is how the three core hot-path components work. "tools" Arrays with a 64-Slot Stack Ring Buffer When a tool-calling agent gets stuck in a retry loop, hashing the whole request body fails. Every turn appends history, shifts provider call IDs call , toolu , fc , rs , and rotates cryptographic thinking signatures signature , encrypted content . You only want to fingerprint the final logical turn group: the preceding assistant or function call item through all trailing tool outputs. In internal/loopguard/simhash.go , extractFinalTurnSpan walks top-level JSON keys with SkipJSONString and SkipJSONValue without allocating. On a 32KB "tools" array, SkipJSONValue jumps from to the matching using bytes.IndexByte inside strings and stops once it finds "messages" or "input" . Inside that array, a fixed 64-slot ring buffer on the stack avoids allocating offset slices: js const tailRing = 64 var bounds tailRing 2 int totalElems := 0 Each element's start, end byte range overwrites bounds totalElems& tailRing-1 . Up to 63 parallel tool outputs can trail an assistant message without evicting the initiating assistant or function call item, and older turns are never re-scanned. If the final turn group exceeds MaxTurnGroupWindow 8KB , ExtractFinalTurnGroup splits it into a 4KB head tool call arguments and a 4KB tail trailing error or tool result . Splitting raw JSON at an arbitrary offset risks landing right after the backslash in \" , which would invert quote parity for the entire tail. safeTailStart prevents this by counting consecutive backslashes before tStart : func safeTailStart group byte, tStart int int { bs := 0 for p := tStart - 1; p = 0 && group p == '\\'; p-- { bs++ } if bs&1 == 1 && tStart+1 < len group { return tStart + 1 } return tStart } An odd run of backslashes advances tStart past the escaped character. ComputeTurnSimHash64 then runs scanJSONSegment over head and tail, using hasOddUnescapedQuotes tail to detect a mid-string slice. During scanning, it skips "signature" and "encrypted content" , strips random provider ID prefixes call , toolu , fc , rs , msg , resp , chatcmpl , req , decodes \uXXXX escapes including UTF-16 surrogate pairs inline to UTF-8 so Python ensure ascii=True hashes identically to UTF-8, keeps 1 to 4 digit numbers while dropping 5+ digit timestamps, and ignores short replies under SimHashMinNormBytes = 20 . On Apple M2 Go 1.24 , BenchmarkSimHashTurnGroup 32KBTools ZeroAlloc measures 2.16 µs/op , 0 B/op , and 0 allocs/op . We reuse this zero-allocation turn scanner for HasTrailingAssistantToolThinking . Before downgrading an Anthropic request, we check whether the trailing assistant message contains both a "thinking" or "redacted thinking" block and a "tool use" block. A substring search false-positives whenever user prose mentions "thinking" . HasTrailingAssistantToolThinking structurally inspects only the trailing assistant object's "content" array re-slicing the full turn span if a 4KB thinking block crossed the 4KB cap , still with 0 allocs/op . int64 Nanodollar Ledger Token costs are fractions of a cent per token, and floating-point drift across thousands of requests erodes budget accuracy. MarginSwitch stores all money as int64 nanodollars NanoUSD = 1 000 000 000 , CentNano = 10 000 000 . To avoid global mutex contention, ShardedLedger in internal/ledger/ledger.go hashes each canonical subject key with FNV-1a across 64 shards LedgerShards = 64 . Each shard holds its tenant map, its 10-slot SimHash loopRing map LoopWindowDuration = 60s , tripping at LoopTriggerHits = 6 within Hamming distance <= 3 , and its window spend counter. Placing 64 mutex-guarded structs in a contiguous array 64 ledgerShard causes false sharing when adjacent shards land on the same cache line. While amd64 uses 64-byte cache lines, Apple Silicon arm64 uses 128-byte cache lines. We pad ledgerShard to 128 bytes: type ledgerShard struct { mu sync.Mutex tenants map string tenantAccount loops map string loopRing windowSpendNano int64 unmappedCount int pad 128 - 40 byte // 8+8+8+8+8+88 = 128 bytes } The five fields occupy 40 bytes on 64-bit targets, and pad fills the remaining 88 bytes so every shard sits on its own 128-byte boundary on both arm64 and amd64. All budget and cost arithmetic uses saturating addSatInt64 and mulSatInt64 : func addSatInt64 a, b int64 int64 { if b 0 && a math.MaxInt64-b { return math.MaxInt64 } if b < 0 && a < math.MinInt64-b { return math.MinInt64 } return a + b } Without saturation, a malformed huge token estimate or stacked line items could wrap int64 negative and bypass budget checks. Clamping at math.MaxInt64 ensures overflow fails safe. Under b.RunParallel across 64 tenants BenchmarkLedgerReserveAndSettle 64Shards , Apple M2, Go 1.24 , reserve plus settle runs in 56.94 ns/op . Even with a 0-alloc scanner and a 56ns ledger, upstream TTFT stalls can exhaust RAM. If 300 clients POST 400KB prompts and upstream pauses 10 seconds before sending headers, naive buffering pins 120MB of request bodies, or 240MB if you keep an unmodified copy for replay. We paired GOMEMLIMIT=200MiB with a lock-free ByteSemaphore internal/proxy/inspector.go capped at DefaultGlobalBufferCapBytes = 64 1024 1024 64MB and a per-request cap of DefaultMaxSingleBufferBytes = 4 1024 1024 4MB : func s ByteSemaphore TryAcquire n int64 bool { if n <= 0 { return true } for { cur := s.used.Load if cur+n s.limit { return false } if s.used.CompareAndSwap cur, cur+n { return true } } } Three rules in internal/proxy/handler.go keep peak heap bounded: bufSem.TryAcquire fails under load, the proxy reads only a 64KB preview HeadScanPreviewBytes , stitches it onto r.Body via io.MultiReader , and streams directly upstream. replayRoundTripper.RoundTrip receives upstream headers before SSE streaming starts , meta.releaseBufferAndSem nils origBody and returns the bytes to ByteSemaphore . meta.origBody is retained during TTFT only when ticket.Downgraded == true for HTTP 400 raw replay . At 300 concurrent 400KB requests waiting on TTFT under GOMEMLIMIT=200MiB , measured HeapAlloc holds at 17.7 MB . Author's note: I built these components as part of MarginSwitch https://marginswitch.dev , a self-hosted Go proxy for capping flat-rate AI SaaS margin bleed. You can inspect the source and run the 60-second $0 -credit local simulator or Free Shadow Mode at github.com/marginswitch https://github.com/marginswitch .