⚡ POWERED BY BUN'S NATIVE PERFORMANCE

Bungate Logo

The Lightning-Fast HTTP Gateway & Load Balancer for the Modern Web. Zero config, maximum performance.

🚀 Single-digit ms latency 🧠 8+ Load Balancing Algorithms 🔒 TLS 1.3 + Security Hardening ⚡ Zero Config Required

Why Choose Bungate?

Built for developers who demand performance without sacrificing developer experience

🚀

Bun-Native Performance

Optimized specifically for Bun's runtime with minimal overhead. Achieves 18K+ requests/second with single-digit millisecond average latency and sub-30ms 99th percentile response times in production benchmarks.

🔧

TypeScript First

Full TypeScript support with comprehensive type definitions for all APIs. Enjoy excellent IDE autocomplete, type safety, and inline documentation as you build.

🎯

Zero Config

Works out of the box with sensible defaults. Get started in seconds without sacrificing power, flexibility, or performance. Production-ready from day one.

🧠

Smart Load Balancing

8 intelligent strategies: round-robin, least-connections, weighted, ip-hash, random, p2c (power-of-two-choices), latency-based, and weighted-least-connections. Session affinity with cookie-based persistence.

🛡️

Production Ready

Circuit breakers, health checks, auto-failover, timeout management, and graceful degradation. Built for reliability and resilience in production environments.

🔐

Enterprise Security

Production-grade security with TLS/HTTPS, input validation, CSRF protection, security headers, JWT key rotation, and trusted proxy validation. Built-in protection against injection attacks, information disclosure, and DoS attacks.

Get Started in Seconds

Production-ready HTTP gateway with full TypeScript support and intelligent load balancing

gateway.ts
// Install: bun add bungate
import { BunGateway } from 'bungate'

// Create gateway with cluster mode & auth
const gateway = new BunGateway({
  server: { port: 3000 },
  cluster: { 
    enabled: true, 
    workers: 4  // Multi-process
  },
  auth: {
    secret: process.env.JWT_SECRET,
    excludePaths: ['/health', '/auth/*'],
  },
  metrics: { enabled: true },
})

// Intelligent load balancing with health checks
gateway.addRoute({
  pattern: '/api/*',
  loadBalancer: {
    strategy: 'least-connections',
    targets: [
      { url: 'http://api1.example.com' },
      { url: 'http://api2.example.com' },
      { url: 'http://api3.example.com' },
    ],
    healthCheck: {
      enabled: true,
      interval: 15000,
      path: '/health',
    },
  },
  circuitBreaker: { 
    enabled: true, 
    failureThreshold: 5 
  },
})

// Rate limiting with JWT auth
gateway.addRoute({
  pattern: '/admin/*',
  target: 'http://admin.example.com',
  rateLimit: {
    max: 100,
    windowMs: 60000,
    keyGenerator: (req) => req.user?.id || 'unknown',
  },
})

await gateway.listen()
console.log('🚀 Bungate cluster running on :3000')

8+ Load Balancing Strategies

Choose the right algorithm for your traffic patterns and architecture

🔄 Round Robin

Equal distribution across all targets. Perfect for stateless services with uniform capacity.

round-robin.ts
gateway.addRoute({
  pattern: '/api/*',
  loadBalancer: {
    strategy: 'round-robin',
    targets: [
      { url: 'http://api1.example.com' },
      { url: 'http://api2.example.com' },
      { url: 'http://api3.example.com' },
    ],
  },
})

🎯 Least Connections

Route to the server with fewest active connections. Ideal for variable request durations.

least-connections.ts
gateway.addRoute({
  pattern: '/api/*',
  loadBalancer: {
    strategy: 'least-connections',
    targets: [
      { url: 'http://api1.example.com' },
      { url: 'http://api2.example.com' },
    ],
  },
})

⚖️ Weighted

Distribute based on server capacity and weights. Perfect for heterogeneous server specs.

weighted.ts
gateway.addRoute({
  pattern: '/api/*',
  loadBalancer: {
    strategy: 'weighted',
    targets: [
      { url: 'http://api1.example.com', weight: 70 },
      { url: 'http://api2.example.com', weight: 20 },
      { url: 'http://api3.example.com', weight: 10 },
    ],
  },
})

🔐 IP Hash

Consistent routing based on client IP. Maintains session affinity for stateful applications.

ip-hash.ts
gateway.addRoute({
  pattern: '/app/*',
  loadBalancer: {
    strategy: 'ip-hash',
    targets: [
      { url: 'http://app1.example.com' },
      { url: 'http://app2.example.com' },
    ],
  },
})

🎲 Random

Randomized distribution for simple, even load. Low overhead with good distribution.

random.ts
gateway.addRoute({
  pattern: '/api/*',
  loadBalancer: {
    strategy: 'random',
    targets: [
      { url: 'http://api1.example.com' },
      { url: 'http://api2.example.com' },
    ],
  },
})

🔀 Power of Two Choices (P2C)

Pick the better of two random targets by load/latency. Balances efficiency with performance.

p2c.ts
gateway.addRoute({
  pattern: '/api/*',
  loadBalancer: {
    strategy: 'p2c',
    targets: [
      { url: 'http://api1.example.com' },
      { url: 'http://api2.example.com' },
      { url: 'http://api3.example.com' },
    ],
  },
})

⚡ Latency

Prefer the target with lowest average response time. Optimizes for user experience.

latency.ts
gateway.addRoute({
  pattern: '/api/*',
  loadBalancer: {
    strategy: 'latency',
    targets: [
      { url: 'http://api1.example.com' },
      { url: 'http://api2.example.com' },
    ],
  },
})

📊 Weighted Least Connections

Combines weights with connection count. Best for mixed capacity with variable load.

weighted-least-connections.ts
gateway.addRoute({
  pattern: '/api/*',
  loadBalancer: {
    strategy: 'weighted-least-connections',
    targets: [
      { url: 'http://api1.example.com', weight: 3 },
      { url: 'http://api2.example.com', weight: 2 },
      { url: 'http://api3.example.com', weight: 1 },
    ],
  },
})

🔐 Enterprise Security Built-In

Production-grade security features that protect against OWASP Top 10 threats

🔒 TLS 1.3 with Auto HTTP Redirect

Encrypted communications with automatic HTTPS upgrade

tls-gateway.ts
const gateway = new BunGateway({
  server: { port: 443 },
  security: {
    tls: {
      enabled: true,
      cert: './cert.pem',
      key: './key.pem',
      minVersion: 'TLSv1.3',
      cipherSuites: [
        'TLS_AES_256_GCM_SHA384',
        'TLS_CHACHA20_POLY1305_SHA256',
      ],
      redirectHTTP: true,  // Auto-redirect :80 → :443
      redirectPort: 80,
    },
  },
})

// All traffic now encrypted with TLS 1.3! 🔐
✓ Man-in-the-Middle Protection ✓ Automatic HTTP → HTTPS ✓ Strong Cipher Suites

🎫 JWT with Zero-Downtime Key Rotation

Secure authentication with automatic key rotation and JWKS support

jwt-auth.ts
const gateway = new BunGateway({
  security: {
    jwtKeyRotation: {
      secrets: [
        { 
          key: process.env.JWT_SECRET_NEW, 
          algorithm: 'HS256',
          kid: '2024-11',
          primary: true  // New tokens use this
        },
        { 
          key: process.env.JWT_SECRET_OLD, 
          algorithm: 'HS256',
          kid: '2024-10',
          deprecated: true  // Still validates old tokens
        },
      ],
      jwksUri: 'https://auth.example.com/.well-known/jwks.json',
      jwksRefreshInterval: 3600000,  // 1 hour
    },
  },
})

gateway.addRoute({
  pattern: '/api/*',
  target: 'http://backend:3000',
  auth: {
    secret: process.env.JWT_SECRET_NEW,
    jwtOptions: {
      algorithms: ['HS256', 'RS256'],
      issuer: 'https://auth.example.com',
    },
  },
})
✓ Zero-Downtime Rotation ✓ JWKS Auto-Refresh ✓ Multi-Algorithm Support

🛡️ Input Validation & Sanitization

Protection against injection attacks and malformed data

input-validation.ts
const gateway = new BunGateway({
  security: {
    inputValidation: {
      maxPathLength: 2048,
      maxHeaderSize: 16384,
      maxHeaderCount: 100,
      allowedPathChars: /^[a-zA-Z0-9\/_\-\.~%]+$/,
      blockedPatterns: [
        /\.\./,           // Directory traversal
        /%00/,           // Null byte injection
        /<script>/i,     // XSS attempts
        /javascript:/i,  // JavaScript protocol
      ],
      sanitizeHeaders: true,
    },
    sizeLimits: {
      maxBodySize: 10 * 1024 * 1024,  // 10 MB
      maxUrlLength: 2048,
    },
  },
})

// Requests with '../../../etc/passwd' → Blocked! 🚫
// Requests with '<script>alert(1)</script>' → Blocked! 🚫
✓ Path Traversal Protection ✓ XSS Prevention ✓ DoS Protection

📋 Comprehensive Security Headers

HSTS, CSP, X-Frame-Options, and more automatically applied

security-headers.ts
const gateway = new BunGateway({
  security: {
    securityHeaders: {
      enabled: true,
      hsts: {
        maxAge: 31536000,        // 1 year
        includeSubDomains: true,
        preload: true,
      },
      contentSecurityPolicy: {
        directives: {
          'default-src': ["'self'"],
          'script-src': ["'self'"],
          'style-src': ["'self'"],
          'frame-ancestors': ["'none'"],
        },
      },
      xFrameOptions: 'DENY',
      xContentTypeOptions: true,
      referrerPolicy: 'strict-origin-when-cross-origin',
    },
  },
})

// Every response gets security headers automatically! 🛡️
✓ Clickjacking Protection ✓ XSS Mitigation ✓ MIME Sniffing Prevention

🌐 Trusted Proxy Validation

Secure client IP extraction with CDN support

trusted-proxies.ts
const gateway = new BunGateway({
  security: {
    trustedProxies: {
      enabled: true,
      trustedIPs: [
        '10.0.0.0/8',      // Private network
        '172.16.0.0/12',   // Private network
      ],
      trustedNetworks: [
        'cloudflare',     // Cloudflare IPs
        'aws',            // AWS CloudFront
        'gcp',            // Google Cloud CDN
        'azure',          // Azure CDN
      ],
      maxForwardedDepth: 3,
    },
  },
})

// Prevents IP spoofing attacks! 🎯
// Only trusts X-Forwarded-For from verified proxies
✓ IP Spoofing Prevention ✓ CDN Support Built-In ✓ CIDR Notation

🏰 Complete Security-Hardened Gateway

All security features combined for maximum protection

production-gateway.ts
import { BunGateway } from 'bungate'

const gateway = new BunGateway({
  server: { port: 443 },
  security: {
    // TLS/HTTPS
    tls: {
      enabled: true,
      cert: process.env.TLS_CERT,
      key: process.env.TLS_KEY,
      minVersion: 'TLSv1.3',
      redirectHTTP: true,
      redirectPort: 80,
    },
    // Input validation
    inputValidation: {
      maxPathLength: 2048,
      sanitizeHeaders: true,
      blockedPatterns: [/\.\./, /%00/, /<script>/i],
    },
    // Security headers
    securityHeaders: {
      enabled: true,
      hsts: { maxAge: 31536000, preload: true },
      contentSecurityPolicy: {
        directives: {
          'default-src': ["'self'"],
          'frame-ancestors': ["'none'"],
        },
      },
      xFrameOptions: 'DENY',
    },
    // Size limits
    sizeLimits: {
      maxBodySize: 10 * 1024 * 1024,
      maxUrlLength: 2048,
    },
    // Trusted proxies
    trustedProxies: {
      enabled: true,
      trustedNetworks: ['cloudflare', 'aws'],
    },
    // JWT key rotation
    jwtKeyRotation: {
      secrets: [
        { key: process.env.JWT_NEW, primary: true },
        { key: process.env.JWT_OLD, deprecated: true },
      ],
    },
  },
})

gateway.addRoute({
  pattern: '/api/*',
  target: 'http://backend:3000',
  auth: {
    secret: process.env.JWT_NEW,
    jwtOptions: { algorithms: ['HS256'] },
  },
  rateLimit: {
    max: 1000,
    windowMs: 60000,
  },
})

await gateway.listen()
console.log('🔒 Production gateway secured!')
✓ OWASP Top 10 Protection ✓ PCI DSS Compliant ✓ Zero-Config Security

🔐 Production-Grade Security

Comprehensive security hardening to protect against modern threats

🔒

TLS/HTTPS Support

Full TLS 1.2+ support with configurable cipher suites, automatic HTTP to HTTPS redirection, and certificate validation. Protect against man-in-the-middle attacks with encrypted communications.

🛡️

Input Validation

Comprehensive input validation and sanitization for paths, headers, and query parameters. Protection against injection attacks, directory traversal, and malformed data with RFC-compliant validation.

🔐

Security Headers

Automatic security headers including HSTS, CSP, X-Frame-Options, X-Content-Type-Options, and Referrer-Policy. Configurable Content Security Policy with report-only mode for testing.

🎫

JWT Key Rotation

Support for multiple JWT secrets with automatic key rotation. JWKS endpoint integration with automatic refresh, zero-downtime key updates, and deprecation warnings for monitoring.

🔍

Trusted Proxy Validation

Secure client IP extraction with trusted proxy configuration. CIDR notation support, predefined trusted networks (Cloudflare, AWS, GCP, Azure), and forwarded header chain validation.

🚫

CSRF Protection

Built-in Cross-Site Request Forgery protection with automatic token generation and validation. Configurable for state-changing operations with path-based exclusions.

📏

Request Size Limits

Configurable limits for request body, headers, URL length, and query parameters. Protection against resource exhaustion and DoS attacks with early rejection and appropriate HTTP status codes.

🔐

Secure Session Management

Cryptographically secure session ID generation with minimum 128 bits of entropy. Automatic expiration, secure cookie attributes (Secure, HttpOnly, SameSite), and session validation.

⚠️

Secure Error Handling

Production-safe error responses that prevent information disclosure. Sanitized error messages, no stack traces in production, and comprehensive internal logging for debugging.

Comprehensive Feature Suite

Enterprise-grade features for modern API gateways

Cluster Mode

Multi-process clustering for maximum CPU utilization. Zero-downtime rolling restarts with SIGUSR2, dynamic scaling (scaleUp/Down/To), and exponential backoff with jitter for worker restarts.

🔄

Load Balancing

8 different strategies including round-robin, least-connections, weighted, ip-hash, latency-based, and power-of-two-choices for optimal traffic distribution.

🌐

Circuit Breaker

Automatic failure detection and recovery with configurable thresholds. Prevent cascading failures and improve system resilience.

🔐

JWT Authentication

Secure JSON Web Token authentication with JWKS support, role-based authorization, and custom claims validation built right in.

Middleware System

Powerful async/await middleware pipeline for custom request/response processing. CORS support, path rewriting, URL transformation, and comprehensive lifecycle hooks.

📊

Observability

Prometheus metrics, structured JSON logging with request tracing, health check APIs, real-time statistics, and custom metric collection for complete visibility.

⏱️

Rate Limiting

Flexible rate limiting with custom key generation. Protect your APIs from abuse with per-IP, per-user, or custom limits and configurable time windows.

Built for Modern Web

Leveraging Bun's speed with developer-friendly APIs

⚡ 19.5K
Requests per Second
🔒 TLS 1.2+
Encrypted Communications
🧠 8+
Load Balancing Strategies
🛡️ Built-in
Security Hardening

Ready to Get Started?

Build high-performance HTTP gateways with Bun today