Custom caches for expensive script results
Key Takeaway
Populate a custom cache with get(key, loader), and make sure the loader returns a value the cache can store. A cache can't store undefined, so a loader that returns undefined leaves no entry and runs again on every call.
A custom cache is a small in-memory store on each B2C Commerce application server. Script code uses it to keep results that are expensive to calculate, slow to retrieve, or needed very often, so the work isn't repeated on every request. You define custom caches in a JSON file in a cartridge. You then read and write entries with the dw.system.CacheMgr and dw.system.Cache script API classes.
When to use a custom cache
Custom caches sit at the application server layer. They are most useful on endpoints that must stay dynamic, such as pages or remote includes that show consumer or cart data. Page caching can't be applied to those endpoints, but expensive work still happens there.
Good candidates fall into three groups:
- Calculations that are expensive and whose result can change, so the result can't be stored permanently.
- Responses from external systems, such as in-store availability and prices. Caching them for a period of time cuts the number of calls and reduces page load time.
- Operations that are cheap but run very often, such as building configuration in a configuration-as-code setup.
A base product shows an On Sale banner if any of its variation products is in a promotion. Checking every variation product each time the base product is displayed is costly. The result can change, so you can't store it permanently. Instead, you calculate the result once and cache it for a few minutes.
In a configuration-as-code setup, reading a JSON file and merging brand- and country-specific overrides isn't expensive by itself. The trouble is frequency, because the work runs on every request and every remote include. Caching the result for each brand and country combination avoids that repeated work.