Skip to content

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:

CategoryTTLDescription
Default86,400s (1 day)Most cached data
Search43,200s (12 hours)Search results and facets
SEO864,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):

  1. Read: with a positive TTL (the caller's $expires, or cache_l2_default_expires when null) the entry is read (:132-133); a TTL <= 0 deletes the entry and bypasses the cache (:134-137).
  2. Serve: a stored value other than false / null is returned (:139-143). A stored false / null is returned only when the caller passed $cacheNegative = true and the entry carries the __cache_negative marker (: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.
  3. Compute: the model or library method runs (:151).
  4. 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, when dbReportsError() (: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, no error() method or no conn_id. The count exists because error() reports only the last statement, and with db_debug off a failed query reaches the model as an ordinary "nothing found".
  5. Non-opted calls behave as before: their false / null is 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):

CallSiteNegative cached
product_model::existsBySlug (product slug)ecommercen/eshop/controllers/Adv_eshop.php:67-73dead URL: no product with that slug
product_category_model::existsBySlug (category part of a product URL)Adv_eshop.php:74-82evaluated only when the product slug exists
product_model::findSlugsByUrl (canonical redirect)Adv_eshop.php:90-96no canonical match
product_model::getCatProducts (category page listing)ecommercen/eshop/controllers/Adv_product_categories.php:293-318zero-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():

GroupModels/Keys Cleared
products13 product-related models (pricing, stock, attributes, variations, etc.)
searchsearch_model, lines_model
seometatags_model, seo_lib
cmscategories_model, subcontent_model
blogblog_category_model, blog_author_model, blog_tags_model, blog_model
slidersslideshow_group_model, sliders_model, slide_model
mapsmaps_model
promopromo_model
settingssettings, registry, registry_model, transporters_model, cookies_model
product_bundlesproduct_bundle_storage_model
cloudflareSpecial: calls clearCloudflareCache() (Cloudflare zone purge)
allFull 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 ​

ComponentPathRole
AdvClearSiteCacheecommercen/job/libraries/AdvClearSiteCache.phpJob: clears specific or all cache groups
AdvClearCacheOnLimitecommercen/job/libraries/AdvClearCacheOnLimit.phpJob: monitors file cache size, clears when over limit
JobClearCacheTraitecommercen/job/libraries/JobClearCacheTrait.phpShared trait providing clearCache() delegation
clearCache()ecommercen/helpers/pscache_helper.phpHelper: routes cache option to model-group clearing
clearPsCacheArray()ecommercen/helpers/pscache_helper.phpHelper: deletes all or specific cache groups via Pscache
clearCloudflareCache()ecommercen/helpers/pscache_helper.phpHelper: purges Cloudflare CDN cache via zone API
Pscacheapplication/libraries/Pscache.phpCache library wrapping PSR-6 CachePool
Client stubsapplication/modules/job/libraries/ClearSiteCache.php, ClearCacheOnLimit.phpEmpty extension points for client overrides

Code Flow ​

AdvClearSiteCache ​

  1. Entry: executeCommand(['cache' => $option]) where $option is an optional cache group name.
  2. Delegation: Calls $this->clearCache($option) via JobClearCacheTrait.
  3. Trait logic: If no option provided, defaults to 'all'.
  4. Helper dispatch: Calls global clearCache($option) from pscache_helper.php.
  5. Group resolution: A switch statement 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: calls clearCloudflareCache() directly (Cloudflare zone purge)
    • 'all' (default) -> Empty array, which triggers Pscache::delete_all()
  6. 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 ​

  1. Entry: executeCommand([]) -- no options.
  2. Adapter check: Reads cache_l2_adapter config. If not FileAdapter::class, logs info and returns (no-op for Redis).
  3. Size measurement: Executes du -s -k <cache_path> via shell exec() to get cache directory size in KB.
  4. Limit comparison: Compares measured size against getCacheSizeLimit() (config cache_l2_size_limit, in GB, converted to KB for comparison).
  5. Conditional clear: If size exceeds limit, calls $this->clearCache() (via trait -> full cache purge).
  6. 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 KeySourceDescription
cache_l2_adapterapplication/config/cache.phpAdapter FQCN (FileAdapter or RedisAdapter)
cache_l2_connectionapplication/config/cache.phpFile path or Redis connection string
cache_l2_size_limitapplication/config/cache.phpMax cache size in GB (default: 5)
cache_l2_default_expiresapplication/config/cache.phpDefault TTL in seconds (default: 86400)

Configuration ​

Environment Variables ​

VariableDefaultDescription
APP_CACHE_L2_ADAPTERFileAdapter::classCache adapter class
APP_CACHE_L2_CONNECTION../cache/Cache storage path
APP_CACHE_L2_SIZE_LIMIT5Size limit in GB (5 standard, 10 for dedicated)
APP_CACHE_L2_PREFIX''Cache key prefix

Job Options ​

JobOptionTypeRequiredDescription
AdvClearSiteCachecachestringNoCache 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 ClearSiteCache or ClearCacheOnLimit in application/modules/job/libraries/ extending the Adv* base class to add custom cache groups or logic.
  • Cache group mapping: The clearCache() helper in pscache_helper.php can be overridden in client repos by defining the function before the helper loads.
  • Cloudflare integration: Clients with Cloudflare can use the cloudflare cache option to purge CDN cache via the Cloudflare library.

Business Rules ​

  1. File adapter only: AdvClearCacheOnLimit is a no-op when cache_l2_adapter is not FileAdapter. It silently logs and returns.
  2. Default is full purge: When no cache group is specified, AdvClearSiteCache clears all cached data.
  3. Size limit in GB: The cache_l2_size_limit config is in GB. Default is 5 GB globally; dedicated clients may use 10 GB.
  4. Shell dependency: AdvClearCacheOnLimit depends on the du command being available in the system PATH.
  5. Language-scoped path: Cache path includes the language abbreviation suffix (e.g., ../cache/el/).
  6. Development mode: In development, all cache expiration is set to -1 (disabled), so these jobs have limited effect.
  7. Negative results are opt-in: a false / null from 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).
  8. 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 ​

  1. A cached negative outlives the creation of the thing it denies — since #666 a dead product URL's existsBySlug / findSlugsByUrl misses 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 the product_model group: the only clearCache('products') calls are in ecommercen/eshop/controllers/Adv_vats_admin.php:136-146, and Adv_products_admin.php makes no Pscache call; the one product-modifying path that clears it is the category admin's bulk discount update, which calls delete_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 daily ClearSiteCache job 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.)
  2. 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.
  3. 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 ​

TestCovers
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.phpadvmysqli_driver::$failedQueryCount: failed statements are counted and a later success does not reset the count
tests/Support/PscacheProbeClasses.phpGlobal probe model/library classes the Pscache tests attach (including a negative-returning model)

Gap: no test covers AdvClearSiteCache, AdvClearCacheOnLimit or the clearCache() group mapping.

Wiki Guide: Cache Guide -- cache adapter configuration and usage patterns