redis_rate

repository·v10·Indexed 21 days ago

https://github.com/go-redis/redis_rate

A rate limiting library for go-redis that implements the Generic Cell Rate Algorithm (GCRA), also known as the leaky bucket algorithm, using Redis. It provides functionality to allow or deny requests via a Limiter, supporting custom rate limits and helper functions like PerSecond, PerMinute, and PerHour. Requires Redis version 3.2 or newer.

Tokens
1.4K
Snippets
8
Records
10
Agent score
27%

What's inside redis_rate

  1. How redis_rate works

    v10

    The redis_rate package implements the GCRA (Generic Cell Rate Algorithm), also known as the leaky bucket algorithm, for rate limiting using Redis.

    Requirements:

    • Redis Version: 3.2 or newer (required for the replicate_commands feature).
    • Go Version: Supports the two most recent Go versions and requires Go modules support.
  2. Install redis_rate/v10

    v10

    To use redis_rate, ensure your project is initialized with Go modules. You must include the /v10 suffix in your import path and installation command.

    1. Initialize your module:

      go mod init github.com/my/repo
    2. Install the v10 package:

      go get github.com/go-redis/redis_rate/v10
    go mod init github.com/my/repo
    go get github.com/go-redis/redis_rate/v10
  3. Use the Limiter to allow or deny requests

    v10

    To implement rate limiting, create a new limiter using redis_rate.NewLimiter(rdb) where rdb is a go-redis client. You can then call limiter.Allow(ctx, key, limit) to check if a request should be permitted.

    Commonly used limiters include redis_rate.PerSecond(n).

    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
    }
  4. Check if multiple events are allowed with AllowN

    v10

    Use AllowN to report whether n events may happen at the current time for a specific key.

    // Check if 5 events can happen at once
    result, err := limiter.AllowN(ctx, "api_key_abc", redis_rate.PerMinute(100), 5)
  5. Configure rate limits with Limit

    v10

    The Limit struct defines the rate limiting parameters. You can define limits manually or use helper functions for common time intervals:

    • Rate: The number of events allowed.
    • Burst: The maximum number of events allowed to happen instantaneously.
    • Period: The time window for the rate.

    Helper functions:

    • PerSecond(rate int) Limit: Sets rate and burst to rate over 1 second.
    • PerMinute(rate int) Limit: Sets rate and burst to rate over 1 minute.
    • PerHour(rate int) Limit: Sets rate and burst to rate over 1 hour.
    // Example: 10 requests per minute with a burst of 10
    limit := redis_rate.PerMinute(10)
    
    // Manual configuration
    limit := redis_rate.Limit{
        Rate:   5,
        Burst:  10,
        Period: time.Minute,
    }
  6. Check maximum allowed events with AllowAtMost

    v10

    Use AllowAtMost to determine how many events (up to a maximum of n) can be permitted at the current time. It returns the number of allowed events that is less than or equal to n.

    // Returns how many of the 10 requested events can actually be allowed
    result, err := limiter.AllowAtMost(ctx, "key", limit, 10)
  7. Check if an event is allowed with Allow

    v10

    Use Allow to check if a single event (n=1) is permitted for a specific key under a given limit. It returns a *Result containing the status of the request.

    result, err := limiter.Allow(ctx, "user_123", redis_rate.PerSecond(5))
    if err != nil {
        // handle error
    }
    if result.Allowed > 0 {
        // event is allowed
    }
  8. Understand the Result struct

    v10

    The Result struct provides detailed information about the outcome of a rate limiting check:

    • Limit: The Limit configuration used for the check.
    • Allowed: The number of events that may happen at the current time.
    • Remaining: The maximum number of requests that could be permitted instantaneously for this key given the current state.
    • RetryAfter: The duration until the next request will be permitted. It returns -1 if the rate limit has not been exceeded.
    • ResetAfter: The duration until the rate limiter returns to its initial state (i.e., when Remaining will equal Limit.Rate).