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, битрикс, кеш.
In this repository119 other files it gives its agents.
- strategy-bitrix-d7-incrementalSkill
- strategy-explicit-over-magicSkill
- strategy-framework-conventionsSkill
- strategy-legacy-safe-editsSkill
- strategy-minimal-diffSkill
- strategy-no-untested-refactorSkill
- strategy-preserve-public-apiSkill
- strategy-readonly-immutabilitySkill
- strategy-security-firstSkill
- strategy-test-drivenSkill
- openapiSkill
- paginationSkill
- rest-designSkill
- versioningSkill
- cqrsSkill
- dependency-inversionSkill
- hexagonalSkill
- repository-patternSkill
- service-layerSkill
- bitrixSkill
- findings-reportSkill
- laravelSkill
- performanceSkill
- phpSkill
- project-analysisSkill
- refactoringSkill
- roi-prioritizationSkill
- securitySkill
- stack-detectionSkill
- component-engineSkill
- d7-eventsSkill
- d7-loaderSkill
- d7-orm-queriesSkill
- iblock-elementsSkill
- kernel-main-moduleSkill
- localizationSkill
- controllersSkill
- ormSkill
- validationSkill
- controllersSkill
- query-builderSkill
- routingSkill
- autoload-psr4Skill
- dependency-managementSkill
- scriptsSkill
- connection-poolingSkill
- mysql-indexingSkill
- redisSkill
- transactionsSkill
- ci-github-actionsSkill
- deployment-strategiesSkill
- docker-phpSkill
- env-configSkill
- associationsSkill
- entities-mappingSkill
- orm-basicsSkill
- entity-apiSkill
- module-developmentSkill
- routing-controllersSkill
- formsSkill
- The first 60 shown.
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
- Distinctive: line 89
Do not use this skill for generic PHP caching (raw Redis, PSR-6/PSR-16, Laravel Cache).
- Distinctive: line 91
Do not use this skill to store per-user session state or mutable application state.
- Very specific: line 138
Verify: A warm cache returns the value from get() without recomputation.
- Distinctive: line 141
Verify: The next request reads the value from cache instead of the DB.
- Distinctive: line 144
Verify: Clearing managed cache invalidates the value with no bespoke logic.
- Very specific: line 161
Verify: A second call with the same inputs returns cached data via getVars().
- Very specific: line 165
Verify: The entry is associated with the iblock tag after endTagCache().
- Distinctive: line 168
Verify: Editing an element clears only the tagged entries.
- Very specific: line 179
Use \Bitrix\Main\Data\ManagedCache for values derived from the database that should be dropped whenever the kernel clears managed cache (e.g
≈ “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.
Files
<!-- 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\Cachefor arbitrary PHP data with TTL,Data\ManagedCachefor kernel-managed cache tied to the DB,TaggedCachewhen 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 ORMwithTagCachepath) 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- Get
$mc = \Bitrix\Main\Application::getInstance()->getManagedCache();and tryif ($mc->read($ttl, $key)) { $value = $mc->get($key); }.- Verify: A warm cache returns the value from
get()without recomputation.
- Verify: A warm cache returns the value from
- 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.
- 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')`- Get
$cache = \Bitrix\Main\Data\Cache::createInstance();and call$cache->initCache($ttl, $uniqueId, $initDir), building$uniqueIdfrom all inputs.- Verify: A second call with the same inputs returns cached data via
getVars().
- Verify: A second call with the same inputs returns cached data via
- On a cache miss, open the tag cache with
$tagged = \Bitrix\Main\Application::getInstance()->getTaggedCache();, call$tagged->startTagCache($initDir), compute the data, thenregisterTag('iblock_id_23').- Verify: The entry is associated with the iblock tag after
endTagCache().
- Verify: The entry is associated with the iblock tag after
- 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/ManagedCacheclasses 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\ManagedCachefor values derived from the database that should be dropped whenever the kernel clears managed cache (e.g
Anti-patterns
| Anti-pattern | Why it fails | Do instead |
| Using the cache as primary storage | Caches 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 key | One 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 staleness | Flushing 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
- 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.
- 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. - 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.
- Cached data goes stale because no tag was registered — Without a tag, nothing links the entry to the entity, so
clearByTagnever touches it. Fix: Wrap the read in TaggedCache,registerTagfor 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 ORMwithTagCachepath) 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 componentAbortResultCache) 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.phpunder thecacheservice, 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, andTaggedCacheclasses are the current API; the global$CACHE_MANAGERremains 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 -->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
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.

