ratelimiting

package
v2.0.2 Latest Latest
Warning

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

Go to latest
Published: Mar 23, 2026 License: AGPL-3.0 Imports: 8 Imported by: 0

Documentation

Overview

Package ratelimiting provides a per-key rate limiter interface using the token bucket algorithm.

Index

Examples

Constants

View Source
const (
	ProviderMemory = "memory"
	ProviderNoop   = "noop"
)

Variables

View Source
var (
	// Providers provides rate limiter construction for dependency injection.
	Providers = wire.NewSet(
		ProvideRateLimiterFromConfig,
	)
)

Functions

func RegisterRateLimiter

func RegisterRateLimiter(i do.Injector)

RegisterRateLimiter registers a RateLimiter with the injector.

Types

type Config

type Config struct {
	Provider       string  `env:"PROVIDER"         json:"provider"`
	RequestsPerSec float64 `env:"REQUESTS_PER_SEC" json:"requestsPerSecond"`
	BurstSize      int     `env:"BURST_SIZE"       json:"burstSize"`
}

Config configures rate limiting.

func (*Config) EnsureDefaults

func (cfg *Config) EnsureDefaults()

EnsureDefaults sets default values for zero fields.

func (*Config) ProvideRateLimiter

func (cfg *Config) ProvideRateLimiter() (RateLimiter, error)

ProvideRateLimiter returns a RateLimiter from config.

func (*Config) ValidateWithContext

func (cfg *Config) ValidateWithContext(ctx context.Context) error

ValidateWithContext validates the config.

type NoopRateLimiter

type NoopRateLimiter struct{}

NoopRateLimiter always allows requests.

func (*NoopRateLimiter) Allow

func (n *NoopRateLimiter) Allow(ctx context.Context, key string) (bool, error)

Allow always returns true.

func (*NoopRateLimiter) Close

func (n *NoopRateLimiter) Close() error

Close is a no-op.

type RateLimiter

type RateLimiter interface {
	Allow(ctx context.Context, key string) (bool, error)
	Close() error
}

RateLimiter limits the rate of operations per key.

func NewInMemoryRateLimiter

func NewInMemoryRateLimiter(requestsPerSec float64, burstSize int) RateLimiter

NewInMemoryRateLimiter returns a RateLimiter that uses per-key limiters in memory.

Example
package main

import (
	"context"
	"fmt"

	"github.com/verygoodsoftwarenotvirus/platform/v2/ratelimiting"
)

func main() {
	limiter := ratelimiting.NewInMemoryRateLimiter(10.0, 5)

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

	fmt.Println(allowed)
}
Output:

true

func NewNoopRateLimiter

func NewNoopRateLimiter() RateLimiter

NewNoopRateLimiter returns a RateLimiter that never limits.

func ProvideRateLimiterFromConfig

func ProvideRateLimiterFromConfig(cfg *Config) (RateLimiter, error)

ProvideRateLimiterFromConfig provides a RateLimiter from config.

Jump to

Keyboard shortcuts

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