Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 28 ยท Quality

Caching and Performance

Make a Salesforce B2C Commerce storefront fast: page cache, iscache, remote includes, custom caches, CDN, cache keys, personalization and profiling.

On B2C Commerce, caching is the performance strategy. A request that reaches your controller, queries the catalog, runs scripts and renders ISML is expensive; a request answered from the page cache costs almost nothing. A well-built storefront serves the vast majority of its anonymous traffic (category pages, product pages, content pages) from cache and spends its server time on the pages that must be personal: cart, checkout and account. Most "SFCC is slow" stories end with someone discovering that a page was not cacheable, or was cached with the wrong key.

This lesson covers the layers (CDN, page cache, remote includes, custom caches), how a cache key is formed, how to keep pages cacheable while still showing personal data, how to find slow code, and the patterns that most often hurt. The real configuration is read-only here because it needs an instance. The TryIt blocks are stand-ins that model the ideas with a clock you control, so you can see hits, misses and expiry deterministically.

The layers

flowchart LR
    S["Shopper"] --> C["CDN and WAF"]
    C --> P["Page cache"]
    P -->|"miss"| A["Application server<br/>controller, models, ISML"]
    A --> I["Remote includes<br/>(own cache entries)"]
    A --> K["Custom caches<br/>(script data)"]
    A --> D["Database and services"]

A request is answered by the first layer that has a valid copy; only a miss goes deeper.

  • The CDN sits in front of the platform (B2C Commerce includes an embedded CDN with web application firewall features). It serves static files and can cache and filter pages.
  • The page cache stores rendered pages and fragments on the platform and answers requests without running your controller.
  • Remote includes let a page be assembled from pieces with different cache lifetimes.
  • Custom caches store data computed by your scripts (not HTML) inside the application tier.

Making a page cacheable

A response is stored in the page cache only if it says so. In ISML you declare it with iscache:

HTML
<iscache type="relative" hour="24"/>

type="relative" means "keep it for 24 hours from now"; type="daily" means "until this time of day" (<iscache type="daily" hour="3"/>). status="off" explicitly disables caching for a template. Pages that show prices or availability can be told which data they depend on with varyby, so the entry is refreshed when promotions or stock change:

HTML
<iscache type="relative" hour="24" varyby="price_promotion"/>

In SFRA you usually do not write the tag in the template. A middleware sets properties on the response and the server module turns them into the right cache headers:

JavaScript
'use strict';

var server = require('server');
var cache = require('*/cartridge/scripts/middleware/cache');

server.get('Show', cache.applyPromotionSensitiveCache, function (req, res, next) {
    res.render('product/productDetails', { product: /* ... */ null });
    next();
});

module.exports = server.exports();

The base cartridge ships several of these (a default cache, and variants for promotion-sensitive or inventory-sensitive pages). Setting res.cachePeriod and res.cachePeriodUnit yourself is also possible. See Controllers, Routes and Middleware for how middleware runs.

The cache key

A page cache entry is found by its URL, including the query string, plus any varyby dimensions. Two consequences matter every week:

  1. /shoes?utm_source=news and /shoes?utm_source=ads are different entries. Tracking parameters fragment the cache and lower the hit rate. Strip them at the edge or avoid generating such links internally.
  2. Anything that changes the output of a page but is not in the key (the customer's name, a cookie, a session value) will be cached for the first visitor and shown to everyone. A cached page must be identical for every shopper who requests that key.
JS Stand-in: a TTL cache with a controllable clock

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Five requests caused three renders: the entry was reused until it expired and again rebuilt after invalidation. In production the equivalent of invalidate is a cache invalidation in Business Manager (or through automation), and you pay for it with a burst of misses, so avoid invalidating more than you must.

Personalization without losing the cache

Product pages need a mini cart, a "Hello, Anna" greeting and a login link. If you print them directly in the page, the page cannot be shared. There are two standard answers.

Remote includes. The cached shell contains a placeholder, and the platform requests the fragment separately with its own cache setting:

HTML
<isinclude url="${URLUtils.url('Cart-MiniCart')}"/>

The fragment's template says <iscache status="off"/> (or the route sets res.personalized), so it is never shared, while the big page around it is. A remote include is a new request: it does not share pdict with the including page, so pass what it needs in the URL, and remember that each include costs a request (a category page with 24 includes, one per tile, is a classic problem).

Client-side loading. The page ships static HTML and a small script fetches the personal parts. This is the same approach this site uses for progress data, and it is how headless storefronts work (see Headless Storefronts with PWA Kit).

JS Stand-in: a cached shell with an uncached personal fragment

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Anna and Ben see their own greeting, but the shell was rendered only once for /shoes. The third request used a different query string, so it rendered a second shell: this is the tracking-parameter fragmentation from above, visible in the log.

Custom caches

Sometimes the expensive part is not HTML but data: a list of stores, a tax table fetched from a service, the result of a heavy calculation. A custom cache keeps such values in memory on the application server. You declare the cache in a JSON file referenced from package.json, then use CacheMgr:

JSON
{
  "caches": [
    { "id": "storeLookup", "maxEntries": 500, "expireAfterSeconds": 3600 }
  ]
}
JavaScript
'use strict';

var CacheMgr = require('dw/system/CacheMgr');

function getStoresNear(postalCode) {
    var cache = CacheMgr.getCache('storeLookup');
    return cache.get('stores_' + postalCode, function loader() {
        return loadStoresFromService(postalCode); // runs only on a miss
    });
}

Rules of thumb: a custom cache is per application server (entries are not shared between servers and are lost on restarts or code activation), so it must be safe to lose and safe to hold slightly stale; never put customer-specific data in it unless the key includes the customer; keep entries small; give every cache an expiry.

Finding the slow part

Do not guess. Measure.

  • The Storefront Toolkit (on non-production instances) shows, among other things, cache information for the current page: whether it was cacheable and for how long.
  • The Code Profiler in Business Manager records where script time is spent (which scripts and API calls dominate), and request logs show slow requests and quota problems.
  • Add your own timing logs around calls you suspect, using the logging practices from Testing, Debugging and Logging.

Patterns that hurt

  • Loops that load full objects. Calling the product API or building a full product model for every tile; use lighter models and search hits, and page the results.
  • Many remote includes per page, each a separate request.
  • Disabling the cache "for now" on a template (or setting personalized) and leaving it that way.
  • Cache keys polluted by tracking parameters, random numbers or timestamps.
  • Synchronous service calls in the render path of a cacheable page (see Service Framework and Third-Party Integrations): one slow third party now slows every cache miss.
  • Unbounded queries such as custom object searches without limits or indexes.
JS Stand-in: counting work in a per-item loop versus a batch

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The platform has its own limits and quotas for script API calls per request, so a loop that merely feels slow on one request can also hit a quota under load. Always ask "how many calls does this make for a page of 24 products?"

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why do /shoes?utm_source=news and /shoes?utm_source=ads hurt the page cache?

    The page cache key includes the query string. Tracking parameters create duplicate entries and lower the hit rate, so strip or avoid them.
  2. 2. How do you show a personal mini cart on an otherwise cached page?

    The shell stays shared and cached; the personal fragment is requested separately and is not shared. Printing personal data into a cached page would show it to other shoppers.
  3. 3. Which statement about custom caches is correct?

    Custom caches live in the memory of each application server and are not a database. Give them expiry and treat a miss as normal.
  4. 4. Where should you start when a page is slow?

    Guessing leads to wrong fixes. Profilers and logs show which script or call dominates and whether the page was cacheable.

Summary

  • Caching is the main performance tool: CDN, page cache, remote includes and custom caches each answer some requests before they reach your code.
  • Cache pages with iscache or the SFRA cache middleware; the key is the URL plus varyby settings, so tracking parameters fragment the cache.
  • A cached page must be identical for everyone; put personal parts in uncached remote includes or load them with JavaScript.
  • Custom caches are per server, in memory and expendable: always give them an expiry.
  • Measure with the Storefront Toolkit, Code Profiler and logs, then fix per-item loops, too many includes and slow service calls in the render path.
  • The TryIt blocks are stand-ins that model keys, TTL and personalization; the real cache is managed by the platform.

Next: Testing, Debugging and Logging