Appearance
Cache Management
Flow ID: SY-07 | Module(s): job, helpers, libraries (Pscache) | Complexity: Low | Last Updated: 2026-10-19 — 4.128.0 resync: Pscache read-through and opt-in negative-result caching (#666), Known Issues and Tests sections added
Business Overview
Cache management ensures the application's file-based cache does not grow unbounded and can be selectively or fully cleared. Two complementary jobs handle this: one for on-demand or scheduled full/partial cache clearing, and another that monitors disk usage and auto-purges when a configurable size limit is exceeded. These jobs only act on file-based caching; Redis-backed deployments skip the size-monitoring job entirely.
The Pscache library is the read-through cache most legacy storefront queries go through. By default it remembers only results that found something; since 4.128 a caller can opt in to also remembering "nothing found" (#666), which the storefront uses for dead URLs and empty filter listings so that crawler traffic does not re-run the same misses against the database. A result computed while any database statement failed is never remembered for such a caller.
Cache Tier Architecture
The application uses a 4-tier cache architecture:
┌─────────────────────────────────────────────────────────────────┐
│ L0: InMemory (per-request) │
│ Static arrays within services. Lifetime = single PHP request. │
│ No serialization cost. Used for repeated lookups. │
├─────────────────────────────────────────────────────────────────┤
│ L1: APCu / SHM (pod-local) │
│ Shared memory on the same server. Fast, but not distributed. │
│ Lost on PHP-FPM restart. Used for hot config and registry. │
├─────────────────────────────────────────────────────────────────┤
│ L2: File / Redis (distributed) │
│ Configurable via APP_CACHE_L2_ADAPTER (FileAdapter or Redis). │
│ Default TTL: 86400s (1 day). Survives restarts. │
│ Search TTL: 43200s (12h). SEO TTL: 864000s (10 days). │
├─────────────────────────────────────────────────────────────────┤
│ Session: Redis (7-day TTL) │
│ Customer session data. Shared across pods in clustered envs. │
└─────────────────────────────────────────────────────────────────┘L2 TTL defaults:
| Category | TTL | Description |
|---|---|---|
| Default | 86,400s (1 day) | Most cached data |
| Search | 43,200s (12 hours) | Search results and facets |
| SEO | 864,000s (10 days) | Meta tags, canonical URLs, sitemap data |
PSCache wrapper: The Pscache library provides dependency tracking and language-aware cache keys: a read-through key is {language_abbr}.{property}.{sha1(method + serialize(arguments))} (application/libraries/Pscache.php:208-212), so multilingual content is cached separately per language, and delete_group() clears one {lang}.{group}.* pattern per admin language (:390-402).
Pscache Read-Through and Negative Results (#666)
Pscache::model() (application/libraries/Pscache.php:96-103) and library() (:73-80) load the model or library if it is not attached, then call _call() (:121-174):
- Read: with a positive TTL (the caller's
$expires, orcache_l2_default_expireswhen null) the entry is read (:132-133); a TTL <= 0 deletes the entry and bypasses the cache (:134-137). - Serve: a stored value other than
false/nullis returned (:139-143). A storedfalse/nullis returned only when the caller passed$cacheNegative = trueand the entry carries the__cache_negativemarker (:144-146). Any other negative entry is treated as a miss, so a negative written by a non-opted call is never served as verified to an opted-in one. - Compute: the model or library method runs (
:151). - Write: with a positive TTL the result is written (
:157-171), negative results included, but only an opted-in caller's negative is marked__cache_negative(:158,:169,write()at:322-347). For an opted-in call nothing at all is written, positive or negative, whendbReportsError()(:194-206) says the default connection had a failure during the call: the driver's failed-statement count (advmysqli_driver::$failedQueryCount,system/database/drivers/advmysqli/advmysqli_driver.php:74, incremented in_execute()at:254-262) rose since before the call (dbFailedQueryCount(),:179-182, snapshot at:149), or the last statement reports an error code, or there is no DB object, noerror()method or noconn_id. The count exists becauseerror()reports only the last statement, and withdb_debugoff a failed query reaches the model as an ordinary "nothing found". - Non-opted calls behave as before: their
false/nullis written but never served (so it is recomputed on every call), and they still cache a result computed after a failed query.
get() (:273-279) keeps returning false for a miss; it now reads through the private read() (:284-315), which returns the whole envelope (or null on a miss, a malformed entry or a failed dependency check) so _call() can tell a stored false from a miss.
Opt-in call sites (the flag is passed positionally, so a fork whose Pscache override lacks the parameter silently keeps the old behaviour):
| Call | Site | Negative cached |
|---|---|---|
product_model::existsBySlug (product slug) | ecommercen/eshop/controllers/Adv_eshop.php:67-73 | dead URL: no product with that slug |
product_category_model::existsBySlug (category part of a product URL) | Adv_eshop.php:74-82 | evaluated only when the product slug exists |
product_model::findSlugsByUrl (canonical redirect) | Adv_eshop.php:90-96 | no canonical match |
product_model::getCatProducts (category page listing) | ecommercen/eshop/controllers/Adv_product_categories.php:293-318 | zero-product listing (false) |
Not opted in: the baseCategory() slug lookup (Adv_eshop.php:117) and the sidebar tag facet getOfferableListingTagIds(), which returns null on a failed facet statement so that the failure is retried rather than served (see CF-01 Product Browsing).
Override note: model(), library(), _call() and write() gained a trailing optional parameter ($cacheNegative / $negative); a fork that overrides any of them must add it to stay signature-compatible.
Healthz endpoint: The application health check endpoint verifies both L1 and L2 cache health, returning degraded status if either tier is unavailable.
Development mode: When development mode is active, all cache expiration is set to TTL = -1 (disabled), effectively bypassing all caching layers.
Cache Invalidation Groups
10+ module invalidation groups are available via clearCache():
| Group | Models/Keys Cleared |
|---|---|
products | 13 product-related models (pricing, stock, attributes, variations, etc.) |
search | search_model, lines_model |
seo | metatags_model, seo_lib |
cms | categories_model, subcontent_model |
blog | blog_category_model, blog_author_model, blog_tags_model, blog_model |
sliders | slideshow_group_model, sliders_model, slide_model |
maps | maps_model |
promo | promo_model |
settings | settings, registry, registry_model, transporters_model, cookies_model |
product_bundles | product_bundle_storage_model |
cloudflare | Special: calls clearCloudflareCache() (Cloudflare zone purge) |
all | Full purge via Pscache::delete_all() |
Architecture
AdvClearSiteCache (job) AdvClearCacheOnLimit (job)
| |
v v
JobClearCacheTrait Check cache_l2_adapter
| (FileAdapter only)
v |
clearCache() helper v
(pscache_helper) du -s -k on cache path
| |
v v
clearPsCacheArray() If over limit -> clearCache()
| |
v v
Pscache Pscache
delete_all() or delete_all()
delete_group()Key Components
| Component | Path | Role |
|---|---|---|
AdvClearSiteCache | ecommercen/job/libraries/AdvClearSiteCache.php | Job: clears specific or all cache groups |
AdvClearCacheOnLimit | ecommercen/job/libraries/AdvClearCacheOnLimit.php | Job: monitors file cache size, clears when over limit |
JobClearCacheTrait | ecommercen/job/libraries/JobClearCacheTrait.php | Shared trait providing clearCache() delegation |
clearCache() | ecommercen/helpers/pscache_helper.php | Helper: routes cache option to model-group clearing |
clearPsCacheArray() | ecommercen/helpers/pscache_helper.php | Helper: deletes all or specific cache groups via Pscache |
clearCloudflareCache() | ecommercen/helpers/pscache_helper.php | Helper: purges Cloudflare CDN cache via zone API |
Pscache | application/libraries/Pscache.php | Cache library wrapping PSR-6 CachePool |
| Client stubs | application/modules/job/libraries/ClearSiteCache.php, ClearCacheOnLimit.php | Empty extension points for client overrides |
Code Flow
AdvClearSiteCache
- Entry:
executeCommand(['cache' => $option])where$optionis an optional cache group name. - Delegation: Calls
$this->clearCache($option)viaJobClearCacheTrait. - Trait logic: If no option provided, defaults to
'all'. - Helper dispatch: Calls global
clearCache($option)frompscache_helper.php. - Group resolution: A
switchstatement maps the option string to an array of model group names:'maps'->['maps_model']'cms'->['categories_model', 'subcontent_model']'blog'->['blog_category_model', 'blog_author_model', 'blog_tags_model', 'blog_model']'sliders'->['slideshow_group_model', 'sliders_model', 'slide_model']'promo'->['promo_model']'product_categories_vendors'->['product_category_model', 'vendors_model']'settings'->['settings', 'registry', 'registry_model', 'transporters_model', 'cookies_model']'seo'->['metatags_model', 'seo_lib']'products'-> 13 product-related models'search'->['search_model', 'lines_model']'product_bundles'->['product_bundle_storage_model']'cloudflare'-> Special path: callsclearCloudflareCache()directly (Cloudflare zone purge)'all'(default) -> Empty array, which triggersPscache::delete_all()
- Cache deletion:
clearPsCacheArray($models)calls either$pscache->delete_all()(when models is empty) or iterates and calls$pscache->delete_group(group: $model)for each model.
AdvClearCacheOnLimit
- Entry:
executeCommand([])-- no options. - Adapter check: Reads
cache_l2_adapterconfig. If notFileAdapter::class, logs info and returns (no-op for Redis). - Size measurement: Executes
du -s -k <cache_path>via shellexec()to get cache directory size in KB. - Limit comparison: Compares measured size against
getCacheSizeLimit()(configcache_l2_size_limit, in GB, converted to KB for comparison). - Conditional clear: If size exceeds limit, calls
$this->clearCache()(via trait -> full cache purge). - Logging: Logs current cache size in GB and whether action was taken.
Data Model
No database tables are involved. Cache operates on the filesystem (or Redis, but the limit job only monitors files).
| Config Key | Source | Description |
|---|---|---|
cache_l2_adapter | application/config/cache.php | Adapter FQCN (FileAdapter or RedisAdapter) |
cache_l2_connection | application/config/cache.php | File path or Redis connection string |
cache_l2_size_limit | application/config/cache.php | Max cache size in GB (default: 5) |
cache_l2_default_expires | application/config/cache.php | Default TTL in seconds (default: 86400) |
Configuration
Environment Variables
| Variable | Default | Description |
|---|---|---|
APP_CACHE_L2_ADAPTER | FileAdapter::class | Cache adapter class |
APP_CACHE_L2_CONNECTION | ../cache/ | Cache storage path |
APP_CACHE_L2_SIZE_LIMIT | 5 | Size limit in GB (5 standard, 10 for dedicated) |
APP_CACHE_L2_PREFIX | '' | Cache key prefix |
Job Options
| Job | Option | Type | Required | Description |
|---|---|---|---|---|
AdvClearSiteCache | cache | string | No | Cache group to clear (e.g., products, settings, all) |
AdvClearCacheOnLimit | (none) | -- | -- | No options; auto-detects adapter and path |
Cache Group Names
Valid values for the cache option: maps, cms, blog, sliders, promo, product_categories_vendors, settings, seo, products, search, product_bundles, cloudflare, all.
Client Extension Points
- Job override: Create
ClearSiteCacheorClearCacheOnLimitinapplication/modules/job/libraries/extending theAdv*base class to add custom cache groups or logic. - Cache group mapping: The
clearCache()helper inpscache_helper.phpcan be overridden in client repos by defining the function before the helper loads. - Cloudflare integration: Clients with Cloudflare can use the
cloudflarecache option to purge CDN cache via the Cloudflare library.
Business Rules
- File adapter only:
AdvClearCacheOnLimitis a no-op whencache_l2_adapteris notFileAdapter. It silently logs and returns. - Default is full purge: When no cache group is specified,
AdvClearSiteCacheclears all cached data. - Size limit in GB: The
cache_l2_size_limitconfig is in GB. Default is 5 GB globally; dedicated clients may use 10 GB. - Shell dependency:
AdvClearCacheOnLimitdepends on theducommand being available in the system PATH. - Language-scoped path: Cache path includes the language abbreviation suffix (e.g.,
../cache/el/). - Development mode: In development, all cache expiration is set to
-1(disabled), so these jobs have limited effect. - Negative results are opt-in: a
false/nullfrom a Pscache read-through is served from cache only to a caller that passed$cacheNegative = true, and only from an entry written by such a caller (application/libraries/Pscache.php:144-146,:169). - No caching after a DB failure for opted-in calls: if any statement failed during the call, or the connection is gone, an opted-in call writes nothing (
application/libraries/Pscache.php:157,:194-206).
Known Issues & Security Gaps
- A cached negative outlives the creation of the thing it denies — since #666 a dead product URL's
existsBySlug/findSlugsByUrlmisses and an empty category listing are cached for the caller's TTL (ecommercen/eshop/controllers/Adv_eshop.php:67-96,ecommercen/eshop/controllers/Adv_product_categories.php:293-318;pscache_ttl=cache_l2_default_expires, default 86400 s,application/config/cache.php:7). No upstream product save clears theproduct_modelgroup: the onlyclearCache('products')calls are inecommercen/eshop/controllers/Adv_vats_admin.php:136-146, andAdv_products_admin.phpmakes no Pscache call; the one product-modifying path that clears it is the category admin's bulk discount update, which callsdelete_all()(ecommercen/eshop/controllers/Adv_product_categories_admin.php:739-743), not a create or rename. So a product whose URL was requested before it was created or renamed answers 404 until the entry expires, the dailyClearSiteCachejob runs (application/config/jobs.php:28,0 6 * * *), or someone clears the cache; likewise a filter listing that was empty stays empty after matching products are added. Before #666 those misses were recomputed on every request. (Positive entries already had the same staleness.) - No single-flight on a cold key —
_call()takes no lock between the miss and the write (application/libraries/Pscache.php:139-171), so concurrent requests for the same cold key (crawler bursts on the same filter URL) each run the query. #666 removed repeat misses, not the stampede on the first one; single-flight locking was deferred. - Unmarked negatives are still written — a non-opted call writes its
false/null(application/libraries/Pscache.php:157-171) although_call()never serves it to anyone, costing one cache write per miss.
Tests
| Test | Covers |
|---|---|
tests/Unit/Pscache/PscacheTest.php | #666: a non-opted negative is recomputed; an opted-in negative is served for the caller's TTL and a cached hit is not rewritten; nothing is cached when the DB reports an error, when the connection is gone, when no DB is loaded, or when an earlier query in the call failed; a non-opted call still caches after a failed query; an opted-in call does not serve a negative written by a non-opted call; positives still cached; get() still returns false for a miss. Also the earlier model() / library() load-guard regressions (#499) |
tests/Unit/Database/AdvmysqliFailedQueryCountTest.php | advmysqli_driver::$failedQueryCount: failed statements are counted and a later success does not reset the count |
tests/Support/PscacheProbeClasses.php | Global probe model/library classes the Pscache tests attach (including a negative-returning model) |
Gap: no test covers AdvClearSiteCache, AdvClearCacheOnLimit or the clearCache() group mapping.
Related Flows
- CF-01 Product Browsing -- the category listing and sidebar tag facet, the main users of the opt-in negative cache
- CF-03 URL Routing -- the
Adv_eshopdispatcher whose product lookups are negatively cached - SY-01 Cron Framework -- Job registration and scheduling infrastructure
- SY-29 Deployment Architecture -- FileAdapter on Plesk vs. RedisAdapter on K8s deployment targets
Wiki Guide: Cache Guide -- cache adapter configuration and usage patterns