Skip to content

lzle/ratelimit

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

ratelimit

Go Reference Go License: MIT

Token-bucket rate limiting for Go io.Reader / io.Writer, with per-key isolation and thread-safe controllers.

Quick start

package main

import (
	"io"
	"log"
	"strings"

	"github.com/lzle/ratelimit"
)

func main() {
	limiter, err := ratelimit.NewRateLimiter(map[string]ratelimit.RateLimitConfig{
		"user-a": {BandwidthQuota: 1024}, // bytes per second
	})
	if err != nil {
		log.Fatal(err)
	}

	key := "user-a"
	r := limiter.GetReader(key, strings.NewReader("hello ratelimit"))
	w := limiter.GetWriter(key, io.Discard)

	if _, err := io.Copy(w, r); err != nil {
		log.Fatal(err)
	}

	if err := limiter.Close(key); err != nil {
		log.Fatal(err)
	}
}

Notes

  • Quota is bytes per second (BandwidthQuota).
  • Each GetReader / GetWriter acquires the key — balance with Close(key) or references accumulate.
  • Internals: token bucket, 50ms refill window, min burst 64 bytes per window.

Test

go test ./... -count=1

Acknowledgments

The flowctrl package is largely based on CubeFS util/flowctrl. See flowctrl/NOTICE for attribution and upstream licensing.

License

This repository is MIT licensed for the parts authored here (Copyright (c) 2026 lzle). Third-party code in flowctrl/ remains subject to the Apache License 2.0 of the CubeFS project; see flowctrl/NOTICE.

About

Bandwidth-style throttling for Go streaming I/O: per-key limits, token bucket, Close to release controllers.

Topics

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors

Languages