limiter

package module
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Aug 23, 2026 License: MIT Imports: 2 Imported by: 2

README

limiter

A unified rate-limiting and concurrency-control interface with multiple pluggable backends. Follows the "one interface, many backends" pattern.

Interfaces

// Core concurrency control
type Limiter interface {
    Running() int
    Acquire(ctx context.Context, key []byte) error
    Release(key []byte)
}

// String-keyed convenience variant
type StringLimiter interface {
    Running() int
    Acquire(ctx context.Context, key string) error
    Release(key string)
}

// Byte-size-aware (bandwidth / storage quotas)
type SizeLimiter interface {
    Running() int64
    Acquire(ctx context.Context, key []byte, size int64) error
    Release(key []byte, size int64)
    Remaining(key []byte) int64
}

Implementations

Package Type Description
count/ Concurrency Global concurrency cap (atomic or blocking)
keycount/ Concurrency Per-key concurrency cap (mutex, sync-atomic, or blocking)
keysize/ Size Per-key cumulative byte-size cap
tokenbucket/ Rate Token-bucket rate limiter (QPS / burst)
null/ — No-op implementation (disable limiting)
redis/ Distributed Redis-backed sliding window, token bucket, concurrency
memcached/ Distributed Memcached-backed sliding window, concurrency
mongodb/ Distributed MongoDB-backed rate limit, concurrency
etcd/ Distributed etcd-backed rate limit, concurrency

Usage

import (
    "github.com/LingByte/ling-base/limiter"
    "github.com/LingByte/ling-base/limiter/count"
    "github.com/LingByte/ling-base/limiter/keycount"
    "github.com/LingByte/ling-base/limiter/tokenbucket"
)

// Global max 100 concurrent
l := count.New(100)
if err := l.Acquire(nil); err != nil {
    // limit exceeded
}
defer l.Release(nil)

// Per-user max 5 concurrent
l := keycount.New(5)
l.Acquire(nil, []byte("user123"))
defer l.Release([]byte("user123"))

// 100 QPS, burst 200
l := tokenbucket.New(100, 200)
if err := l.Acquire(nil); err != nil {
    // rate limited
}

// String-keyed helper
if err := limiter.AcquireString(l, ctx, "user123"); err != nil {
    // limit exceeded
}
defer limiter.ReleaseString(l, "user123")

Errors

Error Meaning
ErrLimitExceeded Acquire cannot grant a permit (non-blocking mode)
ErrKeyRequired Implementation requires a non-empty key
ErrInvalidLimit Configured limit is <= 0
ErrInvalidSize Requested size is <= 0

Testing

All implementations have unit tests. Distributed backends use in-memory mocks or miniredis — no external servers required.

License

MIT

Documentation

Overview

Package limiter defines a unified rate-limiting and concurrency-control interface with multiple pluggable implementations.

The package follows the same "one interface, many backends" pattern used by github.com/LingByte/ling-base/lock. Each sub-package provides a concrete strategy:

  • count/ — global concurrency cap (atomic or blocking)
  • keycount/ — per-key concurrency cap (mutex, sync-atomic, or blocking)
  • keysize/ — per-key cumulative byte-size cap
  • tokenbucket/ — token-bucket rate limiter (QPS / burst)
  • null/ — no-op implementation (disable limiting)

Basic usage:

// Global max 100 concurrent
l := count.New(100)
if err := l.Acquire(nil); err != nil {
    // limit exceeded
}
defer l.Release(nil)

// Per-user max 5 concurrent
l := keycount.New(5)
l.Acquire([]byte("user123"))
defer l.Release([]byte("user123"))

// 100 requests per second, burst 200
l := tokenbucket.New(100, 200)
if err := l.Acquire(nil); err != nil {
    // rate limited
}

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrLimitExceeded is returned when Acquire cannot grant a permit
	// immediately (non-blocking mode).
	ErrLimitExceeded = errors.New("limiter: limit exceeded")

	// ErrKeyRequired is returned when an implementation requires a non-empty
	// key but received an empty one.
	ErrKeyRequired = errors.New("limiter: key must not be empty")

	// ErrInvalidLimit is returned when the configured limit is <= 0.
	ErrInvalidLimit = errors.New("limiter: limit must be greater than zero")

	// ErrInvalidSize is returned when the requested size is <= 0.
	ErrInvalidSize = errors.New("limiter: size must be greater than zero")
)

Sentinel errors returned by limiter implementations.

Functions

func AcquireString

func AcquireString(l Limiter, ctx context.Context, key string) error

AcquireString is a helper that wraps a Limiter with a string key.

func ReleaseString

func ReleaseString(l Limiter, key string)

ReleaseString is a helper that wraps a Limiter with a string key.

Types

type Limiter

type Limiter interface {
	// Running returns the current number of active permits, or -1 if the
	// implementation does not track this metric.
	Running() int

	// Acquire obtains a permit for the given key. The key may be nil for
	// global limiters. Returns ErrLimitExceeded (non-blocking) or
	// context.Canceled / context.DeadlineExceeded (blocking) on failure.
	Acquire(ctx context.Context, key []byte) error

	// Release frees a permit previously obtained via Acquire.
	Release(key []byte)
}

Limiter is the core concurrency-control interface. Every implementation satisfies this contract.

  • Running returns the current number of active permits (-1 if unknown).
  • Acquire attempts to obtain a permit for the given key. In non-blocking implementations it returns ErrLimitExceeded immediately when the limit is reached. In blocking implementations it waits until a permit is available or ctx is cancelled.
  • Release frees a previously acquired permit.

type SizeLimiter

type SizeLimiter interface {
	// Running returns the current total bytes held, or -1 if unknown.
	Running() int64

	// Acquire requests size bytes for the given key.
	Acquire(ctx context.Context, key []byte, size int64) error

	// Release returns size bytes for the given key.
	Release(key []byte, size int64)

	// Remaining returns the remaining capacity for the given key.
	Remaining(key []byte) int64
}

SizeLimiter extends Limiter with byte-size-aware acquisition, useful for bandwidth or storage quotas.

type StringLimiter

type StringLimiter interface {
	Running() int
	Acquire(ctx context.Context, key string) error
	Release(key string)
}

StringLimiter is a string-keyed variant for convenience.

Directories

Path Synopsis
count module
tokenbucket module

Jump to

Keyboard shortcuts

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