Bun is a JavaScript runtime built in Zig that replaces Node.js, npm, and many bundling tools in one binary — with 2–4× faster startup times, significantly higher HTTP throughput on benchmarks, and native TypeScript execution without a transpilation step. Deploying a Bun API server on a Hong Kong VPS reduces cold-start latency for your process restarts and serves more requests per CPU core, making it particularly effective for high-concurrency API workloads serving Asia-Pacific users.
Bun vs Node.js on a VPS
| Factor | Node.js | Bun |
|---|---|---|
| TypeScript execution | Requires tsc or ts-node | Native — no transpile step |
| Startup time | 80–200ms | 10–30ms |
| HTTP requests/sec (simple API) | ~60,000 | ~120,000–160,000 |
| npm compatibility | Full | 90%+ (growing) |
| Package install speed | npm: 30–60s | bun install: 3–8s |
| Built-in test runner | No (need Jest/Vitest) | Yes (bun test) |
| SQLite built-in | No | Yes (bun:sqlite) |
Step 1: Install Bun on HK VPS
<code">curl -fsSL https://bun.sh/install | bash source ~/.bashrc bun --version # 1.1.x # Or via npm (for non-root users) npm install -g bun
Step 2: Create a Bun API with Elysia
Elysia is the leading Bun-first web framework — type-safe, fast, with end-to-end TypeScript inference.
<code"># Create project
mkdir /var/www/bun-api && cd /var/www/bun-api
bun init -y
bun add elysia @elysiajs/cors @elysiajs/bearer @elysiajs/swagger
bun add postgres # PostgreSQL client
# src/index.ts
import { Elysia, t } from 'elysia'
import { cors } from '@elysiajs/cors'
import { bearer } from '@elysiajs/bearer'
import { swagger } from '@elysiajs/swagger'
import { db } from './db'
import { productRoutes } from './routes/products'
import { userRoutes } from './routes/users'
const app = new Elysia()
.use(cors({
origin: ['https://yourdomain.com'],
methods: ['GET', 'POST', 'PUT', 'DELETE'],
}))
.use(bearer())
.use(swagger({
path: '/docs',
documentation: {
info: { title: 'HK VPS API', version: '1.0.0' },
},
}))
// Health check
.get('/health', () => ({
status: 'ok',
timestamp: new Date().toISOString(),
runtime: 'bun',
}))
// Routes
.use(productRoutes)
.use(userRoutes)
// Global error handler
.onError(({ code, error, set }) => {
if (code === 'VALIDATION') {
set.status = 422
return { error: 'Validation failed', details: error.message }
}
if (code === 'NOT_FOUND') {
set.status = 404
return { error: 'Not found' }
}
set.status = 500
return { error: 'Internal server error' }
})
.listen({ port: 3000, hostname: '127.0.0.1' })
console.log(`Bun API running on ${app.server?.url}`)
export type App = typeof app
Route with Validation
<code"># src/routes/products.ts
import { Elysia, t } from 'elysia'
import { db } from '../db'
export const productRoutes = new Elysia({ prefix: '/api/products' })
.get('/', async ({ query }) => {
const { page = 1, limit = 20, category } = query
const offset = (page - 1) * limit
const products = await db`
SELECT id, name, price, category, stock
FROM products
WHERE active = true
${category ? db`AND category = ${category}` : db``}
ORDER BY created_at DESC
LIMIT ${limit} OFFSET ${offset}
`
return { data: products, page, limit }
}, {
query: t.Object({
page: t.Optional(t.Numeric({ minimum: 1 })),
limit: t.Optional(t.Numeric({ minimum: 1, maximum: 100 })),
category: t.Optional(t.String()),
})
})
.get('/:id', async ({ params, set }) => {
const [product] = await db`
SELECT * FROM products WHERE id = ${params.id} AND active = true
`
if (!product) { set.status = 404; return { error: 'Product not found' } }
return product
}, {
params: t.Object({ id: t.String() })
})
.post('/', async ({ body, set }) => {
const [product] = await db`
INSERT INTO products ${db(body)}
RETURNING *
`
set.status = 201
return product
}, {
body: t.Object({
name: t.String({ minLength: 1, maxLength: 255 }),
price: t.Number({ minimum: 0 }),
category: t.String(),
stock: t.Integer({ minimum: 0 }),
})
})
Step 3: PostgreSQL with Bun
<code"># src/db.ts
import postgres from 'postgres'
export const db = postgres(process.env.DATABASE_URL!, {
max: 10,
idle_timeout: 30,
connect_timeout: 10,
types: {
// Auto-parse JSONB columns
jsonb: { to: 114, from: [114], serialize: JSON.stringify, parse: JSON.parse },
},
})
// Run migrations
await db`
CREATE TABLE IF NOT EXISTS products (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
name TEXT NOT NULL,
price NUMERIC(10,2) NOT NULL,
category TEXT NOT NULL,
stock INTEGER NOT NULL DEFAULT 0,
active BOOLEAN DEFAULT true,
created_at TIMESTAMPTZ DEFAULT NOW()
)
`
Step 4: Systemd Process Management
<code">cat > /etc/systemd/system/bun-api.service << 'EOF' [Unit] Description=Bun TypeScript API After=network.target postgresql.service [Service] Type=simple User=bun-api WorkingDirectory=/var/www/bun-api EnvironmentFile=/var/www/bun-api/.env ExecStart=/root/.bun/bin/bun run src/index.ts Restart=always RestartSec=5 [Install] WantedBy=multi-user.target EOF cat > /var/www/bun-api/.env << 'EOF' DATABASE_URL=postgresql://api_user:Pass!@localhost/api_db NODE_ENV=production EOF systemctl enable --now bun-api
Step 5: Nginx
<code">cat > /etc/nginx/sites-available/bun-api << 'EOF'
server {
listen 443 ssl http2;
server_name api.yourdomain.com;
ssl_certificate /etc/letsencrypt/live/api.yourdomain.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/api.yourdomain.com/privkey.pem;
location / {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
EOF
ln -s /etc/nginx/sites-available/bun-api /etc/nginx/sites-enabled/
certbot --nginx -d api.yourdomain.com
nginx -t && systemctl reload nginx
Step 6: Bun’s Built-In SQLite (for lightweight use cases)
<code"># For lightweight data (config, sessions, analytics) — no PostgreSQL needed
import { Database } from 'bun:sqlite'
const db = new Database('/var/data/app.db', { create: true })
db.run(`
CREATE TABLE IF NOT EXISTS sessions (
id TEXT PRIMARY KEY,
user_id INTEGER,
data TEXT,
expires_at INTEGER
)
`)
// Prepared statements — fast and safe
const insertSession = db.prepare(
'INSERT INTO sessions VALUES (?1, ?2, ?3, ?4)'
)
insertSession.run(sessionId, userId, JSON.stringify(data), expiry)
Conclusion
Bun on a Hong Kong VPS is a compelling Node.js alternative for API servers — native TypeScript execution eliminates the build step in development, 2–4× faster HTTP throughput serves more concurrent Asia-Pacific requests per CPU core, and instant startup reduces PM2 restart latency. Elysia’s end-to-end type safety and schema validation make Bun-based APIs both fast and robust. For new TypeScript API projects targeting Asia-Pacific users, Bun on a HK VPS with CN2 GIA is a strong default choice.
Run your API faster: Browse Server.HK Hong Kong VPS plans — Bun’s single binary installs in seconds; a 2 GB plan handles most production API workloads.