{"slug": "how-we-built-a-0-alloc-simhash-agent-loop-breaker-and-56ns-sharded-token-ledger", "title": "How We Built a 0-Alloc SimHash Agent Loop Breaker and 56ns Sharded Token Ledger in Go", "summary": "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.", "body_md": "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.\n\nMulti-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.\n\nWhile 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.\n\n`\"tools\"` Arrays with a 64-Slot Stack Ring Buffer\nWhen 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.\n\nIn `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\"`.\n\nInside that array, a fixed 64-slot ring buffer on the stack avoids allocating offset slices:\n\n``` js\nconst tailRing = 64\nvar bounds [tailRing][2]int\ntotalElems := 0\n```\n\nEach 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.\n\nIf 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.\n\n`safeTailStart` prevents this by counting consecutive backslashes before `tStart`:\n\n```\nfunc safeTailStart(group []byte, tStart int) int {\n    bs := 0\n    for p := tStart - 1; p >= 0 && group[p] == '\\\\'; p-- {\n        bs++\n    }\n    if bs&1 == 1 && tStart+1 < len(group) {\n        return tStart + 1\n    }\n    return tStart\n}\n```\n\nAn 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`.\n\nOn Apple M2 (`Go 1.24`), `BenchmarkSimHashTurnGroup_32KBTools_ZeroAlloc` measures `2.16 µs/op`, `0 B/op`, and `0 allocs/op`.\n\nWe 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`.\n\n`int64` Nanodollar Ledger\nToken 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`).\n\nTo 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.\n\nPlacing 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:\n\n```\ntype ledgerShard struct {\n    mu              sync.Mutex\n    tenants         map[string]*tenantAccount\n    loops           map[string]*loopRing\n    windowSpendNano int64\n    unmappedCount   int\n    _pad            [128 - 40]byte // 8+8+8+8+8+88 = 128 bytes\n}\n```\n\nThe 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.\n\nAll budget and cost arithmetic uses saturating `addSatInt64` and `mulSatInt64`:\n\n```\nfunc addSatInt64(a, b int64) int64 {\n    if b > 0 && a > math.MaxInt64-b {\n        return math.MaxInt64\n    }\n    if b < 0 && a < math.MinInt64-b {\n        return math.MinInt64\n    }\n    return a + b\n}\n```\n\nWithout 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.\n\nUnder `b.RunParallel` across 64 tenants (`BenchmarkLedgerReserveAndSettle_64Shards`, Apple M2, Go 1.24), reserve plus settle runs in `56.94 ns/op`.\n\nEven 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.\n\nWe 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):\n\n```\nfunc (s *ByteSemaphore) TryAcquire(n int64) bool {\n    if n <= 0 {\n        return true\n    }\n    for {\n        cur := s.used.Load()\n        if cur+n > s.limit {\n            return false\n        }\n        if s.used.CompareAndSwap(cur, cur+n) {\n            return true\n        }\n    }\n}\n```\n\nThree rules in `internal/proxy/handler.go` keep peak heap bounded:\n\n`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).\nAt 300 concurrent 400KB requests waiting on TTFT under `GOMEMLIMIT=200MiB`, measured `HeapAlloc` holds at `17.7 MB`.\n\n*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).*", "url": "https://wpnews.pro/news/how-we-built-a-0-alloc-simhash-agent-loop-breaker-and-56ns-sharded-token-ledger", "canonical_source": "https://dev.to/devsignal_eng/how-we-built-a-0-alloc-simhash-agent-loop-breaker-and-56ns-sharded-token-ledger-in-go-5cn8", "published_at": "2026-11-26 23:36:02+00:00", "updated_at": "2026-11-26 23:44:42.355247+00:00", "lang": "en", "topics": ["ai-agents", "ai-infrastructure", "large-language-models", "ai-tools", "mlops"], "entities": ["MarginSwitch", "Go", "OpenAI", "Anthropic", "Stripe", "Apple M2"], "also_reported_by": [], "takeaway": "Fingerprint only the final logical turn group with a stack-allocated 64-slot ring buffer and escape-safe 4KB head/tail splitting to detect agent retry loops at 2.16 µs/op with zero allocations on a 32KB tools array.", "recommendation": {"advice": "Hash only the final turn group and use a fixed stack ring buffer plus backslash-parity checks when slicing JSON, so loop detection stays allocation-free under concurrent tool-calling load.", "playbook": "agent-architecture", "playbook_url": "https://wpnews.pro/playbooks/agent-architecture"}, "alternates": {"html": "https://wpnews.pro/news/how-we-built-a-0-alloc-simhash-agent-loop-breaker-and-56ns-sharded-token-ledger", "markdown": "https://wpnews.pro/news/how-we-built-a-0-alloc-simhash-agent-loop-breaker-and-56ns-sharded-token-ledger.md", "text": "https://wpnews.pro/news/how-we-built-a-0-alloc-simhash-agent-loop-breaker-and-56ns-sharded-token-ledger.txt", "jsonld": "https://wpnews.pro/news/how-we-built-a-0-alloc-simhash-agent-loop-breaker-and-56ns-sharded-token-ledger.jsonld"}}