MSBA-343 · Lesson 5 of 12 · 20 min
Caching
▶ Video coming soon A video version of this lesson is on the way.
The fastest database call is the one that never happens. After the set-based clinic, Prudence went back to the receipt trace and counted the calls that remained. Most of them read the same few records again and again: the inspection parameters for the company, the purchase order header, the item's inspection category. None of those changed while a receipt was being posted. Desmond said that was the signature of a caching problem, and spent the session on the places finance and operations apps can keep data close to the code that needs it.
Why cache, and what it costs
A cache keeps a copy of data that has been read, so that the next request can be answered without going back to the source. Caching trades memory and the risk of stale data for speed. The trade is excellent for data that is read often and changes rarely, such as parameters, setup tables and reference lists. It is poor for data that changes often or must always be current, such as inventory on hand or the status of a queue. Every caching decision in this lesson comes back to those two questions: how often is it read, and how bad is it to read an old copy?
Finance and operations apps cache at several levels. Desmond listed them from the closest to the database to the closest to the user.
Table caching
Every table has a CacheLookup property that tells the application server how to cache records read from it. The values are None, NotInTTS, Found, FoundAndEmpty and EntireTable. None turns caching off, which suits tables that change constantly. Found caches a record once it has been found, and later selects for the same record are answered from the cache. FoundAndEmpty also caches the fact that a record was not found, which helps when code repeatedly checks for something that does not exist. NotInTTS behaves like Found outside transactions but always reads from the database inside a transaction, so code that updates records sees current data. EntireTable loads the whole table into the cache the first time any record is read, which suits small tables that hardly ever change.
| CacheLookup value | Behaviour | Good fit at Cobalt Ridge |
|---|---|---|
| None | No caching | CRInspAlertQueue, which changes every few minutes |
| NotInTTS | Cached outside transactions; read fresh inside them | CRPumpWarrantyTable, read often and updated inside transactions |
| Found | Cache records once found | Main tables such as a category table read by key |
| FoundAndEmpty | Also cache that a record was not found | Lookups that often find nothing, such as optional overrides |
| EntireTable | Load the whole table on first read | CRInspectionParameters, one row per company |
Record caching only works for certain selects. A select is answered from the record cache when it looks up a record by all the fields of a unique index, typically the primary key, with equality conditions, and without joins. A select that filters on other fields, uses ranges, or joins to another table goes to the database. That is why tables have find methods that select by the primary key: they are the selects the cache can answer. When Prudence checked the receipt rule, she found that it read the inspection parameters with a select on the company field and a second condition on an enabled flag. The second condition defeated the cache. She replaced it with the table's find method and checked the flag in X++.
EntireTable caching needs care. It is meant for small tables; for a large table it wastes memory and can make the first read slow. A change to any record invalidates the cached table, so it is wrong for tables that change during the day. The inspection parameters table had one row per company and changed perhaps once a year, which made it a textbook case.
Desmond added a warning about consistency across servers. Production runs several application server instances, and each keeps its own cache. When a record changes, the change is made in the database and caches are refreshed, but there can be a short delay before every instance sees it. For parameters this is harmless. For anything where two servers must agree instantly, caching is the wrong tool.
The global object cache
Some data is not a table record: the result of an expensive calculation, a lookup structure built from several tables, or a set of rules parsed from configuration. For these, X++ offers SysGlobalObjectCache, often shortened to SGOC. It is a key and value store shared by all sessions on one application server instance. Code stores a value under a scope and key, and later code anywhere on the same instance can find it. Values are containers, so objects must be packed into containers to be stored.
Prudence used the global object cache for the inspection category rules. Building the map from item groups to inspection categories required reading three setup tables and walking a hierarchy, and the receipt rule needed it for every line. She built it once per instance and stored it in the cache under a scope named after the class. When the setup changed, the setup form's write method cleared the scope so the next request would rebuild it.
public static container categoryMap()
{
SysGlobalObjectCache sgoc = classFactory.globalObjectCache();
str scope = classStr(CRInspectionCategoryMap);
container key = [curExt()];
container map = sgoc.find(scope, key);
if (map == conNull())
{
map = CRInspectionCategoryMap::buildMap(); // reads setup tables
sgoc.insert(scope, key, map);
}
return map;
}
// Called from the setup form after a change
public static void clearCache()
{
classFactory.globalObjectCache().clear(classStr(CRInspectionCategoryMap));
}The key included the current company. Prudence's first version had used a fixed key, and in testing a CRUS user received CRCA's map. Desmond called it the classic global cache bug: anything that differs by company, user or language must be part of the key.
Singletons
The global object cache also supports the singleton pattern, where a class guarantees that only one instance exists and every caller gets that instance. In X++, a singleton for the lifetime of a session is often built with the session cache, SysGlobalCache, reached through appl.globalCache() on the server. A singleton for the whole server instance is built with the global object cache. The MB-500 outline names both global cache and singleton, and the distinction it tests is scope: session cache values belong to one user's session and disappear with it; global object cache values are shared across sessions on one instance.
Prudence used a session singleton for the telemetry helper in lesson 11, which held settings that the user's session read many times. She used no singletons for anything that held data, preferring the explicit cache with a clear method.
| Cache | Scope | Typical use | Watch out for |
|---|---|---|---|
| Table record cache (CacheLookup) | All sessions on an instance, per record or table | Parameters, setup, main data read by key | Only key lookups are cached |
| SysGlobalObjectCache | All sessions on one instance | Expensive computed structures | Include company and other context in the key; clear on change |
| SysGlobalCache | One user session | Session singletons and per-session settings | Disappears when the session ends |
| Display method cache | One form | Display methods shown on grids | Values refresh only when the record does |
Display methods and forms
The performance timer in lesson 3 had shown dozens of server calls while scrolling the warranty list. The list showed two display methods, one for the customer's name and one for the number of days remaining on the warranty. Without caching, each display method runs on the server for every visible row each time the form refreshes. With caching, the form calculates the value once when the record is read and keeps it with the record.
There are two ways to cache a display method. The older one is to call cacheAddMethod on the form data source in its init method, naming each display method. The newer one is to decorate the display method with the SysClientCacheDataMethod attribute, which tells the form to cache it whenever it appears. Prudence used the attribute on both methods, and the scrolling calls disappeared from the timer. She checked one behaviour: a cached display method is refreshed only when the record is reread, so the days remaining would not tick down while a user left the form open overnight. Nobody minded.
[SysClientCacheDataMethodAttribute(true)]
public display CRWarrantyDaysRemaining daysRemaining()
{
return max(0, this.EndDate - DateTimeUtil::getSystemDate(DateTimeUtil::getUserPreferredTimeZone()));
}Forms also benefit from sensible data source design: no more data sources than the form shows, joins instead of separate data sources linked by code, and field lists where the pattern allows them. Desmond reviewed the warranty form with Prudence and removed a data source that had been added for a field that was later dropped from the design. It had been joining InventTable on every row for nothing.
Keeping the client responsive
Not every slow operation can be made fast. Some work, such as recalculating warranties for a large customer, takes as long as it takes. What a developer can control is whether the user's browser freezes while it runs. The MB-500 outline names two frameworks for this: the asynchronous framework and the sandbox framework.
The asynchronous pattern lets a form start a server method and carry on, with a callback method on the form that runs when the work finishes. The user can keep working on the form, and the callback updates it with the result. Desmond used it for the warranty form's Check coverage button, which called a slow external service through the integration in MSBA-342. The button started the call asynchronously and the callback filled in a coverage field when the answer arrived.
The sandbox framework, SysOperationSandbox, runs a static method in a separate session while the client shows a progress indicator and lets the user cancel. It suits operations of a few seconds to a few minutes that the user must wait for but should not freeze the browser, such as recalculating all warranties on one sales order. For anything longer, the right answer is a batch job, which the user starts and forgets. Desmond's rule of thumb was: instant, run it directly; seconds to a minute or two that the user must see the result of, use the sandbox or async patterns; longer than that, batch.
// Run a recalculation in a separate session while the client shows progress
SysOperationSandbox::callStaticMethod(
classNum(CRPumpWarrantyService),
staticMethodStr(CRPumpWarrantyService, recalculateForSalesOrder),
[salesTable.SalesId],
"@CRCustom:RecalculatingWarranties");Caching and correctness
Desmond ended the session where he had started it, with the risk side of the trade. A cache that returns stale data is a bug, and caching bugs are hard to find because they depend on timing, server instance and what was read first. His checklist for any new cache had four lines: what is the scope; what is in the key; what clears it; and what happens if a user reads an old value. If any answer was vague, the cache waited.
Prudence applied the checklist to her changes and reran the receipt trace. The repeated parameter reads were gone, the category map was built once and the purchase order header was read once per receipt. The trace was not yet as fast as Kiri wanted, but the remaining cost was now in standard posting, which was where it belonged.
Testing a cache
Caches need tests of their own, because a cache that hides a change is invisible in normal use. Prudence wrote three for the category map. The first built the map twice in the same company and checked that the second call did not read the setup tables, by counting calls through a small test hook. The second changed the setup, called the clear method and checked that the next call returned the new value. The third switched company and checked that the map differed. Desmond added a fourth line to her checklist: run the receipt test after clearing all caches, because code must also be correct when the cache is cold, which is how every server instance starts after a deployment.
She also measured the benefit. In the receipt trace, the category map had cost about eleven seconds across 312 lines. With the cache, the first line paid for building the map and the rest read it, and the cost fell to well under a second. Measurements like this went into the pull request, so the reviewer could see that the cache was worth the complexity it added.
Worked problem
Choosing a cache for the category map
The receipt rule calls a method that builds a map from item groups to inspection categories by reading three setup tables. It runs once per line on every receipt. Setup changes a few times a year. How should Prudence cache it?
Show solution
- Note that the result is computed from several tables, so table caching alone cannot answer it.
- Choose SysGlobalObjectCache, because the map can be shared by every session on the instance.
- Use a scope named after the class and a key that includes the company, because each legal entity has its own setup.
- Clear the scope from the setup form whenever the setup changes.
- Trace the receipt again to confirm that the map is built once and then read from the cache.
Answer: A global object cache entry keyed by company, cleared on setup changes, turns hundreds of setup reads per receipt into one build per company per instance.
Common mistakes
MistakeExpecting a select with extra conditions to be answered from the record cache.
InsteadOnly key lookups on unique indexes are cached; use find methods.
MistakeUsing EntireTable caching on a large or frequently changed table.
InsteadKeep EntireTable for small, rarely changed setup tables.
MistakeLeaving the company out of a global cache key.
InsteadInclude every piece of context that changes the value.
MistakeFreezing the browser for a two-minute operation.
InsteadUse the sandbox or asynchronous patterns, or a batch job for longer work.
Summary and key terms
- Caching trades memory and staleness risk for speed and suits data that is read often and changes rarely.
- The CacheLookup property controls table caching; record caching works only for unique key lookups.
- SysGlobalObjectCache shares values across sessions on one instance; SysGlobalCache holds values for one session.
- Display methods can be cached with SysClientCacheDataMethod or cacheAddMethod to cut server calls on grids.
- The asynchronous and sandbox frameworks keep the client responsive; longer work belongs in batch.
- CacheLookup
- A table property that sets how records read from the table are cached.
- EntireTable cache
- A setting that loads a whole small table into the cache on first read.
- SysGlobalObjectCache
- A key and value cache shared by all sessions on one server instance.
- Singleton
- A pattern in which only one instance of a class exists for a given scope.
- SysOperationSandbox
- A framework that runs a static method in a separate session while the client shows progress.
Practice problems
Work each problem on paper first, then reveal the answer to check.
Which CacheLookup value reads from the database inside transactions?
Show answer
NotInTTS.
What must be included in a global cache key when values differ by legal entity?
Show answer
The company, for example from curExt().
Which attribute caches a display method on forms?
Show answer
SysClientCacheDataMethodAttribute.
Lesson quiz · 5 questions
Score 60% or more to complete this lesson.
Create a free account to save your progress, take quizzes and earn a certificate.