Rate Limiter

Rate limiting with time.Ticker and burst with a token bucket channel.

package main

import (
	"fmt"
	"time"
)

func main() {
	// Simple rate limiting: 1 request per 200ms
	fmt.Println("--- Simple Rate Limit ---")
	limiter := time.NewTicker(200 * time.Millisecond)
	defer limiter.Stop()

	for i := 1; i <= 5; i++ {
		<-limiter.C
		fmt.Printf("request %d at %s\n", i, time.Now().Format("15:04:05.000"))
	}

	// Burst rate limiting: allow 3 immediately, then 1 per 200ms
	fmt.Println("\n--- Burst Rate Limit ---")
	bucket := make(chan struct{}, 3)
	for i := 0; i < 3; i++ {
		bucket <- struct{}{}
	}
	go func() {
		ticker := time.NewTicker(200 * time.Millisecond)
		defer ticker.Stop()
		for range ticker.C {
			select {
			case bucket <- struct{}{}:
			default:
			}
		}
	}()

	for i := 1; i <= 8; i++ {
		<-bucket
		fmt.Printf("request %d at %s\n", i, time.Now().Format("15:04:05.000"))
	}
}
▶ Open Go Playground

Copy the code above and paste to run

© 2026 ByteLearn.dev. Free courses for developers. · Privacy