ratelimiter

package module
v0.0.0-...-769d8c3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 12, 2020 License: BSD-3-Clause Imports: 1 Imported by: 0

README

Go Rate limiter

GoDoc

What is it?

It is an implementation of token bucket algorithm (or analogic Leaky bucket algorithm). Useful for rate limiting.

Features

  • non blocking - Result if request should be refused or not is known as soon as possible. If you need wait when request is allowed another algorithm must be used.
  • memory leak safe - If you remove all references to the instance whole used memory will be immediately released.
  • non thread safe - For usage from multiple threads must be synchronized. For single thread offers better speed.
  • uses uint type so it is fast as the platform
  • allows setting up checking window in which uses for determinating average rate

Usage

Let's assume than we need allow transfer 1MB/s with allowed burst 5MB, and the window of check will be 1s.

import "github.com/polomsky/ratelimiter"

const MB = 1024 * 1024
limiter := ratelimiter.Limiter{
    Capacity:  5 * MB, // 5MB burst
    Decrement: 1 * MB, // 1MB per interval - 1MB/s
    Interval:  time.Second,
}

for i := 0; i < 6; i++ {
    // reports if request should be allowed or not
    fmt.Println(limiter.Add(MB))
}

Documentation

Overview

Package ratelimiter implements function for helping rate limiting.

Example
package main

import (
	"fmt"
	"github.com/polomsky/ratelimiter"
	"time"
)

func main() {
	const MB = 1024 * 1024
	limiter := ratelimiter.Limiter{
		Capacity:  5 * MB, // 5MB burst
		Decrement: 1 * MB, // 1MB per interval - 1MB/s
		Interval:  time.Second,
	}

	for i := 0; i < 6; i++ {
		fmt.Println(limiter.Add(MB))
	}
}
Output:

true
true
true
true
true
false

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Limiter

type Limiter struct {
	// size of the max burst, must be greater than zero, or only Add zero will be allowed
	Capacity uint
	// number of units allowed in each interval, must be greater than zero or it's average output will be zero
	Decrement uint

	// interval in which decrement is subtracted from the current usage, Decrement/Interval defines average output
	Interval time.Duration
	// contains filtered or unexported fields
}

Limiter represents rate limiter object. Supports Bursts up to max uint.

func (*Limiter) Add

func (tb *Limiter) Add(size uint) bool

Add returns true if request of the size should be passed, false when it is refused. Increments internal counter only if returns true.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL