FastHTTP

High-performance HTTP package for Go. Design achieving up to 10x performance of net/http. Pursues ultimate performance through zero memory allocation and advanced optimization. Specialized for high-volume request processing and latency-critical applications.

HTTP ClientGoHigh PerformanceZero AllocationConnection Pool

GitHub Overview

valyala/fasthttp

Fast HTTP package for Go. Tuned for high performance. Zero memory allocations in hot paths. Up to 10x faster than net/http

Stars22,742
Watchers391
Forks1,800
Created:October 18, 2015
Language:Go
License:MIT License

Topics

None

Star History

valyala/fasthttp Star History
Data as of: 7/18/2025, 01:39 AM

Library

fasthttp

Overview

fasthttp is "a high-performance HTTP client and server library for Go" developed as an HTTP communication library up to 10 times faster than the standard net/http. With the concept of "zero allocation design," it minimizes memory allocations to the extreme and achieves overwhelming performance in high-load environments through optimizations using object pooling and connection pooling. With proven track records of processing over 200K requests per second from 1.5M+ concurrent connections in enterprise-level large-scale web services, it has established itself as the ultimate performance solution for HTTP communication in Go language.

Details

fasthttp 2025 edition continues to provide performance that significantly exceeds the standard net/http as the definitive solution for high-load HTTP communication. Through thorough memory optimization with zero allocation design, GC load reduction through object pooling, and efficient connection management, it achieves dramatic improvements in both latency and throughput. With proven track records of processing hundreds of thousands of requests per second at major companies like VertaMedia, it demonstrates its power in microservices, API gateways, and high-load web servers. While migration requires attention due to its different API from net/http, it provides overwhelming advantages in performance-critical scenarios.

Key Features

  • Zero Allocation Design: Extreme optimization that minimizes memory allocations
  • Object Pool and Connection Pool: Efficient resource reuse system
  • Ultra-High-Speed Processing: Achieves up to 10x performance compared to net/http
  • Large-Scale Support: Processing capability for hundreds of thousands of RPS and millions of concurrent connections
  • Flexible API: Header and body configuration at any timing before response transmission
  • Comprehensive Features: Complete implementation of both HTTP client and server

Pros and Cons

Pros

  • Overwhelming performance significantly exceeding net/http (up to 10x faster)
  • Memory efficiency and GC load reduction through zero allocation design
  • Proven stability and processing capability in large-scale services
  • Efficient resource management through object and connection pooling
  • Advanced customization and performance tuning capabilities
  • Comprehensive features for both HTTP client and server

Cons

  • No API compatibility with net/http, requiring code changes during migration
  • More limited streaming processing compared to net/http
  • HTTP/2 support is under development and not yet complete
  • Smaller ecosystem and learning resources compared to net/http
  • Performance improvements may not be expected without proper optimization
  • Requires relatively new Go version 1.23 or later

Reference Pages

Code Examples

Installation and Basic Setup

# Install fasthttp
go get -u github.com/valyala/fasthttp

# Verify Go environment
go version  # Go 1.23 or later required

# Basic project initialization
go mod init fasthttp-example
go get github.com/valyala/fasthttp

Basic HTTP Server Implementation

package main

import (
	"fmt"
	"log"
	"time"
	"github.com/valyala/fasthttp"
)

// Basic request handler
func requestHandler(ctx *fasthttp.RequestCtx) {
	// Get request information
	fmt.Fprintf(ctx, "Hello, World! Request path: %q\n", ctx.Path())
	fmt.Fprintf(ctx, "Request method: %q\n", ctx.Method())
	fmt.Fprintf(ctx, "User agent: %q\n", ctx.UserAgent())
	
	// Set response headers
	ctx.SetContentType("text/plain; charset=utf-8")
	ctx.SetStatusCode(fasthttp.StatusOK)
}

// Advanced request handler
func advancedHandler(ctx *fasthttp.RequestCtx) {
	// Path-based routing
	switch string(ctx.Path()) {
	case "/":
		ctx.SetContentType("text/html")
		fmt.Fprintf(ctx, "<h1>Home Page</h1><p>fasthttp Server</p>")
	case "/api/status":
		ctx.SetContentType("application/json")
		fmt.Fprintf(ctx, `{"status": "ok", "server": "fasthttp"}`)
	case "/api/headers":
		ctx.SetContentType("application/json")
		fmt.Fprintf(ctx, `{"headers": {`)
		ctx.Request.Header.VisitAll(func(key, value []byte) {
			fmt.Fprintf(ctx, `"%s": "%s",`, string(key), string(value))
		})
		fmt.Fprintf(ctx, `}}`)
	default:
		ctx.Error("Not found", fasthttp.StatusNotFound)
	}
}

// Struct-based handler
type MyHandler struct {
	name string
}

func (h *MyHandler) HandleFastHTTP(ctx *fasthttp.RequestCtx) {
	fmt.Fprintf(ctx, "Handler name: %s\n", h.name)
	fmt.Fprintf(ctx, "Request URI: %q", ctx.RequestURI())
}

func main() {
	// Basic server startup
	log.Println("Starting fasthttp server on :8080...")
	log.Fatal(fasthttp.ListenAndServe(":8080", requestHandler))
	
	// Advanced server configuration
	server := &fasthttp.Server{
		Handler:            advancedHandler,
		ReadTimeout:        time.Second * 30,
		WriteTimeout:       time.Second * 30,
		IdleTimeout:        time.Second * 60,
		MaxConnsPerIP:      1000,
		MaxRequestsPerConn: 1000,
		MaxRequestBodySize: 1024 * 1024, // 1MB
	}
	
	log.Println("Starting custom server on :8081...")
	log.Fatal(server.ListenAndServe(":8081"))
	
	// Using struct handler
	myHandler := &MyHandler{name: "Custom Handler"}
	log.Fatal(fasthttp.ListenAndServe(":8082", myHandler.HandleFastHTTP))
}

HTTP Client Implementation (GET/POST/PUT/DELETE)

package main

import (
	"fmt"
	"log"
	"time"
	"github.com/valyala/fasthttp"
)

func main() {
	// Basic GET request
	statusCode, body, err := fasthttp.Get(nil, "https://httpbin.org/get")
	if err != nil {
		log.Fatalf("GET request error: %v", err)
	}
	fmt.Printf("Status: %d\nResponse: %s\n", statusCode, body)
	
	// GET request with query parameters
	req := fasthttp.AcquireRequest()
	resp := fasthttp.AcquireResponse()
	defer fasthttp.ReleaseRequest(req)
	defer fasthttp.ReleaseResponse(resp)
	
	req.SetRequestURI("https://httpbin.org/get?page=1&limit=10")
	req.Header.SetMethod(fasthttp.MethodGet)
	req.Header.Set("User-Agent", "fasthttp-client/1.0")
	
	client := &fasthttp.Client{
		ReadTimeout:  time.Second * 30,
		WriteTimeout: time.Second * 30,
	}
	
	err = client.Do(req, resp)
	if err != nil {
		log.Fatalf("Request error: %v", err)
	}
	
	fmt.Printf("Status: %d\n", resp.StatusCode())
	fmt.Printf("Response: %s\n", resp.Body())
	
	// POST request (sending JSON)
	req.Reset()
	resp.Reset()
	
	jsonData := `{"name": "John Doe", "email": "[email protected]", "age": 30}`
	
	req.SetRequestURI("https://httpbin.org/post")
	req.Header.SetMethod(fasthttp.MethodPost)
	req.Header.SetContentType("application/json")
	req.Header.Set("Authorization", "Bearer your-token")
	req.SetBody([]byte(jsonData))
	
	err = client.Do(req, resp)
	if err != nil {
		log.Fatalf("POST request error: %v", err)
	}
	
	fmt.Printf("POST Status: %d\n", resp.StatusCode())
	fmt.Printf("POST Response: %s\n", resp.Body())
	
	// PUT request (data update)
	req.Reset()
	resp.Reset()
	
	updateData := `{"name": "Jane Doe", "email": "[email protected]"}`
	
	req.SetRequestURI("https://httpbin.org/put")
	req.Header.SetMethod(fasthttp.MethodPut)
	req.Header.SetContentType("application/json")
	req.SetBody([]byte(updateData))
	
	err = client.Do(req, resp)
	if err != nil {
		log.Fatalf("PUT request error: %v", err)
	}
	
	fmt.Printf("PUT Status: %d\n", resp.StatusCode())
	
	// DELETE request
	req.Reset()
	resp.Reset()
	
	req.SetRequestURI("https://httpbin.org/delete")
	req.Header.SetMethod(fasthttp.MethodDelete)
	req.Header.Set("Authorization", "Bearer your-token")
	
	err = client.Do(req, resp)
	if err != nil {
		log.Fatalf("DELETE request error: %v", err)
	}
	
	fmt.Printf("DELETE Status: %d\n", resp.StatusCode())
	
	// Using HostClient for efficient requests
	hostClient := &fasthttp.HostClient{
		Addr:         "httpbin.org:443",
		IsTLS:        true,
		MaxConns:     100,
		ReadTimeout:  time.Second * 30,
		WriteTimeout: time.Second * 30,
	}
	
	req.Reset()
	resp.Reset()
	
	req.SetRequestURI("https://httpbin.org/get")
	req.Header.SetMethod(fasthttp.MethodGet)
	
	err = hostClient.Do(req, resp)
	if err != nil {
		log.Fatalf("HostClient request error: %v", err)
	}
	
	fmt.Printf("HostClient Status: %d\n", resp.StatusCode())
}

Advanced Configuration and Customization (Authentication, Timeout, Proxy, etc.)

package main

import (
	"crypto/tls"
	"fmt"
	"log"
	"time"
	"github.com/valyala/fasthttp"
)

func main() {
	// Custom client configuration
	client := &fasthttp.Client{
		// Timeout settings
		ReadTimeout:  time.Second * 30,
		WriteTimeout: time.Second * 30,
		MaxIdleConnDuration: time.Minute * 5,
		
		// Connection limits
		MaxConnsPerHost:     100,
		MaxIdleConnDuration: time.Minute,
		
		// TLS settings
		TLSConfig: &tls.Config{
			InsecureSkipVerify: false, // Don't set to true in production
		},
		
		// Retry settings
		MaxIdemponentCallAttempts: 3,
	}
	
	req := fasthttp.AcquireRequest()
	resp := fasthttp.AcquireResponse()
	defer fasthttp.ReleaseRequest(req)
	defer fasthttp.ReleaseResponse(resp)
	
	// Custom header configuration
	req.SetRequestURI("https://httpbin.org/headers")
	req.Header.SetMethod(fasthttp.MethodGet)
	req.Header.Set("User-Agent", "fasthttp-client/1.0")
	req.Header.Set("Accept", "application/json")
	req.Header.Set("Accept-Language", "en-US,ja-JP")
	req.Header.Set("X-API-Version", "v2")
	req.Header.Set("X-Request-ID", "req-12345")
	
	// Basic authentication
	req.Header.Set("Authorization", "Basic dXNlcjpwYXNz") // user:pass
	
	err := client.Do(req, resp)
	if err != nil {
		log.Fatalf("Authentication request error: %v", err)
	}
	
	fmt.Printf("Authentication response: %s\n", resp.Body())
	
	// Proxy client configuration
	proxyClient := &fasthttp.Client{
		Dial: fasthttp.DialDualStackTimeout(time.Second * 30),
		// Proxy is not directly supported in fasthttp,
		// requires custom Dialer implementation or third-party library
	}
	
	// Cookie configuration
	req.Reset()
	resp.Reset()
	
	req.SetRequestURI("https://httpbin.org/cookies")
	req.Header.SetMethod(fasthttp.MethodGet)
	req.Header.SetCookie("session_id", "abc123")
	req.Header.SetCookie("user_pref", "dark_mode")
	
	err = client.Do(req, resp)
	if err != nil {
		log.Fatalf("Cookie request error: %v", err)
	}
	
	fmt.Printf("Cookie response: %s\n", resp.Body())
	
	// Multipart form data transmission
	req.Reset()
	resp.Reset()
	
	req.SetRequestURI("https://httpbin.org/post")
	req.Header.SetMethod(fasthttp.MethodPost)
	req.Header.SetContentType("multipart/form-data; boundary=----formdata")
	
	multipartBody := `------formdata
Content-Disposition: form-data; name="username"

testuser
------formdata
Content-Disposition: form-data; name="password"

secret123
------formdata--`
	
	req.SetBody([]byte(multipartBody))
	
	err = client.Do(req, resp)
	if err != nil {
		log.Fatalf("Multipart request error: %v", err)
	}
	
	fmt.Printf("Multipart Status: %d\n", resp.StatusCode())
	
	// Streaming-capable large file handling
	req.Reset()
	resp.Reset()
	
	req.SetRequestURI("https://httpbin.org/stream/100")
	req.Header.SetMethod(fasthttp.MethodGet)
	
	err = client.Do(req, resp)
	if err != nil {
		log.Fatalf("Streaming request error: %v", err)
	}
	
	// Progressive response processing
	bodyBytes := resp.Body()
	fmt.Printf("Streaming data size: %d bytes\n", len(bodyBytes))
	
	// Custom HostClient (for specific host)
	hostClient := &fasthttp.HostClient{
		Addr:         "httpbin.org:443",
		IsTLS:        true,
		MaxConns:     50,
		ReadTimeout:  time.Second * 15,
		WriteTimeout: time.Second * 15,
		
		// Keep-Alive settings
		MaxIdleConnDuration: time.Minute * 5,
		
		// Custom TLS settings
		TLSConfig: &tls.Config{
			ServerName: "httpbin.org",
			MinVersion: tls.VersionTLS12,
		},
	}
	
	req.Reset()
	resp.Reset()
	
	req.SetRequestURI("https://httpbin.org/get")
	req.Header.SetMethod(fasthttp.MethodGet)
	
	err = hostClient.Do(req, resp)
	if err != nil {
		log.Fatalf("HostClient error: %v", err)
	}
	
	fmt.Printf("HostClient Status: %d\n", resp.StatusCode())
}

Error Handling and Retry Functionality

package main

import (
	"fmt"
	"log"
	"time"
	"github.com/valyala/fasthttp"
)

// Custom error type
type HTTPError struct {
	StatusCode int
	Message    string
	URL        string
}

func (e *HTTPError) Error() string {
	return fmt.Sprintf("HTTP %d: %s (URL: %s)", e.StatusCode, e.Message, e.URL)
}

// Safe request execution function
func safeRequest(client *fasthttp.Client, req *fasthttp.Request, resp *fasthttp.Response) error {
	err := client.Do(req, resp)
	if err != nil {
		return fmt.Errorf("request execution error: %w", err)
	}
	
	// Status code check
	statusCode := resp.StatusCode()
	if statusCode >= 400 {
		return &HTTPError{
			StatusCode: statusCode,
			Message:    string(resp.Body()),
			URL:        string(req.RequestURI()),
		}
	}
	
	return nil
}

// Request execution with retry
func requestWithRetry(client *fasthttp.Client, req *fasthttp.Request, maxRetries int, backoffFactor time.Duration) (*fasthttp.Response, error) {
	resp := fasthttp.AcquireResponse()
	
	for attempt := 0; attempt <= maxRetries; attempt++ {
		resp.Reset()
		
		err := safeRequest(client, req, resp)
		if err == nil {
			return resp, nil
		}
		
		// Check if error is retryable
		if httpErr, ok := err.(*HTTPError); ok {
			// Don't retry 4xx errors
			if httpErr.StatusCode >= 400 && httpErr.StatusCode < 500 {
				fasthttp.ReleaseResponse(resp)
				return nil, err
			}
		}
		
		if attempt == maxRetries {
			fasthttp.ReleaseResponse(resp)
			return nil, fmt.Errorf("maximum attempts reached: %w", err)
		}
		
		// Backoff wait
		waitTime := backoffFactor * time.Duration(1<<attempt)
		log.Printf("Attempt %d failed, retrying in %v: %v", attempt+1, waitTime, err)
		time.Sleep(waitTime)
	}
	
	fasthttp.ReleaseResponse(resp)
	return nil, fmt.Errorf("unexpected error")
}

// Rate-limited client
type RateLimitedClient struct {
	client     *fasthttp.Client
	limiter    chan struct{}
	retryDelay time.Duration
}

func NewRateLimitedClient(requestsPerSecond int, retryDelay time.Duration) *RateLimitedClient {
	return &RateLimitedClient{
		client: &fasthttp.Client{
			ReadTimeout:  time.Second * 30,
			WriteTimeout: time.Second * 30,
		},
		limiter:    make(chan struct{}, requestsPerSecond),
		retryDelay: retryDelay,
	}
}

func (rlc *RateLimitedClient) Do(req *fasthttp.Request, resp *fasthttp.Response) error {
	// Rate limiting
	select {
	case rlc.limiter <- struct{}{}:
		defer func() { <-rlc.limiter }()
	default:
		time.Sleep(rlc.retryDelay)
		return rlc.Do(req, resp)
	}
	
	return rlc.client.Do(req, resp)
}

func main() {
	client := &fasthttp.Client{
		ReadTimeout:               time.Second * 30,
		WriteTimeout:              time.Second * 30,
		MaxIdemponentCallAttempts: 1, // Disable fasthttp's automatic retry
	}
	
	req := fasthttp.AcquireRequest()
	defer fasthttp.ReleaseRequest(req)
	
	// Normal request test
	req.SetRequestURI("https://httpbin.org/get")
	req.Header.SetMethod(fasthttp.MethodGet)
	
	resp, err := requestWithRetry(client, req, 3, time.Second)
	if err != nil {
		log.Printf("Request failed: %v", err)
	} else {
		fmt.Printf("Success: Status %d\n", resp.StatusCode())
		fasthttp.ReleaseResponse(resp)
	}
	
	// Error response test
	req.Reset()
	req.SetRequestURI("https://httpbin.org/status/404")
	req.Header.SetMethod(fasthttp.MethodGet)
	
	resp, err = requestWithRetry(client, req, 3, time.Second)
	if err != nil {
		if httpErr, ok := err.(*HTTPError); ok {
			fmt.Printf("HTTP Error: %d - %s\n", httpErr.StatusCode, httpErr.Message)
		} else {
			log.Printf("Other error: %v", err)
		}
	}
	if resp != nil {
		fasthttp.ReleaseResponse(resp)
	}
	
	// Timeout test
	timeoutClient := &fasthttp.Client{
		ReadTimeout:  time.Millisecond * 100, // Short timeout
		WriteTimeout: time.Millisecond * 100,
	}
	
	req.Reset()
	req.SetRequestURI("https://httpbin.org/delay/1")
	req.Header.SetMethod(fasthttp.MethodGet)
	
	resp, err = requestWithRetry(timeoutClient, req, 2, time.Millisecond*500)
	if err != nil {
		log.Printf("Timeout error (expected): %v", err)
	}
	if resp != nil {
		fasthttp.ReleaseResponse(resp)
	}
	
	// Rate-limited client test
	rateLimitedClient := NewRateLimitedClient(5, time.Millisecond*200)
	
	for i := 0; i < 10; i++ {
		req.Reset()
		resp := fasthttp.AcquireResponse()
		
		req.SetRequestURI(fmt.Sprintf("https://httpbin.org/get?request=%d", i))
		req.Header.SetMethod(fasthttp.MethodGet)
		
		start := time.Now()
		err := rateLimitedClient.Do(req, resp)
		duration := time.Since(start)
		
		if err != nil {
			log.Printf("Request %d error: %v", i, err)
		} else {
			fmt.Printf("Request %d completed: Status %d, Duration: %v\n", 
				i, resp.StatusCode(), duration)
		}
		
		fasthttp.ReleaseResponse(resp)
	}
	
	// Concurrent error handling example
	const numRequests = 5
	results := make(chan string, numRequests)
	
	for i := 0; i < numRequests; i++ {
		go func(id int) {
			req := fasthttp.AcquireRequest()
			defer fasthttp.ReleaseRequest(req)
			
			// 50% chance of generating 404 error
			url := "https://httpbin.org/get"
			if id%2 == 0 {
				url = "https://httpbin.org/status/404"
			}
			
			req.SetRequestURI(url)
			req.Header.SetMethod(fasthttp.MethodGet)
			
			resp, err := requestWithRetry(client, req, 2, time.Millisecond*500)
			if err != nil {
				results <- fmt.Sprintf("Goroutine %d: Error - %v", id, err)
			} else {
				results <- fmt.Sprintf("Goroutine %d: Success - Status %d", id, resp.StatusCode())
				fasthttp.ReleaseResponse(resp)
			}
		}(i)
	}
	
	// Collect results
	for i := 0; i < numRequests; i++ {
		result := <-results
		fmt.Println(result)
	}
}

Performance Optimization and Benchmarking

package main

import (
	"fmt"
	"log"
	"runtime"
	"sync"
	"time"
	"github.com/valyala/fasthttp"
)

// Performance monitoring structure
type PerformanceMonitor struct {
	requestCount    int64
	errorCount      int64
	totalDuration   time.Duration
	mu              sync.RWMutex
	startTime       time.Time
}

func NewPerformanceMonitor() *PerformanceMonitor {
	return &PerformanceMonitor{
		startTime: time.Now(),
	}
}

func (pm *PerformanceMonitor) RecordRequest(duration time.Duration, hasError bool) {
	pm.mu.Lock()
	defer pm.mu.Unlock()
	
	pm.requestCount++
	pm.totalDuration += duration
	if hasError {
		pm.errorCount++
	}
}

func (pm *PerformanceMonitor) GetStats() (int64, int64, time.Duration, float64) {
	pm.mu.RLock()
	defer pm.mu.RUnlock()
	
	elapsed := time.Since(pm.startTime)
	rps := float64(pm.requestCount) / elapsed.Seconds()
	
	return pm.requestCount, pm.errorCount, pm.totalDuration, rps
}

// Optimized client configuration
func createOptimizedClient() *fasthttp.Client {
	return &fasthttp.Client{
		// Efficient timeout settings
		ReadTimeout:  time.Second * 10,
		WriteTimeout: time.Second * 10,
		
		// Connection optimization
		MaxConnsPerHost:       100,
		MaxIdleConnDuration:   time.Minute * 5,
		MaxConnDuration:       time.Hour,
		MaxIdemponentCallAttempts: 3,
		
		// TCP performance optimization
		ReadBufferSize:  64 * 1024,  // 64KB
		WriteBufferSize: 64 * 1024,  // 64KB
		
		// Keep-Alive settings
		MaxConnWaitTimeout: time.Second * 5,
	}
}

// Batch request processing
func batchRequests(client *fasthttp.Client, urls []string, concurrency int) {
	monitor := NewPerformanceMonitor()
	semaphore := make(chan struct{}, concurrency)
	var wg sync.WaitGroup
	
	fmt.Printf("Starting batch processing: %d URLs, concurrency: %d\n", len(urls), concurrency)
	
	for i, url := range urls {
		wg.Add(1)
		go func(id int, targetURL string) {
			defer wg.Done()
			
			// Control concurrency with semaphore
			semaphore <- struct{}{}
			defer func() { <-semaphore }()
			
			req := fasthttp.AcquireRequest()
			resp := fasthttp.AcquireResponse()
			defer fasthttp.ReleaseRequest(req)
			defer fasthttp.ReleaseResponse(resp)
			
			req.SetRequestURI(targetURL)
			req.Header.SetMethod(fasthttp.MethodGet)
			
			start := time.Now()
			err := client.Do(req, resp)
			duration := time.Since(start)
			
			hasError := err != nil || resp.StatusCode() >= 400
			monitor.RecordRequest(duration, hasError)
			
			if id%100 == 0 {
				fmt.Printf("Progress: %d/%d completed\n", id, len(urls))
			}
		}(i, url)
	}
	
	wg.Wait()
	
	// Display statistics
	requests, errors, totalDuration, rps := monitor.GetStats()
	avgDuration := totalDuration / time.Duration(requests)
	
	fmt.Printf("\n=== Batch Processing Results ===\n")
	fmt.Printf("Total requests: %d\n", requests)
	fmt.Printf("Errors: %d (%.2f%%)\n", errors, float64(errors)/float64(requests)*100)
	fmt.Printf("Average response time: %v\n", avgDuration)
	fmt.Printf("RPS (Requests Per Second): %.2f\n", rps)
}

// Connection pool monitoring
func monitorConnectionPool(client *fasthttp.Client) {
	ticker := time.NewTicker(time.Second * 5)
	defer ticker.Stop()
	
	for {
		select {
		case <-ticker.C:
			// Display simple memory usage here
			var m runtime.MemStats
			runtime.ReadMemStats(&m)
			
			fmt.Printf("Memory usage: Alloc = %.2f MB, Sys = %.2f MB, NumGC = %d\n",
				float64(m.Alloc)/1024/1024,
				float64(m.Sys)/1024/1024,
				m.NumGC)
		}
	}
}

// Load test function
func loadTest(targetURL string, duration time.Duration, concurrency int) {
	client := createOptimizedClient()
	monitor := NewPerformanceMonitor()
	
	fmt.Printf("Starting load test: %s, duration: %v, concurrency: %d\n", targetURL, duration, concurrency)
	
	// Start memory monitoring in separate goroutine
	go monitorConnectionPool(client)
	
	semaphore := make(chan struct{}, concurrency)
	endTime := time.Now().Add(duration)
	var wg sync.WaitGroup
	
	for time.Now().Before(endTime) {
		wg.Add(1)
		go func() {
			defer wg.Done()
			
			semaphore <- struct{}{}
			defer func() { <-semaphore }()
			
			req := fasthttp.AcquireRequest()
			resp := fasthttp.AcquireResponse()
			defer fasthttp.ReleaseRequest(req)
			defer fasthttp.ReleaseResponse(resp)
			
			req.SetRequestURI(targetURL)
			req.Header.SetMethod(fasthttp.MethodGet)
			
			start := time.Now()
			err := client.Do(req, resp)
			requestDuration := time.Since(start)
			
			hasError := err != nil || resp.StatusCode() >= 400
			monitor.RecordRequest(requestDuration, hasError)
		}()
	}
	
	wg.Wait()
	
	// Final statistics
	requests, errors, totalDuration, rps := monitor.GetStats()
	avgDuration := totalDuration / time.Duration(requests)
	
	fmt.Printf("\n=== Load Test Results ===\n")
	fmt.Printf("Total requests: %d\n", requests)
	fmt.Printf("Errors: %d (%.2f%%)\n", errors, float64(errors)/float64(requests)*100)
	fmt.Printf("Average response time: %v\n", avgDuration)
	fmt.Printf("Max RPS: %.2f\n", rps)
	fmt.Printf("Throughput: %.2f MB/s (estimated)\n", rps*1024/1024) // Assuming 1KB/request
}

func main() {
	// Basic performance test
	urls := make([]string, 1000)
	for i := range urls {
		urls[i] = fmt.Sprintf("https://httpbin.org/get?id=%d", i)
	}
	
	client := createOptimizedClient()
	
	// Batch request test
	batchRequests(client, urls[:100], 20)
	
	// Load test (use appropriate test server in production)
	// loadTest("https://httpbin.org/get", time.Minute, 50)
	
	// Benchmark comparison (fasthttp vs net/http)
	fmt.Println("\n=== fasthttp Benchmark Example ===")
	fmt.Println("Actual benchmark results:")
	fmt.Println("fasthttp: 865 ns/op, 0 allocs/op")
	fmt.Println("net/http: 12567 ns/op, 35 allocs/op")
	fmt.Println("Performance improvement: ~14.5x faster, zero allocations")
	
	// Memory efficiency demo
	demonstrateMemoryEfficiency()
}

func demonstrateMemoryEfficiency() {
	fmt.Println("\n=== Memory Efficiency Demo ===")
	
	// Utilizing object pools
	req := fasthttp.AcquireRequest()
	resp := fasthttp.AcquireResponse()
	
	// Always return to pool after use
	defer fasthttp.ReleaseRequest(req)
	defer fasthttp.ReleaseResponse(resp)
	
	// Zero allocation string manipulation example
	uri := make([]byte, 0, 100)
	uri = append(uri, "https://example.com/api"...)
	uri = append(uri, "?param=value"...)
	
	req.SetRequestURIBytes(uri)
	
	fmt.Println("Implemented object pool and zero allocation operations")
	fmt.Printf("URI set completed: %s\n", req.RequestURI())
}