redisrate

package
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Apr 25, 2025 License: MIT, BSD-2-Clause Imports: 6 Imported by: 0

README

Rate limiting for go-redis

github.com/redis/go-redis with some changes

  • floating numbers support
  • correct operation with redis cluster

Build Status PkgGoDev

Uptrace.dev - distributed traces, logs, and errors in one place

This package is based on rwz/redis-gcra and implements GCRA (aka leaky bucket) for rate limiting based on Redis. The code requires Redis version 3.2 or newer since it relies on replicate_commands feature.

Installation

redis_rate supports 2 last Go versions and requires a Go version with modules support. So make sure to initialize a Go module:

go mod init github.com/my/repo

And then install redisrate/v10 (note **_v10** in the import; omitting it is a popular mistake):

go get github.com/go-redis/redis_rate/v10

Example

package redis_rate_test

import (
 "context"
 "fmt"

 "github.com/redis/go-redis/v9"
 "github.com/go-redis/redis_rate/v10"
)

func ExampleNewLimiter() {
 ctx := context.Background()
 rdb := redis.NewClient(&redis.Options{
  Addr: "localhost:6379",
 })
 _ = rdb.FlushDB(ctx).Err()

 limiter := redis_rate.NewLimiter(rdb)
 res, err := limiter.Allow(ctx, "project:123", redis_rate.PerSecond(10))
 if err != nil {
  panic(err)
 }
 fmt.Println("allowed", res.Allowed, "remaining", res.Remaining)
 // Output: allowed 1 remaining 9
}

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Limit

type Limit struct {
	Rate   float64       // The rate of events per Period.
	Burst  float64       // The maximum burst size.
	Period time.Duration // The period for the rate.
}

Limit defines the maximum frequency of some events.

func PerHour

func PerHour(rate float64) Limit

PerHour returns a Limit that allows rate events per hour.

func PerMinute

func PerMinute(rate float64) Limit

PerMinute returns a Limit that allows rate events per minute.

func PerSecond

func PerSecond(rate float64) Limit

PerSecond returns a Limit that allows rate events per second.

func (Limit) IsZero

func (l Limit) IsZero() bool

IsZero reports whether the limit is the zero value.

func (Limit) String

func (l Limit) String() string

String returns a string representation of the Limit.

type Limiter

type Limiter struct {
	// contains filtered or unexported fields
}

Limiter controls how frequently events are allowed to happen.

func NewLimiter

func NewLimiter(rdb rediser, prefix string) (*Limiter, error)

NewLimiter returns a new Limiter.

Example
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
	Addr: "localhost:6379",
})
_ = rdb.FlushDB(ctx).Err()

limiter, err := NewLimiter(rdb, "rate")
if err != nil {
	panic(err)
}
res, err := limiter.Allow(ctx, "project:123", PerSecond(10.0))
if err != nil {
	panic(err)
}
// Use %.0f to ensure we get whole numbers without decimal places
fmt.Printf("allowed %.0f remaining %.0f\n", res.Allowed, res.Remaining)
Output:

allowed 1 remaining 9

func (Limiter) Allow

func (l Limiter) Allow(ctx context.Context, key string, limit Limit) (*Result, error)

Allow is a shortcut for AllowN(ctx, key, limit, 1).

func (Limiter) AllowAtMost

func (l Limiter) AllowAtMost(
	ctx context.Context,
	key string,
	limit Limit,
	n int,
) (*Result, error)

AllowAtMost reports whether at most n events may happen at time now. It returns number of allowed events that is less than or equal to n.

func (Limiter) AllowN

func (l Limiter) AllowN(
	ctx context.Context,
	key string,
	limit Limit,
	n float64,
) (*Result, error)

AllowN reports whether n events may happen at time now.

func (*Limiter) Reset

func (l *Limiter) Reset(ctx context.Context, key string) error

Reset gets a key and reset all limitations and previous usages

type Result

type Result struct {
	// Limit is the limit that was used to obtain this result.
	Limit Limit

	// Allowed is the number of events that may happen at time now.
	Allowed float64

	// Remaining is the maximum number of requests that could be
	// permitted instantaneously for this key given the current
	// state. For example, if a rate limiter allows 10 requests per
	// second and has already received 6 requests for this key this
	// second, Remaining would be 4.
	Remaining float64

	// RetryAfter is the time until the next request will be permitted.
	// It should be -1 unless the rate limit has been exceeded.
	RetryAfter time.Duration

	// ResetAfter is the time until the RateLimiter returns to its
	// initial state for a given key. For example, if a rate limiter
	// manages requests per second and received one request 200ms ago,
	// Reset would return 800ms. You can also think of this as the time
	// until Limit and Remaining will be equal.
	ResetAfter time.Duration
}

Result contains information about whether a RateLimiter allowed an event to happen.

Jump to

Keyboard shortcuts

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