An Edge Ingress for t3code: Hono, KV, and the Requests That Should Never Reach Postgres
DEV Community

An Edge Ingress for t3code: Hono, KV, and the Requests That Should Never Reach Postgres

It's 3:17 AM. Your phone vibrates with another retry as the agent you deployed yesterday times out on a long prompt. The mobile app reconnects in vain while your logs fill with cryptic errors.

This is the moment you realize controlling Claude Code or Codex from a phone is a networking problem before it is an agent problem.

The Split: Host Harness and Edge Ingress

t3code from pingdotgg serves as the host-side harness: it stays on the machine with the repo, CLI, and credentials. What doesn't belong there are the browser retries and mobile pings.

In front of it runs a Cloudflare Worker that authenticates commands, validates them, and writes receipts to KV. The host applies the command. The phone only ever sees structured JSON. That split defines the architecture.

The Worker opens no database and calls no model. t3code exposes no public HTTP. A command envelope crosses the edge; the working tree never does.

Why Postgres Does Not Belong in the Worker

Tutorials reverse this truth. They embed a Postgres client in the Worker, copy max connections from a Node service, and dub it a pool. Isolates share no sockets. Mobile client spikes multiply connections, exhausting your platform quota while dashboards stay idle.

No pool exists inside a Worker - only a platform-wide ceiling you can't control. Session and command state live in KV. One long-lived client sits next to t3code on the host if needed.

Bundle size is another failure mode. A Node SDK pulled into the Worker brings buffer, stream, and polyfills you didn't intend. Script limits hit hard: uploads fail, cold starts become noise as isolates unpack compat for button presses.

A JSON-Only Router

This router speaks JSON only. Model traffic remains where t3code manages it. Validation fails closed. Idempotency is a KV key, not a transaction. Success and error share one envelope, sparing the phone client from parsing multiple body shapes.

import { Hono } from "hono";
import { z } from "zod";

type Bindings = {
  COMMANDS: KVNamespace;
  INGRESS_TOKEN: string;
};

const Command = z.object({
  sessionId: z.string().uuid(),
  agent: z.enum(["claude-code", "codex"]),
  action: z.enum(["prompt", "interrupt", "approve"]),
  body: z.string().max(16_000),
  idempotencyKey: z.string().min(8).max(80),
});

const app = new Hono<{ Bindings: Bindings }>();

app.post("/v1/commands", async (c) => {
  const auth = c.req.header("authorization") ?? "";
  if (auth !== `Bearer ${c.env.INGRESS_TOKEN}`) {
    return c.json({ ok: false, error: "unauthorized" }, 401);
  }

  const parsed = Command.safeParse(await c.req.json().catch(() => null));
  if (!parsed.success) {
    return c.json(
      { ok: false, error: "invalid_command", issues: parsed.error.issues },
      400,
    );
  }

  const cmd = parsed.data;
  const id = `cmd:${cmd.sessionId}:${cmd.idempotencyKey}`;

  if (await c.env.COMMANDS.get(id)) {
    return c.json({ ok: true, deduped: true, id });
  }

  await c.env.COMMANDS.put(
    id,
    JSON.stringify({ ...cmd, acceptedAt: Date.now(), status: "queued" }),
    { expirationTtl: 86_400 },
  );

  return c.json({ ok: true, deduped: false, id, status: "queued" }, 202);
});

export default app;

The token is a secret (wrangler secret put INGRESS_TOKEN), not a var in git. nodejs_compat is intentionally absent; if a dependency needs it, that dependency is a candidate to delete before it becomes the bundle.

{
  "$schema": "node_modules/wrangler/config-schema.json",
  "name": "agent-ingress",
  "main": "src/index.ts",
  "compatibility_date": "2025-04-01",
  "workers_dev": false,
  "routes": [
    { "pattern": "agents.example.dev/v1/*", "zone_name": "example.dev" }
  ],
  "kv_namespaces": [
    { "binding": "COMMANDS", "id": "REPLACE_WITH_KV_ID" }
  ]
}

KV Limits and the Fleet Boundary

KV suits a single developer machine but fails for a multi-writer fleet. Reads are fast and replicated; writes are not linearizable queues. Two pollers can see the same queued record. Idempotency keys stop duplicate ingress, and the host must CAS status before running the agent. Past one active host, move to Durable Objects instead of forcing KV as Postgres.

The 16 KB cap prevents runaway pastes from pinning keys; large diffs stay on the git machine. Phone-to-receipt latency - a TLS handshake plus one put - suits approve and interrupt. It's the wrong channel for token streaming, which t3code owns on the host-agent path.

Provider Failover Stays on the Host

Provider failover respects the same boundary. In multi-provider fallback on the host - primary returns 529, second takes the prompt - the OpenAI client uses a relay base URL and never imports into the Worker.

const client = new OpenAI({
  baseURL: "https://b-lost.com/v1",
  apiKey: process.env.RELAY_KEY,
});

Chatty, stateful work stays off the isolate like the DB pool. The Worker checks the bearer, rejects bad envelopes, writes KV. t3code keeps the CLI and tree. The phone receives a 202 and JSON receipt, the only stable contract for a device that sleeps.

As Principal Systems Architect, the hardest operational dilemma is KV's simplicity for idempotency versus the linearizability needed for scaling command queues. Solo it shines; fleets need better primitives.

This ingress has held in benchmarks, but 3 AM scenarios test it hardest. What edge ingress patterns have you battle-tested in production? Has KV disappointed you, or is there a superior primitive for device-orchestrated commands? Share your scars - the comments are open.

Read on DEV Community ↗ ← Back to News

Comments

No comments yet. Start the discussion.