agentleFS
AnyOrgNameAnyOrgName/php-skills/skills/bitrix/cache-layers/SKILL.md

cache-layers

Skill4 starsChanged 4 months agoMITView on GitHub

Choose and use the right 1C-Bitrix caching layer — Managed Cache, the generic Cache/TaggedCache, HTML component (autocache), and $CACHE_MANAGER — with correct tagging, dependencies, and invalidation for enterprise workloads. Use when the user wants to cache an expensive query or computation in Bitrix and asks which layer to use (Cache, ManagedCache, or component autocache); the user wants to cache the rendered HTML of a Bitrix component and control its cache time, cache keys, or autocache behavior; the user needs to invalidate or clear Bitrix cache when underlying data changes — tagged-cache tags, `clearByTag`, or component cache clearing; the user wants cache entries tagged so they clear automatically when an iblock element or ORM entity changes (TaggedCache, `registerTag`, `startTagCache`). Keywords: bitrix, cache, performance, managed-cache, tagged-cache, autocache, invalidation, d7, legacy, битрикс, кеш.

The file

We split this skill into the rules it gives an agent

9 rules. About 0 are common, 5 are distinctive, and 4 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈5

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 4

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Do not use this skill for generic PHP caching (raw Redis, PSR-6/PSR-16, Laravel Cache).

    line 89
  2. Distinctive:

    Do not use this skill to store per-user session state or mutable application state.

    line 91
  3. Very specific:

    Verify: A warm cache returns the value from get() without recomputation.

    line 138
  4. Distinctive:

    Verify: The next request reads the value from cache instead of the DB.

    line 141
  5. Distinctive:

    Verify: Clearing managed cache invalidates the value with no bespoke logic.

    line 144
  6. Very specific:

    Verify: A second call with the same inputs returns cached data via getVars().

    line 161
  7. Very specific:

    Verify: The entry is associated with the iblock tag after endTagCache().

    line 165
  8. Distinctive:

    Verify: Editing an element clears only the tagged entries.

    line 168
  9. Very specific:

    Use \Bitrix\Main\Data\ManagedCache for values derived from the database that should be dropped whenever the kernel clears managed cache (e.g

    line 179

≈ “Common” is an estimate: at least 1 in 5 of the 350,495 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md
<!-- generated: do not edit — source: knowledge/atoms/bitrix/cache-layers/ --><!-- schema: atomVersion=3 skillVersion=2 graphVersion=1 --><!-- compile: @php-skills/compiler v1.0.0 (deterministic build) -->

Bitrix Cache Layers

When to use

  • The user wants to cache an expensive query or computation in Bitrix and asks which layer to use (Cache, ManagedCache, or component autocache).
  • The user wants to cache the rendered HTML of a Bitrix component and control its cache time, cache keys, or autocache behavior.
  • The user needs to invalidate or clear Bitrix cache when underlying data changes — tagged-cache tags, clearByTag, or component cache clearing.
  • The user wants cache entries tagged so they clear automatically when an iblock element or ORM entity changes (TaggedCache, registerTag, startTagCache).

When NOT to use

  • Do not use this skill for generic PHP caching (raw Redis, PSR-6/PSR-16, Laravel Cache); it is specific to Bitrix cache layers and their APIs.
  • Do not use this skill to store per-user session state or mutable application state; caches are for reproducible, recomputable data, not the source of truth.

Core guidance

  • Choose the cache layer by scope and invalidation need — Match the layer to the need: Data\Cache for arbitrary PHP data with TTL, Data\ManagedCache for kernel-managed cache tied to the DB, TaggedCache when entries must clear on entity changes, and component autocache for rendered HTML.
  • Prefer tagged invalidation over short TTLs for volatile data — When cached data depends on iblock elements or ORM entities, register tags (startTagCache + registerTag, or the ORM withTagCache path) and clear by tag on change instead of relying on a short TTL to expire it.

Decision Engine

Walk this section before choosing an implementation path.

What are you caching — rendered component HTML, or PHP data/query results?

├── PHP data / query: Must the entry clear automatically when a specific entity or iblock changes?

│   ├── TTL / kernel-managed clear: → managed — use ManagedCache for DB-derived kernel-cleared data, or Data\Cache with a TTL for simple recomputable values.

│   └── Needs entity-driven clear: → tagged — wrap Data\Cache with TaggedCache (startTagCache/registerTag) and clear by tag on entity change.

└── Rendered HTML: → autocache — cache the component output via component cache time and cache keys, and register tags for auto-clear.

Full engine: references/decision-engine.md — Decision Tree, Priority Matrix, Decision Table.

Workflows

Workflow: Managed Cache Value

Progress:
- [ ] Get `$mc = \Bitrix\Main\Application::getInstance()->getManagedCache();` and try
`if ($mc->read($ttl, $key)) { $value = $mc->get($key); }`
- [ ] On a miss, compute the DB-derived value, then `$mc->set($key, $value);` so the
kernel manages its lifetime
- [ ] Rely on the kernel's managed-cache clearing (admin "clear cache", option changes)
to invalidate the value, or call `$mc->clean($key)` explicitly when the source changes
  1. Get $mc = \Bitrix\Main\Application::getInstance()->getManagedCache(); and try if ($mc->read($ttl, $key)) { $value = $mc->get($key); }.
    • Verify: A warm cache returns the value from get() without recomputation.
  2. On a miss, compute the DB-derived value, then $mc->set($key, $value); so the kernel manages its lifetime.
    • Verify: The next request reads the value from cache instead of the DB.
  3. Rely on the kernel's managed-cache clearing (admin "clear cache", option changes) to invalidate the value, or call $mc->clean($key) explicitly when the source changes.
    • Verify: Clearing managed cache invalidates the value with no bespoke logic.

Workflow: Tagged Cache List

Progress:
- [ ] Get `$cache = \Bitrix\Main\Data\Cache::createInstance();` and call
`$cache->initCache($ttl, $uniqueId, $initDir)`, building `$uniqueId` from all inputs
- [ ] On a cache miss, open the tag cache with
`$tagged = \Bitrix\Main\Application::getInstance()->getTaggedCache();`,
call `$tagged->startTagCache($initDir)`, compute the data, then `registerTag('iblock_id_23')`
- [ ] Finish with `$tagged->endTagCache();` and `$cache->endDataCache($result);`, then in
the entity change handler call `$tagged->clearByTag('iblock_id_23')`
  1. Get $cache = \Bitrix\Main\Data\Cache::createInstance(); and call $cache->initCache($ttl, $uniqueId, $initDir), building $uniqueId from all inputs.
    • Verify: A second call with the same inputs returns cached data via getVars().
  2. On a cache miss, open the tag cache with $tagged = \Bitrix\Main\Application::getInstance()->getTaggedCache();, call $tagged->startTagCache($initDir), compute the data, then registerTag('iblock_id_23').
    • Verify: The entry is associated with the iblock tag after endTagCache().
  3. Finish with $tagged->endTagCache(); and $cache->endDataCache($result);, then in the entity change handler call $tagged->clearByTag('iblock_id_23').
    • Verify: Editing an element clears only the tagged entries; unrelated caches keep hits.

Best practices

  • Register the narrowest tags that reflect real dependencies (e.g
  • Derive the cache id from all inputs that change the result and place entries in a descriptive initDir (cache path) so unrelated caches never collide or clear each other
  • Reach for the D7 Data\Cache/ManagedCache classes in new code and keep the legacy global $CACHE_MANAGER (and $GLOBALS['CACHE_MANAGER']) only when editing existing legacy cache logic
  • Use \Bitrix\Main\Data\ManagedCache for values derived from the database that should be dropped whenever the kernel clears managed cache (e.g

Anti-patterns

Anti-patternWhy it failsDo instead
Using the cache as primary storageCaches are evicted and cleared routinely, so anything not recomputable is lost.Keep the source of truth in the DB or a durable store and cache only a derived,<br>recomputable projection of it.
Caching per-user data under a shared keyOne user's cached data then leaks to other users, a correctness and privacy bug.Either exclude per-user data from the cache or include the user group/context in the<br>cache id so entries never cross users.
Clearing the whole cache to fix stalenessFlushing everything throws away valid caches and moves full load back onto the DB.Register tags for the changed entity and clear by tag, so only the affected entries drop.

See references/anti-patterns.md.

Debugging

  1. A site-wide tag destroys the cache hit rate — Broad tags couple unrelated caches, turning small edits into mass invalidations. Fix: Register the narrowest tag that reflects the real dependency (a single element or section id) so edits clear only what actually changed.
  2. Empty or error result gets cached — The cache does not know the result was invalid; it stores whatever was produced. Fix: On error or empty branches call abortDataCache() (component: AbortResultCache) so the bad result is never persisted.
  3. Incomplete cache key serves the wrong result — The cache keys on the id alone, so two logically different results collide. Fix: Build the id from every input that affects the output and namespace entries under a descriptive initDir so unrelated caches never share a key.
  4. Cached data goes stale because no tag was registered — Without a tag, nothing links the entry to the entity, so clearByTag never touches it. Fix: Wrap the read in TaggedCache, registerTag for the entity/iblock, and clear by that tag from the change handler.

Performance notes

  • A site-wide tag destroys the cache hit rate — Tagging many caches with one broad tag (e.g. a whole iblock or the whole site) means any single edit flushes them all, so the hit rate collapses and DB load spikes.
  • Scope tags narrowly to protect hit rate — Register the narrowest tags that reflect real dependencies (e.g. a single iblock id) rather than a broad site-wide tag, so one edit does not flush unrelated caches.
  • Prefer tagged invalidation over short TTLs for volatile data — When cached data depends on iblock elements or ORM entities, register tags (startTagCache + registerTag, or the ORM withTagCache path) and clear by tag on change instead of relying on a short TTL to expire it.

Production checklist

  • Error or empty-result branches call abortDataCache() (or the component AbortResultCache) so failures and empty datasets are never cached.
  • Tags are as narrow as the real dependency (single iblock/entity), and no site-wide tag is used that would flush unrelated caches on every edit.
  • The cache id/key is derived from every input that changes the result (params, language, user group where relevant) so no two distinct results share a key.
  • Cached data is always recomputable from the DB, and no code treats a cache entry as authoritative state that would be lost on eviction or clearing.
  • Every cache whose data depends on entities registers the matching tags and is cleared by tag on change, so no stale data survives an edit.

Version notes

  • Cache backend is configured in .settings.php — On modern cores the cache backend (files, Memcached, Redis) is selected in .settings.php under the cache service, so the same Data\Cache code runs on any backend without changes.
  • D7 cache classes supersede the legacy facade — The D7 \Bitrix\Main\Data\Cache, ManagedCache, and TaggedCache classes are the current API; the global $CACHE_MANAGER remains as a legacy facade over the same managed cache for older code.

Security

  • Never cache per-user data under a shared key — Keep user-specific data (basket, personal price, permissions, session-derived values) out of shared cache keys; if it must be cached, include the user group or identity in the cache id so one user's data cannot be served to another.

Testing

  • Activation and decision behavior are verified in eval/scenarios/bitrix/cache-layers.yaml.

Additional resources

  • references/anti-patterns.md
  • references/core.md
  • references/decision-engine.md
  • references/examples.md
  • references/pitfalls.md
  • references/recipes.md
  • references/version-differences.md

Knowledge graph

Prerequisites: bitrix/kernel-main-module
Related: audit/bitrix, bitrix/component-engine, bitrix/d7-orm-queries, bitrix/iblock-elements, bitrix/kernel-main-module
Behavior constraints: ai-rules/strategy-legacy-safe-edits

<!-- graph-fragment: graph/fragments/bitrix/cache-layers.yaml -->

Skill contract

Produces: cache.bitrix-configured
Requires: bitrix.kernel-bootstrapped
Risk: medium · Confidence: 0.9

<!-- contract-fragment: contracts/fragments/bitrix/cache-layers.yaml -->

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.