All Engineering Guides

How to Prevent Infinite Retry Loops in AI Agents

Stop stuck tool-calling and retry loops automatically using SHA-256 request fingerprinting across a 60-second sliding window.

5 min readsource: src/lib/proxy/spend-guard.ts, src/app/api/org/kill-switch/route.ts

Verified Source Facts

60s sliding window5 identical calls429 LOOP_DETECTED403 KILL_SWITCH_ENGAGED15-minute cooldown20 runs per 10 minutes

Infinite retry loops rarely look like intentional abuse. More often, a JSON parser rejects a tool argument, a workflow runner retries immediately inside a while loop, or an orchestration graph bounces between two planning nodes with identical messages. Standard per-minute rate limits often fail to stop these bursts early because total RPM stays below normal production traffic thresholds while token cost compounds.

Noethekx inspects request structure inside checkAndIncrementLoopWindow and blocks repetitive agent traffic before an upstream provider bills for the fifth duplicate turn.

Canonical Request Fingerprinting

Rather than hashing raw JSON strings that change on minor whitespace or trailing parameter variations, computeLoopFingerprint constructs a canonical SHA-256 digest over four normalized components:

  1. The authenticated proxy key ID (keyId).
  2. Normalized model name (normalizeModelName(model)).
  3. The trailing four conversation messages (last_4_messages).
  4. Canonicalized tools or toolCalls payload definitions.

Each incoming call appends its timestamp to loop_windows/{keyId}_{fp16}, pruning entries older than loopWindowSeconds (default 60s sliding window). When the active window reaches the configured threshold (default 5 identical calls), the gateway immediately halts forwarding and returns HTTP 429 with X-Noethekx-Block-Reason: LOOP_DETECTED.

Handling Loop Blocks in Your Agent Runner

Configure your agent retry loop to treat HTTP 429 with LOOP_DETECTED as a terminal state for the current task rather than an exponential-backoff retry trigger.

ts
const response = await fetch('https://nothekx.com/api/v1/chat/completions', {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${process.env.NOETHEKX_KEY ?? 'nk_live_your_key_here'}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    model: 'gpt-4o',
    max_tokens: 256,
    messages: [{ role: 'user', content: 'Call lookup_invoice with id=402' }],
  }),
});

if (response.status === 429 && response.headers.get('X-Noethekx-Block-Reason') === 'LOOP_DETECTED') {
  throw new Error('Agent halted by Noethekx loop detector');
}

Auto-Revocation, Alerts, and Emergency Kill Switches

On Builder and Team plans, tripping the loop guard dispatches a signed webhook and email alert subject to a 15-minute cooldown (alert_cooldowns) so operators receive actionable warnings without inbox floods. When auto_revoke_on_loop is enabled, the offending nk_live_ key is revoked inside the loop-guard transaction.

If an entire environment misbehaves across multiple keys, operators can engage the organization-wide emergency kill switch via /app/keys or POST /api/org/kill-switch with confirmation "PAUSE ALL KEYS". Every active proxy key immediately stops forwarding and returns 403 KILL_SWITCH_ENGAGED on the next request.

You can also exercise the live loop-detection and spend-reservation engine directly from the interactive simulator on the homepage (rate-limited at 20 runs per 10 minutes per IP) before issuing production keys.

Test hard spend caps in the Zero-Key Sandbox

Route requests through https://nothekx.com/api/v1 or inspect pass-through header mode.

How to Prevent Infinite Retry Loops in AI Agents · Noethekx