Go core
Browse topics

Rate limiting with channels

Version
1.27
Review
Draft

Summary#

A ticker can pace operations at a steady rate. A buffered channel can act as a small token bucket: each operation takes a token, refills add tokens, and the capacity sets the largest burst.

Syntax#

go
ticker := time.NewTicker(period)
defer ticker.Stop()

<-ticker.C // wait for the next slot

Refill a buffered token channel without blocking when it is full.

go
select {
case tokens <- struct{}{}:
default:
}

Example#

go
package main

import (
	"fmt"
	"time"
)

type bucket chan struct{}

func (b bucket) refill() {
	select {
	case b <- struct{}{}:
	default: // already full
	}
}

func (b bucket) allow() bool {
	select {
	case <-b:
		return true
	default:
		return false
	}
}

func main() {
	limit := make(bucket, 2)
	limit.refill()
	limit.refill()

	for request := 1; request <= 3; request++ {
		fmt.Println("burst request", request, limit.allow())
	}

	ticker := time.NewTicker(time.Millisecond)
	defer ticker.Stop()
	for request := 4; request <= 5; request++ {
		<-ticker.C
		limit.refill()
		fmt.Println("paced request", request, limit.allow())
	}

	for range 5 {
		limit.refill()
	}
	fmt.Println("stored tokens", len(limit))
}

Expected output#

The loop refills the bucket itself so that the result does not depend on timing. A server would refill from a goroutine that reads the ticker and stops with the application.

Text
burst request 1 true
burst request 2 true
burst request 3 false
paced request 4 true
paced request 5 true
stored tokens 2

Common mistakes#

All callers that share a limit must use the same limiter. Creating one per request gives each request its own quota. A slow refill loop can miss ticks. The Go wiki suggests golang.org/x/time/rate, outside the standard library, for higher rates. A channel limiter covers only one process.

Version applicability#

Tickers and buffered channels date back to Go 1.0. The complete example requires Go 1.22 for integer range.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0