Elastic Path Commerce Development

Cortex Caching

Cortex Caching

Cortex can cache domain objects it retrieves from Elastic Path Commerce Engine to improve performance on requests which retrieve the same domain object multiple times. Cortex uses a technique called request-scoped caching to do this.

Domain Objects and Caching

Domain objects are classes that represent a unique set of data. Typically in Cortex, domain objects are carts, shoppers, products, and so on.

Domain objects are used in nearly all Cortex operations: getting products, logging in customers, adding to cart, and so on. Most domain objects are stored within, or require calls to Commerce Engine's database, which makes retrieval of these objects expensive operations. Multiple retrievals of the same domain objects within a single Cortex request, without proper caching, can lead to a significant decrease in performance.

How Domain Objects are Cached

Domain objects are cached at the repository level when a repository method retrieves them. Repository methods are annotated with @CacheResultand @CacheRemove annotations which cache an object and evict an object from the cache as needed. Additionally, cache key variants allow for the same cached object to be retrieved by different repository methods using a different key.

Best Practices: When to Cache

When to Cache

Caching should be used only when needed, as caching all methods within a repository leads to cache pollution and duplicate entries.

In general, cache a method response in the following situations:

  • If the method calls Commerce Engine services: Any methods that call down to Commerce Engine to retrieve a domain object should be cached, as this typically requires calling down into the database and is thus an expensive call.
  • If the method calls external services: Calls to external services can be slow and have an actual monetary cost, so caching the response saves processing time and often money.
  • If multiple methods require the same domain object: Occasionally, a repository has multiple methods which call down to Commerce Engine for the same object. Rather than caching each method's response, extract the service calls to a single helper method and cache the response of the helper method.

Methods that call to other repository methods or that extract information from domain objects do not need to be cached.

Caches as Immutable Objects

Modifying cached values is a bad practice that can lead to inconsistencies. Either use immutable types as values, which is the preferred way, or treat cached values as if they were immutable and create new objects on mutation.