Hono + Bun for AI Platforms: 6 Production Patterns Worth Stealing
Six backend patterns from QuotyAI, updated for 2026: typed Hono context, streaming, bounded code execution, change streams, RFC 9457 errors, and dependency injection.
AI platforms need streaming, schema-validated protocols, multi-tenant context, and fast iteration. Hono + Bun is a compact way to build those pieces. It is not a complete AI platform: queues, storage, auth, observability, and isolation still need deliberate design.
This post began as a June 30, 2026 snapshot of QuotyAI. The repository has changed since then. The patterns below match the code checked on 2026-11-24, with historical changes called out.
Architecture: One Bun Process, 33 Hono Sub-Apps
QuotyAI dispatches Socket.IO’s /socket.io/ path to the Bun engine and sends everything else to Hono:
import { Server as SocketIOBunEngine, type WebSocketData } from '@socket.io/bun-engine';
import { Server as SocketIOServer } from 'socket.io';
import { app } from './hono-routes.js';
const io = new SocketIOServer();
const engine = new SocketIOBunEngine();
io.bind(engine);
const { websocket } = engine.handler();
export default {
port: 3000,
idleTimeout: 30,
fetch(req: Request, server: Bun.Server<WebSocketData>) {
const url = new URL(req.url);
if (url.pathname === '/socket.io/') {
return engine.handleRequest(req, server);
}
return app.fetch(req, server);
},
websocket,
};
This follows the Bun engine’s Hono integration. The adapter is at 0.1.2; it is still pre-1.0, so test reconnects, timeouts, and graceful shutdown.
One process is a simplicity tradeoff, not a scaling guarantee. CPU-heavy sandbox work or large fan-out may justify separate workers or services.
Pattern 1: Typed Variables Make Context Explicit
The current AppVariables includes the database, DI container, authenticated user, tenant, and language:
export type AppVariables = {
db: QuotyAIMongoDb;
container: DependencyContainer;
user?: AuthUser;
tenantId?: ObjectId;
language?: string;
};
const app = new Hono<{ Variables: AppVariables }>();
Hono checks c.get() and c.set() keys against the environment type. Auth and tenant middleware can populate the context; downstream handlers consume it without an untyped global bag.
Types do not prove that middleware ran. A missing tenant can still be undefined unless the handler or a narrower sub-app enforces it. See the Hono middleware guide.
Pattern 2: SSE or WebSocket, Chosen by Direction
SSE is one-way server-to-client streaming. WebSocket is bidirectional. Use SSE for token output or a simple event feed; use WebSocket when clients subscribe, send commands, or maintain presence.
Hono’s streamSSE is a supported helper:
import { streamSSE } from 'hono/streaming';
app.get('/events', (c) => streamSSE(c, async (stream) => {
await stream.writeSSE({
event: 'message',
data: JSON.stringify({ type: 'ready' }),
});
stream.onAbort(() => console.log('Client disconnected'));
}));
The stream closes when the callback returns. A long-lived event feed needs its own abort handling, heartbeat policy, and backpressure strategy.
Repository update: the current QuotyAI code uses Socket.IO for interactive agent events. The old SSE sink example is preserved as an illustration, not as the current API.
Pattern 3: Bounded Execution Is Not a Security Boundary
QuotyAI executes generated synchronous functions with vm.createContext(), an allowlist, disabled string/Wasm generation, and a five-second timeout. Async plugin hooks also have a separate two-second wall-clock deadline.
import * as vm from 'vm';
function execute(code: string, input: unknown, entrypoint: string) {
const sandbox: Record<string, unknown> = {
Date, Math, Array, Object, JSON,
parseInt, parseFloat, isNaN, isFinite,
};
const context = vm.createContext(sandbox, {
codeGeneration: { strings: false, wasm: false },
});
const script = new vm.Script(`${code}\n__result__ = ${entrypoint};`);
script.runInContext(context, { timeout: 5_000 });
const runner = sandbox.__result__;
if (typeof runner !== 'function') throw new Error('Entrypoint not found');
return Array.isArray(input) ? runner(...input) : runner(input);
}
Important: Node’s documentation says node:vm is not a security mechanism and must not run untrusted code. The timeout bounds synchronous execution; it does not stop every asynchronous or resource-exhaustion attack. Treat this as a constrained evaluator for reviewed code. Truly untrusted code needs an isolated process or sandbox service with CPU, memory, filesystem, and network limits.
Pattern 4: Change Streams Feed Typed Events
MongoDB change streams require a replica set or sharded cluster. QuotyAI watches database changes, emits typed events, and maps selected events to Socket.IO rooms:
eventBus.on('conversation:message:created', (event) => {
io.to(`conversation:${event.conversationId}`)
.emit('conversation:message:created', event);
});
Clients still need authorization before joining tenant, inbox, or conversation rooms. A change stream is not an authorization layer.
A single watcher is a single point of failure. When you scale out, use resumable change-stream cursors and a shared Socket.IO adapter such as Redis. The repository includes @socket.io/redis-adapter, but that does not replace watcher recovery logic. See the change stream requirements.
Pattern 5: RFC 9457 Problem Details
QuotyAI maps errors through hono-problem-details and adds request context. RFC 9457 standardizes fields such as type, title, status, and detail, plus extension members.
app.onError(problemDetailsHandler({
autoInstance: true,
includeStack: process.env.NODE_ENV !== 'production',
localize: (problem, c) => ({
extensions: {
...problem.extensions,
correlationId: c.req.header('x-correlation-id'),
tenantId: c.get('tenantId')?.toString(),
},
}),
}));
Do not expose stack traces, secrets, or raw internal messages in production. Validation hooks need their own configuration; some validator hooks return responses directly unless delegateToHandler: true is set.
Pattern 6: Dependency Levels Keep the Graph Reviewable
QuotyAI uses tsyringe and registers services in dependency order. The comments are a review aid, not a substitute for cycle detection.
container.registerSingleton(EncryptionService); // Level 0
container.registerSingleton(TenantStorage); // Level 1
container.registerSingleton(TenantService); // Level 2
Each route module resolves its services in middleware and places them in typed context. Avoid resolving the entire container from every handler: that hides dependencies and makes tests harder.
Current Stack Snapshot
Constraints from backend/package.json on 2026-11-24:
| Layer | Constraint |
|---|---|
| Runtime | Bun; @types/bun ^1.4.5 |
| HTTP | Hono ^4.13.19 |
| WebSocket | Socket.IO ^4.8.4; @socket.io/bun-engine ^0.1.2 |
| DI | tsyringe ^4.10.0 |
| Validation | Zod 4.6.7 |
| Database | MongoDB ^7.9.1 |
| AI orchestration | LangChain ^1.6.7; LangGraph ^1.7.5 |
| Logging | LogTape ^2.4.2 |
I removed the old cold-start, bundle-size, and production-latency comparison table. Those numbers were not measured under comparable conditions. The old “24 ms sandbox” figure was an undated private observation, not a benchmark you can reproduce.
When This Stack Fits
Use it when your team wants TypeScript across the backend, typed middleware context, and one compact runtime for HTTP plus WebSockets.
Look elsewhere when you need a batteries-included application framework, extensive built-in conventions, or dependencies that rely on Node internals Bun does not implement. Audit the dependency tree before committing.
TL;DR
| Pattern | Takeaway |
|---|---|
| Typed context | Put shared request state behind Variables and enforce tenant/auth rules |
| Streaming | SSE for one-way feeds; Socket.IO for bidirectional interaction |
| Code execution | Bound time and globals, but isolate untrusted code outside the process |
| Change streams | Recover cursors, authorize rooms, and plan for horizontal scale |
| Errors | RFC 9457 with safe extensions and correlation IDs |
| DI | Register by dependency level and resolve explicit services |
Frequently Asked Questions
Why choose Hono over Express for AI platforms?
Hono’s Web Standards core and typed Variables make request context explicit and portable across Bun, Node.js, Deno, and Workers. Express has a larger middleware ecosystem and more operational examples. The right choice depends on your dependencies and team conventions, not bundle size alone.
Is Bun production-ready for AI backend services? Bun supports the HTTP, WebSocket, database, and testing workloads this repository uses, but production readiness is application-specific. Audit native addons and Node-specific dependencies. As of 2026-11-24, QuotyAI uses Bun types ^1.4.5, Socket.IO ^4.8.4, and @socket.io/bun-engine ^0.1.2.
Is Node.js vm a secure sandbox for AI-generated code?
No. Node explicitly says node:vm is not a security mechanism. An allowlist, disabled string/Wasm code generation, and a synchronous timeout reduce accidental access and infinite loops, but untrusted code needs process isolation, resource limits, and a restricted environment.
What changed in the QuotyAI streaming architecture?
The June 2026 snapshot described SSE for agent events. The repository checked on 2026-11-24 delivers interactive events over Socket.IO in the same Bun process. Hono’s streamSSE remains a valid option for one-way server-to-client streams.
Sources
- Hono streaming · Hono middleware
- Bun engine for Socket.IO · Bun releases
- Node.js vm warning
- MongoDB change streams · RFC 9457
- hono-problem-details
- Local backend source and
backend/package.json, checked 2026-11-24
Tags: hono bun typescript ai-platform backend-architecture real-time
Related articles
Hono Grew From 1.4M to 113.6M Weekly npm Downloads. Here's Why.
Hono's npm downloads rose from 1.41M in the week ending 2025-08-04 to 113.59M in the week ending 2026-11-22. Here is what the release history supports—and what it does not.
Read articleWhy I Picked Bun and Hono for QuotyAI's Backend
A bounded case for Bun and Hono on a solo-founder TypeScript backend: less framework ceremony, typed request contracts, and tradeoffs you should audit before switching.
Read articleVibe Coding vs Open Source: The Math Has Changed
AI coding agents make custom glue code cheaper to draft. The build-or-install decision still has to include review, testing, maintenance, and operational risk.
Read article