window

package
v0.5.0 Latest Latest
Warning

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

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

Documentation

Overview

Package window provides the shared rate-limit window primitive used by every limiter domain (internal/rate and internal/limiters). It implements two counting algorithms behind one interface:

  • Fixed: classic fixed-window counter. INCR plus a first-hit PEXPIRE, executed as a single Lua script so a crash between the two commands can never leave an orphaned counter without a TTL.
  • Sliding: weighted two-bucket sliding-window approximation. Counts are kept in per-bucket keys (bucket length = the window) and the effective count is curr + floor(prev * (window-elapsed)/window), removing the fixed-window 2x boundary-burst weakness with O(1) memory per key.

Bucket indexes are computed from the client clock (injectable for tests); hosts are expected to be NTP-synced. Sliding bucket keys are hash-tagged ("{base}:s:<bucket>") so both buckets always share a Redis Cluster slot.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Mode

type Mode int

Mode selects the window-counting algorithm. The zero value is Fixed so existing call sites keep their behavior.

const (
	// Fixed is the classic fixed-window counter (default).
	Fixed Mode = iota
	// Sliding is the weighted two-bucket sliding-window approximation.
	Sliding
)

type Window

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

Window counts events per key using the configured algorithm.

func New

func New(rdb redis.UniversalClient, mode Mode) *Window

New creates a window counter over the given Redis client.

func (*Window) Count

func (w *Window) Count(ctx context.Context, key string, window time.Duration) (int64, error)

Count returns the current effective count for key without incrementing. Missing keys count as zero.

func (*Window) Incr

func (w *Window) Incr(ctx context.Context, key string, window time.Duration) (int64, error)

Incr records one event for key and returns the effective count within the window. A non-positive window means "no expiry": a plain INCR regardless of mode (used by the lockout limiter's manual-unlock configuration).

func (*Window) Reset

func (w *Window) Reset(ctx context.Context, key string, window time.Duration) error

Reset clears all window state for key.

Jump to

Keyboard shortcuts

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