Ankit Sinha

Design study

Relay

Drop-in LLM and MCP proxy & control plane: instant cost and safety controls via one BASE_URL, backed by durable replay, Docker sandboxing, and multi-agent Postgres concurrency.

TypeScript (nodenext) · Node.js · PostgreSQL · Drizzle · Redis · Zod · Docker · Vitest

The problem #

Drop one proxy layer in front of any LLM or MCP agent—give callers immediate cost and safety wins, with durable execution and concurrency control underneath.

Teams moving agents into production run into five recurring walls: oversized tool outputs bloating prompts, failing tool loops draining budgets, unguarded MCP calls threatening production data, mid-run crashes wiping state, and concurrent agents corrupting shared records. Nobody rewrites an entire agent framework to adopt a new runtime, but changing one BASE_URL or MCP endpoint takes thirty seconds.

Drop-in surface

  • Works unchanged with Claude Code, OpenCode, Cursor, or custom SDKs over HTTP/SSE and MCP STDIO/SSE
  • Cuts API bills 40–70% by offloading oversized tool payloads to retrievable blob pointers
  • Blocks or pauses destructive MCP commands (DROP, rm, external writes) for approval
  • Fork & replay any trace from step N without re-paying for steps 1–N

Systems core underneath

  • Streaming HTTP/SSE and MCP interceptor forwarding chunks with sub-5ms overhead
  • Transactional Postgres step journal (pending/done/failed/unknown) with canonical idempotency
  • Distributed leases, monotonic fencing tokens, and optimistic versions (Keel concurrency core)
  • Ephemeral network-isolated Docker sandboxes & Redis sliding-window circuit breakers

Six layers #

LayerRuntime capabilityBackend mechanism
1. Stream proxy & X-rayDrop-in proxy + per-turn token/latency attributionHTTP/SSE stream tee (<5ms overhead), wire parsers for OpenAI/Anthropic/Gemini, Postgres trace store
2. Context slimming & breakersArtifact blob pointers + runaway loop kill-switchThreshold offloader (>1.5k tokens) + relay_fetch_slice tool, rolling compaction, Redis Lua rate/loop caps
3. MCP firewall & sandboxDeclarative tool blocking, shell isolation & HITL pauseJSON-RPC 2.0 STDIO/SSE multiplexer, Zod policy rules, ephemeral Docker containers, Postgres suspend/resume
4. Durable step journalCrash/429 resume & time-travel fork debuggingUnique idempotency_key journal, Redis backoff queues, copy-on-write session branching from step N
5. Concurrency (Keel core)Multi-agent conflict safety on shared Postgres stateOptimistic version checks, TTL worker leases, monotonic fencing tokens, priority referee & HITL tie queue
6. Trace-to-eval & chaosReproducible regression tests & fault benchmarksrelay export-eval Vitest generator, deterministic crash/timeout/duplicate/429 injection

Pipeline & Postgres schema #

async function executeStep(req: StepRequest) {
  const existing = await store.getCommittedStep(req.idempotencyKey);
  if (existing) return existing.output;                 // crash / retry replay

  await limiter.assertWithinBudget(req.sessionId, req.toolCallHash);

  const verdict = await policy.evaluate(req.tool);       // MCP firewall & HITL
  if (verdict.action === 'deny') return { error: verdict.reason };
  if (verdict.action === 'require_approval') return approvals.suspendRun(req);

  return db.transaction(async (tx) => {
    if (req.resourceId) {
      await tx.assertLeaseAndVersion(req.resourceId, req.fencingToken, req.seenVersion);
    }
    const raw = await sandbox.runTool(req.tool);
    const slim = await context.offloadIfLarge(raw);
    await tx.commitStep(req.idempotencyKey, slim);
    return slim;
  });
}

State lives across five PostgreSQL tables managed with Drizzle: sessions (budget caps, provider config, status), steps (session_id, seq, unique idempotency_key, pending|done|failed|unknown, payloads and token counts), artifacts (offloaded tool blobs and structural summaries), approvals (suspended tool payloads and webhook callbacks), and resources (version, lease_owner, monotonic fencing_token, and lease_expires_at).

Relay step pipeline states: intercept checks idempotency and rate limits, policy evaluates MCP rules or suspends for human approval, execute verifies lease and fencing tokens in Postgres, leading to committed, replayed, or fenced states intercept policy gate execute tx committed replayed suspended fenced TURN ALLOW OK KEY HIT HITL OK STALE / FENCE EVERY LLM TURN & MCP TOOL CALL ROUTES THROUGH ONE IDEMPOTENT PIPELINE

Click any state or step through a trace below to inspect how Relay intercepts, gates, executes, or replays turns.

Select a scenario above to step through live state transitions.

Key decisions #

Drop-in stream tee & artifact pointers

Clients only swap BASE_URL or wrap their MCP server config. Streaming SSE chunks forward immediately while async parsers record tokens and latency. Any tool response exceeding the token threshold moves to PostgreSQL artifacts, leaving only a compact structural summary plus relay_fetch_slice(artifact_id, start, end) in the prompt.

Redis sliding-window circuit breakers

Normalized tool-call hashes feed Redis Lua limiters per session. Repeating the same failing tool call three times or hitting a hard dollar limit terminates the stream cleanly before a runaway loop drains the account.

Zod MCP firewall, Docker sandbox & HITL

Every JSON-RPC tools/call evaluates declarative policy rules into allow, deny, or require_approval. Code/shell tools run inside ephemeral, read-only, network-isolated containers via the Docker Engine API, while guarded operations suspend in PostgreSQL until approved once via the UI or webhook.

Idempotent step journal & fork branching

Every LLM turn and tool execution commits against a unique idempotency_key (pending, done, failed, unknown). On crash or 429 resume, completed steps return from Postgres instantaneously; copy-on-write forks let engineers edit step N and re-run without paying again for steps 1–N−1.

Optimistic versions, leases & fencing tokens (Keel core)

Shared workspace files and database records carry monotonic version counters alongside TTL leases and strictly increasing fencing tokens checked inside the Postgres commit transaction. Slow inference pauses never allow a zombie worker to overwrite newer state.

Production failure scenarios #

ScenarioControl layerInvariant guaranteed
MCP tool dumps an 80k-token file into promptArtifact offloaderPayload stored as blob pointer; active context stays bounded
Agent loops 30 times on a failing shell/API toolRedis circuit breakerTerminated within 3 identical retries before draining spend
Prompt injection tries DROP TABLE or secret egressMCP firewall + HITLBlocked at JSON-RPC boundary or paused for explicit approval
Proxy crashes or hits 429 storm at step 12Step journalResumes at step 12; steps 1–11 replayed with zero duplicates
Two agents concurrently patch the same recordOCC + fencing tokensZero lost updates; stale versions and expired leases rejected

Status #

6layered control
planes
5failure classes
guarded
<5 msSSE proxy
tee overhead
40–70%prompt token
reduction target

Drop-in at the edge via one environment variable; transactional Postgres invariants underneath every turn.

Active design & architecture specification extending Keel's multi-agent Postgres concurrency core with a streaming proxy, artifact offloading, MCP sandboxing, and time-travel trace replay.