VOOZH about

URL: https://deepwiki.com/hypervel/cache/3.2-swoole-store

⇱ Swoole Store | hypervel/cache | DeepWiki


Loading...
Menu

Swoole Store

Purpose and Scope

This document explains the SwooleStore implementation, which provides high-performance shared memory caching using Swoole's table data structure. The store offers sub-microsecond read/write performance by storing cache data directly in shared memory accessible across all worker processes. This document covers the table structure, eviction policies (LRU/LFU/TTL/NOEVICTION), memory management, interval caching, and configuration through SwooleTableManager.

For multi-tier caching strategies that combine SwooleStore with other stores, see Stack Store. For general cache store contracts and interfaces, see Store Contracts.


Architecture Overview

The SwooleStore class implements the Store interface and utilizes Swoole's Table class for data storage. The table resides in shared memory, making cached values accessible across all Swoole worker processes without inter-process communication overhead. The SwooleTableManager handles table creation and configuration resolution.

SwooleStore Component Architecture


Sources: src/SwooleStore.php14-40 src/SwooleTableManager.php12-33


Table Structure and Initialization

The Swoole table uses a fixed schema with four columns that support cache operations and eviction policies.

Table Schema

ColumnTypePurpose
valueSTRINGSerialized cache value
expirationFLOATUNIX timestamp (microsecond precision) when entry expires
last_used_atFLOATUNIX timestamp (microsecond precision) of last access, used for LRU eviction
used_countINTNumber of times entry has been accessed, used for LFU eviction

SwooleTableManager Creation Flow


Sources: src/SwooleTableManager.php21-33 src/SwooleTableManager.php35-62

Configuration Parameters

The SwooleTableManager resolves table configuration from cache.swoole_tables.{name}:

  • rows (default: 1024): Maximum number of cache entries the table can hold
  • bytes (default: 10240): Maximum size in bytes for the value column
  • conflict_proportion (default: 0.2): Hash collision allowance (0.2 = 20% extra memory for collision handling)

Sources: src/SwooleTableManager.php48-52 src/SwooleTableManager.php55-62


Basic Cache Operations

The SwooleStore implements standard cache operations with microsecond-precision timestamps and automatic eviction triggering.

Get Operation with Usage Tracking


The getRecord() method src/SwooleStore.php261-275 automatically updates last_used_at and used_count columns on every read, providing data for LRU and LFU eviction policies.

Sources: src/SwooleStore.php45-61 src/SwooleStore.php261-275 src/SwooleStore.php233-236

Put Operation with Eviction

When storing a value via put(), the store:

  1. Serializes the value
  2. Calculates expiration timestamp as currentTimestamp + seconds
  3. Writes to the Swoole table using table->set()
  4. Triggers evictRecords() to maintain memory limits

Sources: src/SwooleStore.php85-97

Other Standard Operations

OperationMethodImplementation
Store multipleputMany()Iterates and calls put() for each key-value pair
Store if absentadd()Checks table->exists() before calling put()
Incrementincrement()Reads, deserializes, adds value, serializes, writes back
Decrementdecrement()Calls increment() with negated value
Store foreverforever()Calls put() with ONE_YEAR (31536000 seconds)
Removeforget()Calls table->del()
Clear allflush()Iterates all keys (except interval-* keys) and calls forget()

Sources: src/SwooleStore.php102-156 src/SwooleStore.php209-228


Interval Caching

Interval caching provides periodic cache refresh functionality, ensuring frequently-accessed expensive computations remain warm without manual cache invalidation.

Interval Cache Mechanism


Sources: src/SwooleStore.php161-176 src/SwooleStore.php181-204

Interval Storage Format

Interval metadata is stored as a separate cache entry with key interval-{originalKey}:


The SerializableClosure wrapper allows storing closures in serialized form. The refreshIntervalCaches() method is typically called by a Swoole timer registered during server startup (see Event System).

Sources: src/SwooleStore.php169-173 src/SwooleStore.php200-204


Memory Management and Eviction Policies

The SwooleStore implements proactive memory management with configurable eviction policies to prevent memory exhaustion.

Memory Limit Detection

The store monitors two metrics to determine if eviction is needed:


Conflict Rate measures hash collision pressure. When available_slice_num is low, the table's hash structure is experiencing high collision rates.

Memory Usage measures the ratio of stored entries to total capacity.

Both metrics are compared against 1 - memoryLimitBuffer. For example, if memoryLimitBuffer = 0.1, eviction triggers at 90% capacity.

Sources: src/SwooleStore.php288-296

Eviction Flow


Sources: src/SwooleStore.php249-256 src/SwooleStore.php298-317 src/SwooleStore.php356-371

Eviction Policies

The store supports four eviction policies defined as class constants:

PolicyConstantColumn UsedBehavior
LRUEVICTION_POLICY_LRUlast_used_atRemoves least recently used entries based on access timestamp
LFUEVICTION_POLICY_LFUused_countRemoves least frequently used entries based on access count
TTLEVICTION_POLICY_TTLexpirationRemoves entries with earliest expiration (soonest to expire)
No EvictionEVICTION_POLICY_NOEVICTIONN/AThrows exception when memory limit reached

Sources: src/SwooleStore.php16-22 src/SwooleStore.php298-317

LimitedMaxHeap for Efficient Eviction

The handleRecordsEviction() method uses a LimitedMaxHeap (defined inline as an anonymous class) to efficiently select the top N entries for eviction without sorting the entire table:


The heap maintains only evictionProportion * tableSize entries (e.g., 10% of table size), making eviction O(n log k) where k is the eviction proportion, rather than O(n log n) for full sorting.

Sources: src/SwooleStore.php334-354

Stale Record Cleanup

Before policy-based eviction, the flushStaleRecords() method removes all expired entries:


This two-pass approach (collect keys, then delete) avoids modifying the table while iterating over it.

Sources: src/SwooleStore.php356-371


SwooleTableManager

The SwooleTableManager class provides centralized table creation and caching, ensuring each named table is created only once.

Manager Architecture


Sources: src/SwooleTableManager.php12-63

Table Creation Process

The createTable() method instantiates the custom SwooleTable wrapper (not standard Swoole\Table) and defines the four-column schema:


The SwooleTable wrapper (imported as use Swoole\Table) applies the conflictProportion configuration during construction.

Sources: src/SwooleTableManager.php21-33

Configuration Resolution

The manager resolves configuration from the path cache.swoole_tables.{name}:


The special 'null' name returns null config, which causes resolve() to throw an InvalidArgumentException.

Sources: src/SwooleTableManager.php55-62


Configuration Example

Example configuration in config/autoload/cache.php:


Configuration Parameters

ParameterTypeDefaultDescription
driverstringN/AMust be 'swoole'
tablestringN/AName of table configuration in swoole_tables
memory_limit_bufferfloat0.1Reserve buffer before triggering eviction (0.1 = 10% buffer)
eviction_policystring'lru'One of: 'lru', 'lfu', 'ttl', 'noeviction'
eviction_proportionfloat0.1Proportion of entries to evict when memory limit reached
swoole_tables.{name}.rowsint1024Maximum number of cache entries
swoole_tables.{name}.bytesint10240Maximum bytes per value
swoole_tables.{name}.conflict_proportionfloat0.2Hash collision allowance

Sources: src/SwooleStore.php34-40 src/SwooleTableManager.php48-52


Usage Example

The SwooleStore is accessed through the standard cache interface:


The interval cache is refreshed by the CreateTimer listener, which registers a Swoole timer that calls refreshIntervalCaches() periodically. See Event System for timer registration details.

Sources: src/SwooleStore.php161-176 src/SwooleStore.php181-195