VOOZH about

URL: https://deepwiki.com/hypervel/redis/7.1-duration-limiter

⇱ Duration Limiter | hypervel/redis | DeepWiki


Loading...
Menu

Duration Limiter

Purpose and Scope

The DurationLimiter class implements distributed, time-based rate limiting using Redis as a backend store. It enforces a maximum number of concurrent operations (maxLocks) within a sliding time window (decay seconds), using atomic Lua scripts to ensure consistency across distributed application instances.

For information about the timeout exception thrown by this limiter, see Timeout Exceptions. For information about the underlying Redis connection management, see Redis Factory.

Sources: src/Limiters/DurationLimiter.php1-181


Architecture and Integration

The DurationLimiter integrates with the Hypervel Redis infrastructure to provide distributed rate limiting capabilities:


Sources: src/Limiters/DurationLimiter.php10-38 src/RedisFactory.php1-37


Constructor and Configuration

The DurationLimiter constructor accepts five parameters that define the limiter's behavior:

ParameterTypeDescription
$redisRedisFactoryThe Redis factory for obtaining connections
$connectionstringThe named Redis connection pool to use (e.g., 'default', 'cache')
$namestringUnique identifier for this limiter instance (used as Redis key)
$maxLocksintMaximum number of concurrent acquisitions allowed
$decayintDuration in seconds for each time window

Sources: src/Limiters/DurationLimiter.php24-38


State Management in Redis

The limiter stores its state in a Redis hash with three fields that track the current time window:


Public Properties

After calling acquire() or tooManyAttempts(), two public properties are populated:

Sources: src/Limiters/DurationLimiter.php12-20 src/Limiters/DurationLimiter.php81-85 src/Limiters/DurationLimiter.php93-105


Core Operations

acquire() Method

The acquire() method attempts to claim a slot in the current time window. It returns true if successful, false if the limit is reached.


Sources: src/Limiters/DurationLimiter.php64-86 src/Limiters/DurationLimiter.php130-152


block() Method

The block() method provides blocking acquisition with retry logic and timeout handling:


Method Signature:































ParameterTypeDefaultDescription
$timeoutint-Maximum seconds to wait for acquisition
$callback?callablenullOptional callback to execute after successful acquisition
$sleepint750Milliseconds to sleep between retry attempts

Sources: src/Limiters/DurationLimiter.php40-62


tooManyAttempts() Method

The tooManyAttempts() method performs a read-only check without attempting acquisition:


Returns: true if no slots are available, false if slots remain.

Sources: src/Limiters/DurationLimiter.php88-106 src/Limiters/DurationLimiter.php163-180


clear() Method

The clear() method removes the limiter's state from Redis, resetting it completely:


Sources: src/Limiters/DurationLimiter.php108-114


Lua Script Implementation

The limiter uses two Lua scripts executed atomically on the Redis server to ensure consistency across distributed instances.

Acquisition Script (acquire)


Lua Script Parameters:

Key/ArgumentValueDescription
KEYS[1]$this->nameThe limiter's Redis key
ARGV[1]microtime(true)Current time in microseconds
ARGV[2]time()Current time in seconds
ARGV[3]$this->decayDuration of the time window
ARGV[4]$this->maxLocksMaximum allowed acquisitions

Return Array:

  • [0]: Boolean success (1) or failure (0)
  • [1]: Window end timestamp
  • [2]: Remaining slots

Sources: src/Limiters/DurationLimiter.php121-152


Check Script (tooManyAttempts)

The tooManyAttemptsLuaScript() performs read-only checks:


Return Array:

  • [0]: Window end timestamp (or 0 if no active window)
  • [1]: Remaining slots (or $decay if no active window)

Sources: src/Limiters/DurationLimiter.php154-180


Connection Management

The getConnection() method retrieves the Redis connection through the factory:


Sources: src/Limiters/DurationLimiter.php116-119


Usage Patterns

Pattern 1: Non-Blocking Acquisition


Pattern 2: Blocking with Timeout


Pattern 3: Check Before Attempting


Pattern 4: Manual Cleanup


Sources: src/Limiters/DurationLimiter.php1-181


Time Window Behavior

The limiter uses sliding time windows with the following characteristics:

ScenarioBehavior
First acquisitionCreates new window starting now, ending at time() + decay
Within active windowIncrements count, compares to maxLocks
Window expiredResets window with new start/end times
Hash expirationRedis key expires at decay * 2 to prevent stale data

Sources: src/Limiters/DurationLimiter.php130-152


Integration with Redis Factory

The DurationLimiter depends on RedisFactory for connection management:


This design allows:

  • Multi-pool support: Different limiters can use different Redis connections
  • Configuration flexibility: Connection parameters managed centrally
  • Dependency injection: Factory injected via constructor

Sources: src/Limiters/DurationLimiter.php31-38 src/Limiters/DurationLimiter.php116-119 src/RedisFactory.php28-36


Error Handling

The only exception thrown by DurationLimiter is LimiterTimeoutException:


Exception Details:

Sources: src/Limiters/DurationLimiter.php40-62