Installing Bun 1.1 and Bootstrapping an Elysia 1.2 Project
Begin by installing Bun using the official installer. Run the command:
curl -fsSL https://bun.sh/install | bash
After installation, verify the version with bun --version. The output should show 1.1.x or higher. Bun bundles a JavaScriptCore engine, a fast bundler, and a package manager in one binary, eliminating the need for separate Node, npm, and webpack tooling.
Create a new project with:
bun create elysia my-api
cd my-api
bun install
The generated src/index.ts contains a minimal server:
import { Elysia } from 'elysia';
const app = new Elysia()
.get('/', () => 'Hello Elysia')
.listen(3000);
console.log(`🦊 Elysia is running at ${app.server?.url}`);
Start the server using bun src/index.ts. The hot-reload is built-in; any file change triggers an instant restart without manual intervention. Unlike Node’s nodemon, Bun’s watcher is written in Zig and consumes 3–4× less memory under load.
The elysia package at version 1.2.0 depends on Bun’s native fetch, WebSocket, and SQLite APIs. This removes polyfills required in Node environments.
Defining Routes with Elysia Schema Validation
Elysia provides first-party schema validation using a lightweight wrapper around TypeBox. Define input and output contracts directly on routes to eliminate separate Zod + middleware layers.
import { Elysia, t } from 'elysia';
const app = new Elysia()
.post('/users', ({ body }) => createUser(body), {
body: t.Object({
name: t.String({ minLength: 2 }),
email: t.String({ format: 'email' }),
age: t.Optional(t.Number({ minimum: 18 }))
}),
response: t.Object({
id: t.String(),
name: t.String()
})
});
When a request fails validation, Elysia returns a 422 response with a structured error object containing field, value, and message. This behavior is consistent across query, params, headers, and cookies.
Register grouped routes with prefixes:
const userRoutes = new Elysia({ prefix: '/users' })
.get('/', getAllUsers)
.get('/:id', getUserById, {
params: t.Object({ id: t.String() })
})
.post('/', createUser, { body: createUserSchema });
app.use(userRoutes);
Prefixing keeps route files modular while preserving Eden’s type generation later.
Eden: End-to-End Types Without Code Generation
Eden is Elysia’s official client that infers exact request and response types from the server definition. Install it with bun add eden-bun.
On the client side (another Bun or Node project):
import { treaty } from '@elysiajs/eden';
import type { App } from '../src/index';
const api = treaty<App>('http://localhost:3000');
const response = await api.users.post({
name: 'Alice',
email: 'alice@example.com'
});
console.log(response.data.id); // fully typed
Any change to the server schema immediately reflects in the client with TypeScript errors at compile time. No tsc step or OpenAPI generation is required. In practice this removes an entire class of runtime “undefined property” bugs common in separate frontend/backend codebases.
Eden also supports WebSocket, SSE, and streaming responses with full type safety on both ends.
Plugin Architecture and Reusable Modules
Elysia plugins are plain functions that receive and return an Elysia instance. The official @elysiajs/jwt plugin demonstrates the pattern.
import jwt from '@elysiajs/jwt';
const app = new Elysia()
.use(jwt({
name: 'jwt',
secret: process.env.JWT_SECRET || 'super-secret',
exp: '7d'
}))
.post('/login', async ({ jwt, body }) => {
const token = await jwt.sign({ userId: '123' });
return { token };
});
Create a custom plugin for request logging and correlation IDs:
const correlationId = () => new Elysia()
.derive(({ request }) => {
const id = request.headers.get('x-correlation-id') || crypto.randomUUID();
return { correlationId: id };
})
.onRequest(({ correlationId, request }) => {
console.log(`[${correlationId}] ${request.method} ${request.url}`);
});
app.use(correlationId());
Plugins can depend on other plugins using dependencies metadata, allowing deterministic initialization order. Version 1.2 introduced plugin versioning and conflict detection to prevent duplicate registrations.
Rate Limiting Strategies with @elysiajs/rate-limit
Install bun add @elysiajs/rate-limit. The plugin uses an in-memory store by default and can be swapped for Redis.
import rateLimit from '@elysiajs/rate-limit';
app.use(rateLimit({
duration: 60000, // 1 minute window
max: 100, // 100 requests
generator: (req) => req.headers.get('x-forwarded-for') || 'global',
key: 'rate-limit',
skip: (req) => req.url.includes('/health')
}));
For distributed environments, configure Redis backend:
app.use(rateLimit({
store: new RedisStore({
host: 'redis.internal',
port: 6379
}),
duration: 60000,
max: 250
}));
The plugin adds X-RateLimit-Limit, X-RateLimit-Remaining, and X-RateLimit-Reset headers automatically. Trade-off: in-memory store is fastest but does not scale horizontally; Redis adds ~0.8 ms latency per request under 10k RPS but provides consistency across pods.
Authentication Patterns: JWT, OAuth, and Authorization Guards
Combine the JWT plugin with a guard macro for protected routes.
const isAuthenticated = new Elysia()
.use(jwtPlugin)
.derive(async ({ jwt, cookie }) => {
const profile = await jwt.verify(cookie.auth.value);
if (!profile) throw new Error('Unauthorized');
return { user: profile };
});
const protected = new Elysia({ prefix: '/admin' })
.use(isAuthenticated)
.get('/dashboard', ({ user }) => ({ user }));
app.use(protected);
For OAuth2, the community plugin @elysiajs/oauth2 handles Google, GitHub, and Auth0 flows with typed callback handlers. Session storage can use Bun’s built-in SQLite for small deployments:
import { Database } from 'bun:sqlite';
const db = new Database('sessions.db');
db.query('CREATE TABLE IF NOT EXISTS sessions (id TEXT PRIMARY KEY, data TEXT)').run();
This avoids an external database dependency for session storage when traffic is under 5k concurrent users.
Observability: Structured Logging, Metrics, and Tracing
Use the official @elysiajs/opentelemetry plugin (version 1.2 compatible). Configure it once:
import { opentelemetry } from '@elysiajs/opentelemetry';
app.use(opentelemetry({
serviceName: 'api-service',
exporter: {
type: 'otlp',
endpoint: 'https://collector.yourcompany.com'
}
}));
Each request automatically receives a trace ID, span for route handlers, and HTTP metrics (latency, status code distribution). Pair with Bun’s console.log which now outputs JSON when BUN_LOG_FORMAT=json is set.
For custom business metrics, expose a Prometheus endpoint:
import { register } from 'prom-client';
app.get('/metrics', () => register.metrics(), {
response: t.String()
});
Typical production setup forwards logs to Loki, traces to Tempo, and metrics to Prometheus + Grafana. Memory overhead of OpenTelemetry instrumentation on Bun is 8–12 MB at idle versus 45 MB on equivalent Node + express + otel setup.
Database Integration: Bun SQLite, Postgres, and Query Patterns
Bun ships with a high-performance SQLite driver. For a simple analytics API:
import { Database } from 'bun:sqlite';
const db = new Database(':memory:'); // or 'prod.db'
const insert = db.query('INSERT INTO events (type, payload) VALUES ($type, $payload)');
app.post('/track', ({ body }) => {
insert.run({ $type: body.type, $payload: JSON.stringify(body.payload) });
return { success: true };
});
For Postgres, use the native postgres package which Bun accelerates through its fast TCP stack:
import postgres from 'postgres';
const sql = postgres({
host: 'db.internal',
port: 5432,
database: 'app',
username: 'api_user',
password: process.env.DB_PASS
});
app.get('/stats', async () => {
const result = await sql`SELECT COUNT(*) FROM users WHERE active = true`;
return { activeUsers: result[0].count };
});
Connection pooling is automatic. Measured latency for a simple SELECT on a local Postgres instance is 0.6 ms on Bun versus 1.9 ms on Node 20 with the same driver. Trade-off: the postgres package does not yet support prepared statements with named parameters as fluently as Prisma, so complex queries may require raw SQL maintenance.
Testing with Bun’s Built-in Test Runner
Bun includes a Jest-compatible test runner. Create user.test.ts:
import { describe, expect, it } from 'bun:test';
import { treaty } from '@elysiajs/eden';
import { app } from './index';
const api = treaty(app);
describe('User API', () => {
it('creates user with valid data', async () => {
const res = await api.users.post({
name: 'Bob',
email: 'bob@example.com'
});
expect(res.status).toBe(200);
expect(res.data?.id).toBeDefined();
});
it('rejects invalid email', async () => {
const res = await api.users.post({ name: 'Bob', email: 'invalid' });
expect(res.status).toBe(422);
});
});
Run with bun test. The runner executes tests in parallel across multiple threads by default and reports coverage when the --coverage flag is used. Because the same Elysia app instance is imported, tests run against the exact production route definitions.
WebSocket Support for Real-Time Features
Elysia exposes Bun’s native WebSocket with typed events.
app.ws('/chat', {
message: (ws, message) => {
ws.send(`Echo: ${message}`);
},
open: (ws) => {
ws.subscribe('global-chat');
ws.publish('global-chat', 'New user joined');
},
close: (ws) => {
ws.unsubscribe('global-chat');
}
});
Client-side Eden code remains type-safe:
const ws = api.ws.chat.subscribe();
ws.on('message', (data) => console.log(data));
Bun’s WebSocket implementation sustains 45,000 concurrent connections on a single 8-core machine with under 1.2 GB RSS. Compare this to Node’s ws library which typically plateaus around 12,000 connections before memory pressure.
Docker Production Image and Multi-Stage Builds
Use a minimal Dockerfile leveraging Bun’s official image:
FROM oven/bun:1.1 AS base
WORKDIR /app
FROM base AS build
COPY package.json bun.lockb ./
RUN bun install --frozen-lockfile
COPY . .
RUN bun run build
FROM base AS release
WORKDIR /app
COPY --from=build /app .
EXPOSE 3000
ENV NODE_ENV=production
CMD ["bun", "src/index.js"]
The final image size is 68 MB compared to 180 MB for a comparable Node Alpine image. Enable Bun’s production flags with ENV BUN_RUNTIME_FLAGS=--smol to reduce memory allocator overhead for containers with 256 MB limits.
Health check endpoint recommended:
app.get('/health', () => ({ status: 'ok', timestamp: Date.now() }));
Use this with Kubernetes liveness probes on /health with a 2-second timeout.
Benchmarking and Performance Trade-offs
Public benchmarks from the Bun team (bun.sh/benchmarks) show Elysia handling 92,000 requests per second for a simple “hello world” JSON endpoint on a 16-core machine. Equivalent Express on Node 20 reaches approximately 28,000 RPS under identical conditions. These numbers were measured with autocannon -c 100 -d 10.
Realistic production workloads with validation, database calls, and JWT verification reduce the gap. A typical CRUD endpoint on Elysia + Postgres sustains 4,800 RPS while the same logic on Express + Prisma sustains 1,650 RPS on the same hardware. The primary gains come from zero-copy JSON parsing and the absence of V8 overhead.
Trade-offs include:
- Ecosystem maturity: Many npm packages still require
node:polyfills. Theelysiateam maintains a compatibility list; packages using heavy filesystem watchers or native addons may need patches. - Observability tooling: While OpenTelemetry works, some APM agents (Datadog, New Relic) have weaker Bun support as of early 2025. Manual metric instrumentation is sometimes required.
- Memory model: Bun’s garbage collector behaves differently from V8. Long-lived objects in plugins can cause higher baseline RSS until the upcoming generational GC improvements land.
- Deployment platforms: Vercel and Netlify functions still run on Node; use Fly.io, Railway, or self-hosted Kubernetes to gain full Bun benefits.
Advanced Patterns: Streaming Responses and File Uploads
Stream large CSV exports directly from the database:
app.get('/export', () => {
const stream = db.query('SELECT * FROM orders').stream();
return new Response(stream.pipeThrough(csvTransformer()), {
headers: {
'Content-Type': 'text/csv',
'Content-Disposition': 'attachment; filename="orders.csv"'
}
});
});
For file uploads, use Bun’s file API with size limits enforced at the schema level:
.post('/upload', async ({ body }) => {
const file = body.file as File;
if (file.size > 50 * 1024 * 1024) throw new Error('File too large');
await Bun.write(`uploads/${file.name}`, file);
return { url: `/uploads/${file.name}` };
}, {
body: t.Object({ file: t.File() })
});
Combine with virus scanning using clamav daemon sidecar for production SaaS applications handling user uploads.
Migration Strategy from Express or Fastify
Most route logic can be migrated by wrapping existing handler functions inside Elysia route definitions. The largest time sink is usually converting validation from Joi or Zod to Elysia’s t schema. After migration, replace express.json() middleware with Elysia’s built-in parser by removing it entirely.
Run both servers in parallel during cutover using a reverse proxy (Traefik or Nginx) that routes 10 % of traffic to the new Bun service. Monitor error rates and latency percentiles for two weeks before increasing traffic share. This progressive rollout has proven reliable for teams moving codebases of 80+ endpoints.
After migration, expect roughly 60 % reduction in infrastructure costs due to higher density per container and faster cold starts (Bun starts in 11 ms versus 180 ms for a typical Node Express app).
When Not to Choose Elysia and Bun
Edge runtimes such as Cloudflare Workers still favor Hono because of its smaller bundle size and native Workers compatibility. If your team depends on the full npm ecosystem (heavy use of sharp, puppeteer, or complex Redis clients), the compatibility layer may introduce friction that outweighs raw performance gains. Teams already invested in the NestJS ecosystem will find the learning curve steeper than sticking with Fastify adapters.
For internal tools where developer velocity matters more than 2 ms of latency, a tRPC + Next.js App Router stack may still be preferable due to tighter integration with React Server Components.
Monitoring Production Deployments
After deployment, track these key metrics:
- P95 latency under load (target < 45 ms for JSON endpoints)
- Error rate per endpoint (alert above 0.3 %)
- Memory usage per pod (restart if consistently > 85 % of limit)
- Connection count and WebSocket active clients
Use Grafana dashboards with the OpenTelemetry data. Set up alerting on trace sampling where error spans exceed 2 % of total traffic. Bun’s built-in bun --inspect provides a Chrome DevTools compatible debugger for production incidents, allowing heap snapshots without restarting the process.
Regularly review dependency updates with bun upgrade. The Elysia team releases patch versions approximately every 10 days; subscribe to GitHub releases to stay current with security fixes in the validation layer.
This guide equips you with concrete patterns used in production services handling millions of daily requests. The combination of Bun’s runtime performance and Elysia’s developer experience creates a stack that is both faster and safer than traditional Node.js solutions when applied to the right workload.
