VOOZH about

URL: https://deepwiki.com/friendsofhyperf/components/5.5-configuration-and-rate-limiting

⇱ Configuration and Rate Limiting | friendsofhyperf/components | DeepWiki


Loading...
Last indexed: 14 February 2026 (15d5ca)
Menu

Configuration and Rate Limiting

This page documents two infrastructure components: config-consul for dynamic configuration management with Consul integration, and rate-limit for request rate limiting with multiple algorithms and annotation-based control. For cache-based configuration storage, see 5.1. For distributed locking used in rate limiting, see 5.2.

Overview

The configuration and rate limiting subsystems provide runtime control over application behavior:

  • Config-Consul: Enables dynamic configuration updates from Consul without application restarts
  • Rate-Limit: Protects resources from overuse through configurable throttling strategies

Both components integrate with Hyperf's middleware and AOP systems for transparent operation.

Component Architecture


Sources: CHANGELOG-3.1.md36 CHANGELOG-3.1.md63-65 src/config-consul/composer.json1-44


Config-Consul Component

The config-consul component provides dynamic configuration management by synchronizing with HashiCorp Consul's Key-Value store. Configuration updates are detected and applied at runtime without requiring application restarts.

Installation and Setup

Install via Composer:


The component registers itself through FriendsOfHyperf\ConfigConsul\ConfigProvider and requires Hyperf's config-center component as a dependency.

Sources: src/config-consul/composer.json1-2 src/config-consul/composer.json22-26

Configuration Structure

Configuration is managed through Hyperf's config center abstraction. The Consul driver implements the config center interface to fetch and watch configuration changes.

Configuration Flow Diagram


Sources: src/config-consul/composer.json23-26

Dependencies and Integration

The component depends on:

DependencyVersionPurpose
hyperf/codec~3.1.0Data serialization
hyperf/config-center~3.1.0Config center abstraction
hyperf/consul~3.1.0Consul API client
hyperf/stringable~3.1.0String manipulation

Sources: src/config-consul/composer.json23-26

Watch Mode

The component includes a confd.watch option (defaulting to true) that enables continuous polling of configuration changes. When enabled, the FetchProcess worker periodically checks Consul for updates and applies them to the application's configuration container.

Sources: CHANGELOG-3.1.md346


Rate Limit Component

The rate-limit component provides request throttling with four distinct algorithms, annotation-based configuration, and both AOP and middleware enforcement strategies. It was introduced in version 3.1.74 with comprehensive algorithm support and intelligent prioritization.

Installation


Sources: CHANGELOG-3.1.md63

Rate Limiting Algorithms

The component implements four industry-standard rate limiting algorithms:

AlgorithmDescriptionUse Case
FixedWindowAllows N requests per fixed time windowSimple quotas, API tiers
SlidingWindowRolling time window with smooth ratePrevents burst traffic spikes
TokenBucketTokens added at fixed rate, consumed per requestBurst tolerance with average rate control
LeakyBucketProcesses requests at constant rateSmooth output rate, queue management

Algorithm Comparison


Sources: CHANGELOG-3.1.md63

Annotation-Based Rate Limiting

The @RateLimit annotation provides declarative rate limit configuration on controller methods and RPC services. The annotation supports repeatable declaration, allowing multiple rate limit rules on a single method.

Annotation Structure

The annotation includes the following properties:

  • key: Identifier for the rate limit rule
  • limit: Maximum number of requests allowed
  • window: Time window in seconds
  • algorithm: One of the four algorithms
  • IS_REPEATABLE: Flag indicating the annotation can be applied multiple times

Sources: CHANGELOG-3.1.md64

SmartOrder Annotation

The @SmartOrder annotation provides intelligent prioritization of rate limit checks. When multiple @RateLimit annotations are present, @SmartOrder controls the evaluation order, enabling scenarios like:

  • Check user-specific limits before global limits
  • Apply stricter limits for unauthenticated requests
  • Prioritize critical resource limits

Rate Limit Enforcement Flow


Sources: CHANGELOG-3.1.md65

Middleware Integration

The RateLimitMiddleware provides HTTP-layer rate limiting before request routing. This is useful for:

  • Protecting entire route groups
  • Applying global rate limits
  • Rate limiting before authentication

The middleware integrates with Hyperf's middleware pipeline and uses the same RateLimiterManager as the AOP aspects.

Sources: CHANGELOG-3.1.md63

AOP-Based Enforcement

The RateLimitAspect intercepts annotated methods and enforces rate limits transparently. The aspect:

  1. Parses @RateLimit annotations
  2. Evaluates @SmartOrder priorities
  3. Delegates to RateLimiterManager for algorithm execution
  4. Throws exceptions when limits are exceeded

This provides fine-grained control at the method level without modifying business logic.

Sources: CHANGELOG-3.1.md63

Storage Backend

All four algorithms use Redis as the storage backend for counters, timestamps, and tokens. The component requires hyperf/redis as a suggested dependency.

Storage Key Structure


Sources: CHANGELOG-3.1.md63


Integration with Infrastructure Components

Cache Component Integration

The rate limit component can be integrated with the cache component (see 5.1) for storing rate limit metadata outside Redis. This is useful for:

  • Caching rate limit configurations
  • Storing user quota information
  • Maintaining rate limit statistics

Lock Component Integration

The lock component (see 5.2) ensures atomic operations when multiple processes check rate limits simultaneously. This prevents race conditions in distributed environments where:

  • Multiple workers process the same user's requests
  • Rate limit checks occur across different server instances
  • Precise counting is critical

Facade System Access

The facade system (see 5.4) provides static access to rate limiting functionality through the RateLimiter facade, enabling convenient programmatic rate limit checks:


Sources: CHANGELOG-3.1.md63


Configuration Best Practices

Consul Configuration Strategy

When using config-consul:

  1. Namespace Separation: Use Consul folders to separate environments (dev, staging, production)
  2. Key Naming: Use hierarchical keys like app/rate-limit/api/limit
  3. Watch Mode: Enable confd.watch for automatic updates
  4. Fallback Values: Always provide default values in application config files

Rate Limit Strategy Selection

Algorithm Selection Matrix

ScenarioAlgorithmReason
API billing tiersFixedWindowSimple quota tracking
User protectionSlidingWindowSmooth rate enforcement
Burst-tolerant APIsTokenBucketAllow occasional bursts
Message processingLeakyBucketConstant output rate

Performance Considerations

  1. Redis Connection Pooling: Rate limiting is I/O intensive; use connection pools
  2. Key Expiration: Set TTL on Redis keys to prevent memory leaks
  3. Annotation Priority: Use @SmartOrder to check cheap limits first (e.g., IP-based before user-based)
  4. Middleware vs AOP: Use middleware for broad protection, AOP for fine-grained control

Sources: CHANGELOG-3.1.md63-65 CHANGELOG-3.1.md346