ratelimiter

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Aug 10, 2026 License: Apache-2.0 Imports: 12 Imported by: 0

Documentation

Overview

Package ratelimiter provides per-tenant rate limiting middleware using a token bucket algorithm. Rate limits are stored in PostgreSQL and cached in memory for fast middleware checks. The background goroutine reloads configs from the database every 30 seconds.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func New

func New() plugin.Plugin

New creates a new Plugin instance.

Types

type Config

type Config struct {
	// Mode selects the rate-limiting backend: "memory" (default) for
	// per-worker token buckets, or "db" for a DB-backed sliding-window
	// counter that enforces limits across all workers.
	Mode string `json:"mode"`
}

Config holds optional configuration for the rate-limiter plugin.

type Plugin

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

Plugin implements per-tenant rate limiting with a token bucket algorithm. It stores rate limit configurations in PostgreSQL and maintains an in-memory cache of token buckets for fast middleware checks.

func (*Plugin) Info

func (p *Plugin) Info() plugin.PluginInfo

Info returns plugin metadata for discovery and documentation.

func (*Plugin) Init

func (p *Plugin) Init(ctx context.Context, env *plugin.Environment) error

Init initializes the plugin with the given environment. It sets up the in-memory token bucket cache and stores references to the database and logger provided by the engine.

func (*Plugin) Middleware

func (p *Plugin) Middleware(next http.Handler) http.Handler

Middleware wraps the next handler with per-tenant rate limiting. It checks all rate limits configured for the tenant. If any limit is exceeded, it returns 429 Too Many Requests with standard rate limit headers.

func (*Plugin) Migrations

func (p *Plugin) Migrations() []plugin.Migration

Migrations returns the database schema for rate limit storage. The table is idempotent (IF NOT EXISTS) and safe to run multiple times.

func (*Plugin) RegisterRoutes

func (p *Plugin) RegisterRoutes(mux *http.ServeMux) error

RegisterRoutes registers the rate limit management HTTP routes on the given mux. All routes require a tenant context set by the auth middleware.

GET    /rate-limits        — list rate limits for the tenant
PUT    /rate-limits/{key}  — create or update a rate limit
DELETE /rate-limits/{key}  — remove a rate limit

func (*Plugin) Run

func (p *Plugin) Run(ctx context.Context) error

Run starts the background rate limit config reload loop. It queries all rate limit configurations from the database every 30 seconds and rebuilds the in-memory token bucket cache. Returns when ctx is cancelled.

Jump to

Keyboard shortcuts

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