ratelimit

package
v1.6.0 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2026 License: MIT Imports: 8 Imported by: 0

Documentation

Overview

Package ratelimit is a Redis-backed token-bucket rate limiter with per-key buckets, cost-per-request, and a Fiber middleware.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Limiter

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

Limiter is a token-bucket rate limiter backed by Redis.

func New

func New(client redis.UniversalClient, opts ...Option) *Limiter

New returns a Limiter using the given Redis client.

func (*Limiter) Allow

func (l *Limiter) Allow(ctx context.Context, key string, rule Rule, cost int) (Result, error)

Allow attempts to consume cost tokens for key under rule.

Example

A token bucket of 2 with a slow refill: the first two requests pass, the third is denied.

package main

import (
	"context"
	"fmt"

	"github.com/alicebob/miniredis/v2"
	goredis "github.com/redis/go-redis/v9"

	"github.com/rahmadafandi/fibr/ratelimit"
)

func main() {
	mr, _ := miniredis.Run()
	defer mr.Close()
	client := goredis.NewClient(&goredis.Options{Addr: mr.Addr()})
	defer func() { _ = client.Close() }()

	l := ratelimit.New(client)
	rule := ratelimit.Rule{Capacity: 2, RefillPerSec: 1}
	ctx := context.Background()

	for range 3 {
		res, _ := l.Allow(ctx, "user:1", rule, 1)
		fmt.Println(res.Allowed)
	}
}
Output:
true
true
false

func (*Limiter) Middleware

func (l *Limiter) Middleware(rule Rule, keyFunc func(*fiber.Ctx) string) fiber.Handler

Middleware limits requests per key under rule (cost 1 each). keyFunc derives the bucket key; when nil it uses the client IP. On a deny it responds 429 with Retry-After and X-RateLimit-* headers. A Redis error fails open (the request is allowed) so the limiter cannot take the app down.

type Option added in v1.6.0

type Option func(*Limiter)

Option configures a Limiter.

func WithLogger added in v1.6.0

func WithLogger(l *logger.Logger) Option

WithLogger sets the logger Middleware reports Redis failures to. The default is logger.Default().

type Result

type Result struct {
	Allowed    bool
	Remaining  int
	RetryAfter time.Duration // > 0 only when not allowed
}

Result is the outcome of an Allow call.

type Rule

type Rule struct {
	Capacity     int
	RefillPerSec float64
}

Rule defines a bucket: Capacity tokens, refilled at RefillPerSec tokens/sec.

Jump to

Keyboard shortcuts

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