ratelimit

package module
v1.0.8 Latest Latest
Warning

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

Go to latest
Published: Feb 19, 2026 License: MIT Imports: 3 Imported by: 0

README ¶

Distributed Rate Limiter for Go

Go Reference Go Report Card

A high-performance, distributed rate-limiting library for Go, powered by Redis and Lua scripting. This library implements the Sliding Window Counter algorithm to ensure precision and atomicity across multiple service instances.

🚀 Features

  • Distributed Architecture: Synchronize rate limits across multiple nodes using Redis.
  • Sliding Window Algorithm: Prevents traffic bursts at window boundaries, offering better precision than Fixed Window.
  • Atomic Operations: Uses Redis Lua scripting to guarantee thread-safe operations without race conditions.
  • Framework Agnostic: Core logic is decoupled from web frameworks.
  • Production Ready: Built-in support for context.Context for timeout and cancellation handling.

🧠 Algorithm

This library uses the Sliding Window Counter algorithm implemented with Redis sorted sets and Lua scripting to ensure atomicity across distributed instances.

🛠 Installation

go get github.com/vnmchuo/ratelimiter@v1.0.8

💡 Note: Make sure the version tag v1.0.8 exists in the repository. Otherwise, use @latest.

💡 Quick Start

package main

import (
    "context"
    "time"

    "github.com/redis/go-redis/v9"
    "github.com/vnmchuo/ratelimiter"
)

func main() {
    rdb := redis.NewClient(&redis.Options{
        Addr: "localhost:6379",
    })

    // Create a new limiter: 100 requests per minute
    limiter := ratelimiter.NewRedisStore(
        rdb,
        ratelimiter.WithLimit(100),
        ratelimiter.WithWindow(time.Minute),
    )

    res, err := limiter.Allow(context.Background(), "user-123")
    if err != nil {
        panic(err)
    }

    if res.Allowed {
        // Proceed with request
    } else {
        // Handle rate limit exceeded (e.g., HTTP 429)
    }
}

🔌 Framework Integration

This library is designed to be easily wrapped into any middleware.

Gin Example
import (
    ginmw "github.com/vnmchuo/ratelimiter/middleware/gin"
)

// ...
r := gin.Default()
r.Use(ginmw.RateLimiter(limiter, func(c *gin.Context) string {
    return c.ClientIP()
}))

📊 Benchmarks

Run the benchmarks on your machine to verify performance:

go test -bench=. -benchmem ./...

Benchmark results will vary depending on hardware, Redis configuration, and network latency.

📄 License

Distributed under the MIT License. See LICENSE for more information.

Documentation ¶

Overview ¶

Package ratelimiter provides a distributed rate limiter for Go using Redis and the Sliding Window Counter algorithm.

This package is designed for high-performance, concurrent systems and ensures atomic rate-limiting operations across multiple instances by leveraging Redis Lua scripting.

Typical use cases include:

  • API rate limiting
  • Distributed systems throttling
  • Per-user or per-IP request control

See the README for integration examples and framework-specific middleware.

Index ¶

Constants ¶

This section is empty.

Variables ¶

This section is empty.

Functions ¶

This section is empty.

Types ¶

type Config ¶

type Config struct {
	Limit  int           // Maximum number of allowed requests.
	Window time.Duration // The duration of the sliding window.
}

Config holds the parameters for the rate limiting window.

type Limiter ¶

type Limiter interface {
	// Allow checks if a request for the given key is permitted within the configured time window.
	// Returns a Result containing the current status or an error if the store is unreachable.
	Allow(ctx context.Context, key string) (*Result, error)
}

Limiter defines the contract for rate limiting implementations. It allows for different backend stores (Redis, In-Memory, etc.) to be used interchangeably.

type Option ¶

type Option func(*Config)

Option is a functional configuration for the RedisStore.

func WithLimit ¶

func WithLimit(limit int) Option

WithLimit sets the maximum number of requests allowed within the window.

func WithWindow ¶

func WithWindow(window time.Duration) Option

WithWindow sets the duration for the rate limiting sliding window.

type RedisStore ¶

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

RedisStore implements the Limiter interface using Redis as the backend. It utilizes Lua scripting to ensure atomic increments and window management.

func NewRedisStore ¶

func NewRedisStore(client *redis.Client, opts ...Option) *RedisStore

NewRedisStore initializes a new RedisStore with the provided Redis client and options. If no options are provided, it defaults to a limit of 100 requests per minute.

func (*RedisStore) Allow ¶

func (s *RedisStore) Allow(ctx context.Context, key string) (*Result, error)

Allow executes the sliding window rate limiting logic using a Redis Lua script. This operation is atomic and thread-safe for distributed environments.

type Result ¶

type Result struct {
	Allowed    bool          // True if the request is permitted.
	Remaining  int           // Number of requests remaining in the current window.
	Limit      int           // The total configured limit for the window.
	ResetAfter time.Duration // Time remaining until the rate limit window resets.
}

Result represents the outcome of a rate limit check.

Directories ¶

Path Synopsis
examples
gin command
middleware
gin

Jump to

Keyboard shortcuts

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