Diagram showing the architecture of the system Diagram showing the architecture of the system

Architecture

High-Level Design

Diagram showing the Bun core architecture Diagram showing the Bun core architecture

Key Components

API Gateway (Hono)

Entry point for all client requests. Handles cross-cutting concerns:
  • Rate Limiting — Sliding window per user/IP
  • Idempotency — Safe retries with Idempotency-Key header
  • i18n — Locale detection + translation
  • Logging — Request/response tracking
  • Errors — error.middleware.ts maps LocalizedError and ApplicationError to their own status codes; everything else becomes a 500

Service Routes

Hono routers under apps/monolith/src/services/. There is no separate use-case layer, and no single flow all of them follow:
  • services/users/api.ts’s /register and /login — the only two AuthPort routes: Zod DTO → container.authPort → AuthAdapter; see Ports & Adapters.
  • roles, admin, and organizations — several handlers call container.roles.customRoles, a direct call to the CustomRolesRepository class (DIContainer types this field as the concrete repository, not ICustomRolesRepository, so it is not a swapped-through port the way container.authPort is). Most other handlers in these and other services build a Drizzle query directly against DATABASE_URL, with no port in between. Some handlers validate with a Zod schema first (PATCH routes typically do); several GET handlers take no input to validate.
  • A few routes — including services/auth/api.ts’s /app-token — call Better Auth’s own API (container.auth.api...) directly, or run SQL with no schema at all.
The port flow is the target shape for a new seam, not a description of what every route does today.

Ports & Adapters

The port is an interface this codebase owns; the adapter implements it with someone else’s library. AuthPort → AuthAdapter (Better Auth) is the reference arrangement (ADR-0053), and Ports & Adapters is the guide.
  • PostgreSQL — the only database. Drizzle ORM; Better Auth owns the auth schema
  • BunRedis — cache with in-memory fallback, behind ICache
  • File System — i18n JSON files
There is no packages/domain/ or packages/application/, no entity layer, and no use cases. A port plus an adapter is a complete hexagon here. users-domain once had entities, a repository and use cases; nothing ever called them and they were deleted (ADR-0053).

Design Principles

Data Flow

This is the path for /users/register and /users/login — the only two AuthPort routes. Both are public: they register only validateBody, not authMiddleware, which starts at protected routes like /users/me. The custom-role handlers in roles, admin, and organizations call container.roles.customRoles directly — a concrete CustomRolesRepository, not a port in the middle — which is a separate flow from the one below. Most other routes skip step 4 entirely and call Drizzle or Better Auth’s API directly from the route handler.
Steps 4 and 5 are the whole middle. Earlier versions of this page showed a use case and a domain entity between the route and the repository — neither exists in this backend.

Key Architectural Decisions

1. Monolith Over Microservices

The Bun Core Platform is a monolith (single deployable unit). This is intentional:
  • Simplicity — One server to deploy, monitor, debug
  • Co-location — No network latency between modules
  • Transactions — ACID across modules without distributed coordination
  • MVP speed — Faster to build and iterate
When to split later: If a module (e.g., gateway) needs independent scaling or different deployment cycles.

2. ACP WebSocket as Client — PLANNED, NOT BUILT

Everything in this section and the next, and the “Gateway Prompt Flow” below, describes the ClawUI gateway, which does not exist. packages/clawui-domain/ contains a package.json and nothing else. There is no OpenClawAdapter, no SendPromptUseCase, and no BunSQLiteSessionStore. Kept here as the design of record for tasks 5–10 of the architecture-improvements change; do not read it as a description of the running system.
The gateway module would connect to OpenClaw as a client, not a server:
  • Single WebSocket per agent (multiplexed sessions)
  • JSON-RPC 2.0 message framing over WebSocket
  • Async iterable for streaming responses

3. BunSQLite for ClawUI Sessions (Zero Infra) — PLANNED, NOT BUILT

Login sessions are not stored this way. Better Auth owns the session table in PostgreSQL. The design below is for ClawUI’s own chat sessions, which are unbuilt:
  • Zero infrastructure — embedded SQLite file
  • Fast for session workloads (key-value + history)
  • TTL-based expiration for old sessions
  • Falls back to Redis if configured for distributed setups

Gateway Prompt Flow (SSE) — PLANNED, NOT BUILT

Performance Considerations

Cold Start

  • Bun: ~10ms cold start
  • Hono: < 1ms route matching
  • PostgreSQL connection pool: lazy — drizzle(DATABASE_URL) does not connect until the first query
DIContainer.initialize() is not fast. It connects to NATS, loads translations, and builds the access-control config. If NATS_URL is unset it takes 60 seconds to time out, which is the defect that kept the integration suite from running (task 11.4).

Request Latency

Security

Middleware Stack

  1. Rate Limiting — Per user/IP, sliding window
  2. Idempotency — Prevents duplicate submissions
  3. Authentication — authMiddleware verifies in-process (Better Auth session cookie, or a bearer JWT), not an upstream proxy
  4. i18n — No user input in error messages
  5. Logging — Correlation IDs for audit trails

WebSocket Security

  • Token validation on connect
  • Per-session authorization via _meta.sessionKey
  • No sensitive data in WebSocket URLs

Configuration

All configuration via environment variables. See Configuration Reference.