Sub topic 9
What cacheable=true means and when you can use it
This chapter assumes you can write a basic @AuraEnabled method and import it into a Lightning Web Component. You should also know the difference between a wire call and an imperative call. Here we look at what the cacheable option changes, what it forbids, and how it affects imperative calls.
What the option does
@AuraEnabled(cacheable=true) tells the platform that a method only reads data. In return, the platform lets the client store the method's result and reuse it for later calls with the same parameters.
The option has three effects:
- The method becomes eligible for the wire service. A method must be cacheable to be used with
@wire. - The method may not change data. The platform rejects DML in a cacheable method, and it also rejects other operations that change state.
- The client may answer a call from its cache instead of making a server round trip.
The cache lives in the browser session, not on the server. It is separate from Platform Cache. Each user's client holds its own copy.
public with sharing class ContactController {
@AuraEnabled(cacheable=true)
public static List<Contact> searchContacts(String searchTerm) {
String key = '%' + searchTerm + '%';
return [
SELECT Id, Name, Email
FROM Contact
WHERE Name LIKE :key
WITH USER_MODE
ORDER BY Name
LIMIT 20
];
}
@AuraEnabled
public static void updateEmail(Id contactId, String email) {
try {
Contact c = new Contact(Id = contactId, Email = email);
update as user c;
} catch (DmlException e) {
throw new AuraHandledException(e.getDmlMessage(0));
}
}
}searchContacts only queries, so it can be cacheable. updateEmail performs an update, so it must not be. Both classes and methods run with with sharing and user-mode access. The cache does not change that, because the first call is still evaluated for the current user.
The constraints
A cacheable method must be a static method that is public or global. It must not perform DML, and it must not call out in ways that change state. If you add insert, update, delete, or upsert to a cacheable method, the call fails at runtime with an error about DML not being allowed. The failure shows up when the component calls the method, not when you save the class, so test the call path after any edit.
Some practical consequences:
- You cannot make a method cacheable and also have it write an audit record, a log row, or a "last viewed" timestamp. Move that work into a separate non-cacheable method.
- Apex does not allow overloaded
@AuraEnabledmethods. Do not try to expose a cacheable and a non-cacheable variant under one name. Give them different names, such asgetContactsandsaveContacts. - The method should return the same result for the same inputs during the cache lifetime. A method that returns
Datetime.now()or a random value gives surprising output once cached.
What gets cached
The cache key is made from the method and its parameter values. searchContacts({ searchTerm: 'ada' }) and searchContacts({ searchTerm: 'bob' }) are cached as separate entries. A repeat of the first call can be served from the cache, so the server does not run the SOQL again.
This is the main benefit. A cached answer avoids a network round trip, avoids using server time, and makes the UI feel instant. For lookup data that rarely changes, such as picklist-like reference lists or a user's own settings, it is a clear win.
It is also the main risk. A cached answer can be out of date. If another user, a trigger, a flow, or your own code changes the records after the result was cached, the component can keep showing the old values.
Cacheable methods called imperatively
You can call a cacheable method imperatively. The import and call look the same as for a non-cacheable method:
import { LightningElement } from 'lwc';
import searchContacts from '@salesforce/apex/ContactController.searchContacts';
export default class ContactSearch extends LightningElement {
searchTerm = '';
contacts = [];
errorMessage;
isLoading = false;
handleTermChange(event) {
this.searchTerm = event.target.value;
}
async handleSearch() {
this.isLoading = true;
this.errorMessage = undefined;
try {
this.contacts = await searchContacts({ searchTerm: this.searchTerm });
} catch (error) {
this.contacts = [];
this.errorMessage = error?.body?.message || error?.message || 'Unknown error';
} finally {
this.isLoading = false;
}
}
}Because searchContacts is cacheable, a second click with the same term may return the stored result instead of querying again. For a search box this is often fine and even helpful. For a screen that must show the current state right after a save, it is a bug waiting to happen.
Treat the returned data as possibly shared and read-only. Results from cacheable methods can be frozen by the framework, so assigning to a property of a returned record can throw or be ignored. If you need to change the data, copy it first:
// Copy before editing: records from cacheable methods may be read-only.
this.contacts = result.map((c) => ({ ...c, selected: false }));Deciding whether a method can be cacheable
Ask these questions in order.
The table below summarizes typical cases.
| Method purpose | Cacheable? | Reason |
|---|---|---|
| Query reference data, such as a list of regions | Yes | Changes rarely, stale risk is low |
| Search as the user types | Usually yes | Same terms repeat, small stale risk |
| Query data that another process updates often | Only with a refresh plan | Cache may hide new rows |
| Insert, update, or delete | No | DML is not allowed |
| Query that also logs or increments a counter | No | Side effect |
| Call to an external service with changing results | Usually no | Cached answer may be wrong |
Using cacheable methods with refresh
If you do want caching and also need fresh data after a change, plan the refresh. For a method used with @wire, call refreshApex on the provisioned value after the save. That tells the framework to fetch the data again and update the cache. The chapter on refreshing data covers this in full.
For imperative calls, there is no wire provisioned value to refresh. The simplest and most predictable options are:
- Use a non-cacheable method for reads that must always be current.
- Keep the cacheable method for stable data and accept that the result can lag.
- After a save, reload through a path you control, for example by calling a non-cacheable read method.
Do not rely on timing. A cache that happens to be empty during your test can be full for a user who has the page open all day.
Common errors
- DML in a cacheable method. The call fails at runtime. Remove the DML or remove
cacheable=true. - Using
@wirewith a non-cacheable method. Wire requirescacheable=true. Either add it, if the method is truly read-only, or call the method imperatively. - Mutating returned data. Records from cacheable calls may be read-only. Copy them first.
- Expecting a fresh read on every click. A repeated imperative call with the same parameters may return the cached result.
- Putting a side effect in a read method. A cached call skips the server, so the side effect would not run every time anyway.
Summary
cacheable=true is a promise that a method only reads data and that a briefly old answer is acceptable. In exchange you get fewer server calls and access to the wire service. Choose it for stable, read-only queries. Leave it off for anything that writes data or must always be current.
Exercise
A component loads a contact's open cases with an Apex method marked cacheable=true. A user closes a case in another tab, returns to the component, clicks the "Reload" button that calls the method imperatively, and still sees the closed case. Give the most likely cause and two ways to fix it.
Show answer
The imperative call is served from the client cache, because the method is cacheable and the parameters are the same, so the result is stale. Fixes: (1) remove cacheable=true and use a non-cacheable method for this read, so every click queries the server; (2) keep the method cacheable but add an explicit refresh step, for example wire the method and call refreshApex on the provisioned value after changes, or reload through a separate non-cacheable method.
Exercise
You add an update statement to a method marked @AuraEnabled(cacheable=true) so that it also records a "last viewed" date. What happens when the component calls it, and how do you restructure the code?
Show answer
The call fails at runtime because DML is not allowed in a cacheable method. Split the work into two methods: keep the read method cacheable, and create a separate @AuraEnabled method without cacheable=true that performs the update. The component calls the update method imperatively when needed.