Skip to content

A high-performance reverse proxy built with Go and fasthttp. This proxy supports HTTP and WebSocket traffic with advanced features like load balancing, rate limiting, CORS, authentication, and more.

Notifications You must be signed in to change notification settings

hypnguyen1209/fasthttp-reverse-proxy

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

FastHTTP Reverse Proxy

A high-performance reverse proxy built with Go and fasthttp. This proxy supports HTTP and WebSocket traffic with advanced features like load balancing, rate limiting, CORS, authentication, and more.

Features

  • 🚀 High Performance: Built on fasthttp for maximum throughput
  • 🔄 Load Balancing: Round-robin, least connections, and IP hash strategies
  • 🌐 Protocol Support: HTTP/HTTPS and WebSocket proxying
  • 🛡️ Security: Rate limiting, CORS, and authentication support
  • 📊 Health Checks: Built-in health monitoring for upstream services
  • 🔧 Configuration: YAML-based configuration for easy management
  • 🔄 Dynamic Reload: Live configuration updates without downtime
  • 📈 Logging: Structured logging with access logs
  • 🐳 Docker Ready: Includes Dockerfile for containerized deployment
  • 🔒 TLS Support: HTTPS/WSS with custom certificates

Quick Start

Prerequisites

  • Go 1.21 or later
  • Docker (optional, for containerized deployment)

Installation

  1. Clone or download the source code

  2. Install dependencies:

    go mod download
  3. Build the application:

    go build -o fasthttp-reverse-proxy main.go
  4. Run the proxy:

    ./fasthttp-reverse-proxy -config config.yml -routes routes.yml

Docker Deployment

  1. Using the examples directory: The project includes a complete Docker setup in the examples/ directory with docker-compose configuration and test backends.

    cd examples/
    docker-compose up --build
  2. Manual Docker build:

    docker build -f examples/Dockerfile -t fasthttp-reverse-proxy .
  3. Run the container:

    docker run -p 8080:8080 \
      -v $(pwd)/config.yml:/root/config.yml \
      -v $(pwd)/routes.yml:/root/routes.yml \
      fasthttp-reverse-proxy \
      -config /root/config.yml -routes /root/routes.yml

For detailed Docker examples and test configurations, see the examples/ directory.

Configuration

Server Configuration (config.yml)

# Server Configuration
server:
  host: "0.0.0.0"                    # Listen address
  port: 8080                         # Listen port
  read_timeout: "30s"                # Request read timeout
  write_timeout: "30s"               # Response write timeout
  idle_timeout: "120s"               # Connection idle timeout
  max_conns_per_ip: 100             # Max connections per IP
  max_request_body_size: "10MB"      # Max request body size

# Logging Configuration
logging:
  level: "info"                      # Log level: debug, info, warn, error
  format: "json"                     # Log format: json, text
  enable_access_log: true            # Enable access logging

# Health Check Configuration
health:
  path: "/health"                    # Health check endpoint
  enabled: true                      # Enable health checks

# Load Balancer Configuration
load_balancer:
  strategy: "round_robin"            # Load balancing strategy

# SSL/TLS Configuration
tls:
  enabled: false                     # Enable HTTPS
  cert_file: ""                      # Path to certificate file
  key_file: ""                       # Path to private key file
  auto_redirect_http: false          # Auto redirect HTTP to HTTPS

# CORS Configuration
cors:
  enabled: true                      # Enable CORS
  allowed_origins: ["*"]             # Allowed origins
  allowed_methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"]
  allowed_headers: ["*"]             # Allowed headers
  expose_headers: []                 # Exposed headers
  allow_credentials: false           # Allow credentials
  max_age: 86400                     # Preflight cache duration

# Rate Limiting
rate_limit:
  enabled: false                     # Enable rate limiting
  requests_per_minute: 100           # Requests per minute per IP
  burst: 10                          # Burst capacity

Routes Configuration (routes.yml)

routes:
  # API Routes with Load Balancing
  - path: "/api/v1/*"
    method: "*"                      # All HTTP methods
    targets:
      - url: "http://localhost:3001"
        weight: 1
      - url: "http://localhost:3002"
        weight: 1
    type: "http"
    timeout: "30s"
    retry_count: 3
    strip_path: false                # Keep full path
    health_check:
      path: "/health"
      interval: "30s"
      timeout: "5s"
    headers:
      add:
        X-Forwarded-Proto: "http"
      remove:
        - "X-Internal-Header"

  # WebSocket Route
  - path: "/ws/*"
    method: "*"
    targets:
      - url: "ws://localhost:4001"
        weight: 1
    type: "websocket"
    timeout: "300s"
    strip_path: false

  # Static Files with Caching
  - path: "/static/*"
    method: "GET"
    targets:
      - url: "http://localhost:8081"
        weight: 1
    type: "http"
    timeout: "10s"
    retry_count: 1
    strip_path: true                 # Remove /static prefix
    cache:
      enabled: true
      ttl: "1h"

  # Admin Panel with Authentication
  - path: "/admin/*"
    method: "*"
    targets:
      - url: "http://localhost:9000"
        weight: 1
    type: "http"
    timeout: "60s"
    retry_count: 2
    auth:
      type: "basic"
      username: "admin"
      password: "secret"

  # Default Route (catch-all)
  - path: "/*"
    method: "*"
    targets:
      - url: "http://localhost:8080"
        weight: 1
    type: "http"
    timeout: "30s"
    retry_count: 1

Command Line Options

./fasthttp-reverse-proxy [options]

Options:
  -config string
        Path to configuration file (default "config.yml")
  -routes string
        Path to routes file (default "routes.yml")

Route Configuration Options

Basic Route Properties

  • path: URL path pattern (supports wildcards with *)
  • method: HTTP method (* for all methods, or specific like GET, POST)
  • targets: List of upstream servers with weights
  • type: Route type (http or websocket)
  • timeout: Request timeout duration
  • retry_count: Number of retry attempts
  • strip_path: Remove matched path prefix from upstream request

Advanced Features

Health Checks

health_check:
  path: "/health"        # Health check endpoint
  interval: "30s"        # Check interval
  timeout: "5s"          # Check timeout

Header Manipulation

headers:
  add:                   # Headers to add
    X-Custom: "value"
  remove:                # Headers to remove
    - "X-Internal"

Authentication

auth:
  type: "basic"          # basic, bearer, or none
  username: "user"       # Username for basic auth
  password: "pass"       # Password/token

Caching

cache:
  enabled: true          # Enable response caching
  ttl: "1h"             # Cache TTL

Load Balancing Strategies

  • round_robin: Distribute requests evenly across targets
  • least_connections: Route to target with fewest active connections
  • ip_hash: Route based on client IP hash (sticky sessions)

Performance Features

  • Connection Pooling: Reuses connections to upstream servers
  • Zero-Copy Operations: Minimal memory allocations
  • Concurrent Processing: Handles thousands of concurrent connections
  • Efficient Routing: Fast path matching with wildcards

Dynamic Configuration Reload

The proxy supports live configuration updates without requiring a restart. This feature enables zero-downtime configuration changes.

How It Works

The proxy monitors configuration files for changes using file system events and automatically reloads them when modifications are detected. Additionally, you can trigger manual reloads using system signals.

Automatic Reload

The proxy watches both config.yml and routes.yml files for changes:

# Start the proxy
./fasthttp-reverse-proxy -config config.yml -routes routes.yml

# In another terminal, modify the configuration
vim config.yml

# The proxy will automatically detect the change and reload
# Check the logs for reload confirmation

Manual Reload

You can trigger a manual reload by sending a SIGHUP signal to the proxy process:

# Find the proxy process ID
ps aux | grep fasthttp-reverse-proxy

# Send SIGHUP signal (replace PID with actual process ID)
kill -HUP <PID>

# Or if you know the process name
pkill -HUP fasthttp-reverse-proxy

Configuration Validation

Before applying new configuration, the proxy validates:

  • Server Configuration: Port ranges, host validity
  • Route Configuration: URL validity, target availability
  • TLS Configuration: Certificate and key file existence
  • YAML Syntax: Proper YAML formatting

If validation fails, the proxy keeps the current configuration and logs the error.

Safety Features

  • Atomic Updates: Configuration is updated atomically to prevent partial updates
  • Rollback Protection: Invalid configurations are rejected, keeping the current working config
  • Zero Downtime: Active connections continue to work during reload
  • Rate Limiter Reset: Rate limiters are cleared when rate limiting settings change

Reload Events Log

When configuration is reloaded, you'll see log messages like:

2025/05/29 10:30:00 Configuration file changed: config.yml
2025/05/29 10:30:00 Reloading configuration...
2025/05/29 10:30:01 Configuration reloaded successfully. Routes: 5 -> 7

Testing Dynamic Reload

Use the included test script to verify the reload functionality:

# Make the test script executable
chmod +x test-reload.sh

# Run the comprehensive test
./test-reload.sh

For a quick demonstration of the feature:

# Make the demo script executable  
chmod +x demo-reload.sh

# Run the interactive demo
./demo-reload.sh

Docker Considerations

When running in Docker, ensure configuration files are mounted as volumes to enable file watching:

version: '3.8'
services:
  reverse-proxy:
    build: .
    volumes:
      - ./config.yml:/root/config.yml:ro
      - ./routes.yml:/root/routes.yml:ro
    # For manual reload via docker
    # docker kill -s HUP <container_name>

Monitoring and Observability

Health Check Endpoint

The proxy provides a health check endpoint at /health (configurable):

curl http://localhost:8080/health

Response:

{
  "status": "healthy",
  "timestamp": "2025-05-29T10:30:00Z"
}

Access Logs

When enable_access_log is true, the proxy logs all requests:

2025/05/29 10:30:00 192.168.1.100 GET /api/v1/users 200 15.2ms

Security Features

Rate Limiting

Protects against DoS attacks by limiting requests per IP:

rate_limit:
  enabled: true
  requests_per_minute: 100
  burst: 10

CORS Support

Handles cross-origin requests with configurable policies:

cors:
  enabled: true
  allowed_origins: ["https://example.com"]
  allowed_methods: ["GET", "POST"]

Authentication

Supports multiple authentication methods:

  • Basic Auth: Username/password authentication
  • Bearer Token: Token-based authentication
  • None: No authentication required

Docker Compose Example

version: '3.8'

services:
  reverse-proxy:
    build: .
    ports:
      - "8080:8080"
    volumes:
      - ./config.yml:/root/config.yml
      - ./routes.yml:/root/routes.yml
    environment:
      - LOG_LEVEL=info
    restart: unless-stopped

  # Example backend service
  backend:
    image: nginx:alpine
    ports:
      - "3001:80"

Performance Tuning

System Limits

Increase system limits for high-traffic scenarios:

# Increase file descriptor limits
ulimit -n 65536

# Tune TCP settings
echo 'net.core.somaxconn = 65536' >> /etc/sysctl.conf
echo 'net.ipv4.tcp_max_syn_backlog = 65536' >> /etc/sysctl.conf

Configuration Tuning

server:
  max_conns_per_ip: 1000
  read_timeout: "10s"
  write_timeout: "10s"
  idle_timeout: "60s"

Troubleshooting

Common Issues

  1. Connection Refused

    • Check if upstream services are running
    • Verify target URLs in routes configuration
  2. High Memory Usage

    • Reduce max_conns_per_ip
    • Tune request timeouts
  3. SSL/TLS Issues

    • Verify certificate and key file paths
    • Check certificate validity

Debug Mode

Enable debug logging for troubleshooting:

logging:
  level: "debug"

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests if applicable
  5. Submit a pull request

License

This project is open source. Please check the license file for details.

Support

For issues and questions:

  • Create an issue in the repository
  • Check the troubleshooting section
  • Review the configuration examples

Performance Benchmarks

Based on fasthttp performance characteristics:

  • Throughput: 100K+ requests/second (depending on hardware)
  • Memory: Low memory footprint with connection pooling
  • Latency: Sub-millisecond overhead for proxying

Roadmap

  • Circuit breaker pattern
  • Metrics export (without Prometheus dependency)
  • Advanced load balancing algorithms
  • Request/response transformation
  • Plugin system

About

A high-performance reverse proxy built with Go and fasthttp. This proxy supports HTTP and WebSocket traffic with advanced features like load balancing, rate limiting, CORS, authentication, and more.

Topics

Resources

Stars

Watchers

Forks

Packages

No packages published