VOOZH about

URL: https://deepwiki.com/hypervel/cache/4-advanced-features

⇱ Advanced Features | hypervel/cache | DeepWiki


Loading...
Menu

Advanced Features

This page provides an overview of advanced caching capabilities available in the hypervel/cache package. These features extend the basic cache operations to support complex use cases such as tag-based cache invalidation, distributed locking across processes, rate limiting mechanisms, and intelligent memory management with configurable eviction policies.

For basic cache operations and store configuration, see Core Components. For framework integration details, see Integration and Operations.

Overview of Advanced Features

The hypervel/cache package provides four primary categories of advanced functionality:

Feature CategoryPrimary Use CaseKey ComponentsSupported Stores
Tagged CachingInvalidate related cache entries by tagsRedisTaggedCache, RedisTagSetRedis
Distributed LockingCoordinate exclusive access across processesDatabaseLock, RedisLock, FileLock, ArrayLockDatabase, Redis, File, Array
Rate LimitingControl operation frequency with decay windowsLimitAll stores with locking support
Memory ManagementAutomatic eviction when memory limits reachedSwooleStore with policiesSwoole

These features integrate with the core store implementations through well-defined contracts and extend the basic cache operations with additional coordination and management capabilities.

Sources: src/SwooleStore.php1-372 src/DatabaseLock.php1-204 src/RedisTagSet.php1-122 src/RedisTaggedCache.php1-125

Advanced Features Architecture


This diagram illustrates how advanced features integrate with the core cache architecture. The Repository provides access methods for tagging and locking, while stores implement the necessary contracts. Memory management operates transparently within the SwooleStore.

Sources: src/RedisTaggedCache.php1-125 src/RedisTagSet.php1-122 src/DatabaseLock.php1-204 src/SwooleStore.php1-372

Tagged Caching System

Tagged caching enables associating cache entries with one or more semantic tags and performing bulk operations on all entries sharing specific tags. This is particularly useful for invalidating related data without knowing individual cache keys.

Key Components

ComponentPurposeKey Methods
RedisTaggedCacheTag-aware cache operationsput(), add(), increment(), flush(), flushStale()
RedisTagSetTag-to-entry relationship managementaddEntry(), entries(), flushStaleEntries(), tagId()
TaggedCacheBase class for tagged implementationsProvides common tagged cache behavior

Tag Storage Structure

Redis tags are stored as sorted sets with the key pattern tag:{name}:entries. The score in each sorted set represents the expiration timestamp of the cached entry, enabling efficient removal of stale entries via ZREMRANGEBYSCORE.


When you call flush() on a tagged cache, the system scans all entries in the tag's sorted set and deletes the corresponding cache keys. The flushStale() method src/RedisTaggedCache.php119-124 removes only expired entries by using Redis ZREMRANGEBYSCORE src/RedisTagSet.php80-87

For detailed information on tagged cache operations and implementation, see Cache Tagging.

Sources: src/RedisTaggedCache.php1-125 src/RedisTagSet.php1-122

Distributed Locking

Distributed locking provides a mechanism for coordinating exclusive access to shared resources across multiple processes or servers. All major store implementations provide lock support through the LockProvider interface.

Lock Implementations

Lock ClassStorage MechanismDistributedRefreshableUse Case
RedisLockRedis keys with Lua scriptsYesYesDistributed systems
DatabaseLockDatabase table rowsYesYesDatabase-backed coordination
FileLockFilesystem locks via LockableFileNoNoSingle-server file-based
ArrayLockIn-memory PHP arraysNoYesIn-process coordination
NoLockNo-op implementationNoNoNull store compatibility

Refreshable Locks

The RefreshableLock interface src/DatabaseLock.php10 enables extending lock TTL without releasing and reacquiring. This is implemented by DatabaseLock, RedisLock, and ArrayLock.


The DatabaseLock implementation src/DatabaseLock.php75-105 uses a two-phase acquisition strategy: first attempting an insert, then falling back to an update if a lock already exists but is either owned by the current process or expired. It also implements a lottery-based cleanup src/DatabaseLock.php100-102 to probabilistically remove expired locks.

For comprehensive locking patterns and implementation details, see Distributed Locking.

Sources: src/DatabaseLock.php1-204

Rate Limiting

Rate limiting controls the frequency of operations using time-based decay windows. The Limit class provides a fluent API for defining rate limit constraints.

Rate Limit Configuration

Rate limits are defined using the Limit class with methods like perMinute(), perHour(), and perDay(). These limits are enforced through the RateLimiter class which uses the cache store's locking mechanism.

Configuration MethodMaximum AttemptsDecay Period
perMinute(int)Configurable60 seconds
perHour(int)Configurable3600 seconds
perDay(int)Configurable86400 seconds
perSecond(int)Configurable1 second

Rate limiting is typically used in conjunction with distributed locks to ensure atomic increment operations when tracking attempt counts.

For detailed rate limiting implementation and usage patterns, see Rate Limiting.

Sources: Referenced through lock provider integration in cache operations

Memory Management and Eviction Policies

The SwooleStore implements sophisticated memory management with configurable eviction policies to handle situations where the Swoole table reaches capacity.

Eviction Policies

The store supports four eviction policies defined as constants src/SwooleStore.php16-22:

Policy ConstantStrategySelection CriterionUse Case
EVICTION_POLICY_LRULeast Recently Usedlast_used_at timestampTime-based access patterns
EVICTION_POLICY_LFULeast Frequently Usedused_count counterFrequency-based patterns
EVICTION_POLICY_TTLShortest Time-to-Liveexpiration timestampExpire soonest entries first
EVICTION_POLICY_NOEVICTIONNo evictionN/AFail when full

Eviction Flow


The eviction process src/SwooleStore.php248-256 first removes stale expired records, then checks if memory limits are reached. Memory usage is determined by two metrics: conflict rate and table utilization src/SwooleStore.php288-296 If eviction is needed, the store uses a LimitedMaxHeap data structure src/SwooleStore.php334-354 to efficiently select the bottom N% of records (configured via evictionProportion) based on the chosen policy criterion.

Automatic Access Tracking

The SwooleStore automatically tracks access metadata src/SwooleStore.php261-275:

  • last_used_at: Updated on every get() call
  • used_count: Incremented on every get() call

This metadata enables LRU and LFU eviction policies without additional application-level tracking.

Interval Caching

The SwooleStore also supports interval-based cache refresh src/SwooleStore.php161-176 where cache values are automatically regenerated at specified intervals using a closure resolver. This is useful for expensive computations that should be updated periodically.

For comprehensive memory management details and eviction policy configuration, see Memory Management and Eviction.

Sources: src/SwooleStore.php1-372

Feature Interaction Matrix

Understanding how advanced features interact with different store types is essential for architecture decisions:

Store TypeTagged CachingDistributed LocksRate LimitingEviction PoliciesInterval Caching
RedisStore✓ Full support✓ Lua-based✓ Via locks
DatabaseStore✓ Table-based✓ Via locks
SwooleStore✗ Non-distributedLimited✓ Full support✓ Full support
FileStore✓ File-based✓ Via locks
ArrayStore✓ In-process✓ Via locks
StackStoreVia Redis tierVia any tierVia any tierVia Swoole tierVia Swoole tier

The StackStore enables combining features from multiple stores, such as using Redis for tagged caching while leveraging Swoole for memory management and interval caching in the L1 tier.

Sources: src/SwooleStore.php1-372 src/RedisTaggedCache.php1-125 src/DatabaseLock.php1-204