Sub topic 2
Why cached data goes stale
This chapter assumes you can build a basic Lightning Web Component and wire a cacheable Apex method to it. It also assumes you can read an @AuraEnabled method with a SOQL query, and that you are comfortable with promises and async/await. The chapter explains what the client-side cache does and why it can show data that no longer matches the database. It is the reason refreshApex, covered in later chapters, exists.
What the cache does
When you mark an Apex method cacheable=true and wire it to a component, the platform stores the response in a client-side cache in the browser. The cache entry is keyed by the method and the parameter values. The next time any component asks for the same method with the same parameters, the platform can answer from the cache without waiting for a server round trip.
This has two practical effects:
- Components render faster, because cached data is available immediately.
- Several components that wire the same method with the same parameters share one entry. They do not each cause a separate server call.
The cache is a performance feature. It does not promise that what you see matches what is in the database right now.
Where staleness comes from
Data is stale when the cache holds a response that was correct when it was stored, but the underlying records have changed since. The cache has no general way to learn about every change. Apex results are arbitrary: a method can query several objects, apply filters, and compute values. The platform cannot work out which cached results a given record change affects.
Several kinds of change leave a cached Apex result out of date:
| Source of the change | Why the cache does not notice |
|---|---|
| Your own component calls a non-cacheable Apex method that runs DML | The cached query result is separate from the DML call, and nothing links the two |
| Another user edits or deletes the records | The change happens on the server and never reaches your browser session |
| A flow, trigger, process, or batch job changes the records | The change happens on the server, outside the client |
| The user edits the record in another tab, or in a standard page component | Another cache entry or UI layer handled the change, not your Apex result |
| A record is updated through `updateRecord` from `lightning/uiRecordApi` | Record data wires can refresh, but cached Apex results are not tied to them |
The last row catches many developers out. Lightning Data Service keeps record data (getRecord and similar adapters) consistent when you use its own APIs. Your Apex method is outside that mechanism, so a cached Apex result does not update just because a record it returned was edited elsewhere.
The platform does revalidate, but not on your schedule
You may see the cache correct itself without any code from you. That is expected, and it is easy to misread. When a cached value exists, the wire service can provision it right away and then check the server. If the server's answer differs, the component receives the new value.
You cannot build on this behavior, for three reasons:
- The timing is not under your control. Your code cannot wait for the cache to "catch up" at a known moment.
- The re-check depends on the platform's internal rules, such as when the data was cached and when the component asks for it again. Those rules are not a contract.
- A user who has just saved a change expects to see it now, not at some later point.
Rely on the platform's own revalidation for background freshness only. When your code changes data, refresh the wire explicitly.
A concrete example of stale data
The following example shows the problem with no refresh logic. It uses the ContactController from the plan. The Apex class has a cacheable read method and a non-cacheable update method.
public with sharing class ContactController {
@AuraEnabled(cacheable=true)
public static List<Contact> getContacts(Id accountId) {
return [
SELECT Id, Name, Email
FROM Contact
WHERE AccountId = :accountId
WITH USER_MODE
ORDER BY Name
LIMIT 50
];
}
@AuraEnabled
public static void updateEmail(Id contactId, String email) {
Contact c = new Contact(Id = contactId, Email = email);
update as user c;
}
}The component below wires getContacts to a property. A button changes the email of the first contact by calling updateEmail. It never refreshes the wire.
import { LightningElement, api, wire } from 'lwc';
import getContacts from '@salesforce/apex/ContactController.getContacts';
import updateEmail from '@salesforce/apex/ContactController.updateEmail';
export default class StaleDemo extends LightningElement {
@api recordId;
status = '';
@wire(getContacts, { accountId: '$recordId' })
contacts;
async handleChange() {
const first = this.contacts.data && this.contacts.data[0];
if (!first) {
return;
}
const email = `demo${Date.now()}@example.com`;
try {
await updateEmail({ contactId: first.Id, email });
this.status = `Saved ${email}. The list below was not refreshed.`;
} catch (e) {
this.status = 'The save failed.';
}
}
}<template>
<lightning-button label="Change first email" onclick={handleChange}></lightning-button>
<p>{status}</p>
<template lwc:if={contacts.data}>
<template for:each={contacts.data} for:item="contact">
<p key={contact.Id}>{contact.Name}: {contact.Email}</p>
</template>
</template>
<template lwc:if={contacts.error}>
<p>Could not load contacts.</p>
</template>
</template>Place the component on an Account record page and click the button. The status line reports a successful save. The list still shows the old email, because the component is still rendering the value the wire provisioned before the save. A page reload fetches the new value, which is proof that the database was updated and only the client copy was old.
Nothing here is broken. The save worked, the cache did its job, and the two never communicated.
The timeline of a stale read
The diagram traces what happens in the example from the first render to the stale display.
The updateEmail call goes straight to the server. It does not pass through the cache entry for getContacts, so the entry is not changed or invalidated.
Why DML cannot do the invalidation for you
It is natural to ask why the platform does not clear the cache entry when you run DML. The reason is that the platform cannot tell which entries the DML affects. Your query could filter on a field you just changed, or on a related object. Another component might call a different cacheable method over the same records. The only party that knows which wire should be refreshed is your component. This is the design reason refreshing is a call you make, and it is why the next chapters have you keep a reference to the wired result and pass it to refreshApex.
A related rule explains why the read and the save sit in separate methods. A method marked cacheable=true must not modify data, so Apex DML belongs in a non-cacheable method. Because the update method is not cached, calling it can never refresh the read method's cache. The two results are separate by design.
Staleness within one session
Staleness is not only about other users. Within a single user session, several things can leave a component out of date:
- A parent component updates data, but a child component holds a cached result for the same method and parameters.
- A modal or utility component saves a change while a list component on the same page keeps displaying its earlier result.
- A navigation event returns the user to a page where the component has not been recreated, so it keeps its earlier wire result.
In each case the data is fine on the server. The question is whether the component that displays it asked again. You will see the same pattern whenever a write path and a read path are separate pieces of code.
Recognizing staleness when debugging
Use these checks when a user says "I saved it but the list didn't change":
- Confirm the save worked. Check the record in the UI or run a SOQL query. If the record is unchanged, the problem is the save, not the cache.
- Reload the page. If the new value appears, the cache was serving old data.
- Check whether the display comes from a cacheable Apex wire. Record data from
getRecordbehaves differently. - Look for a refresh step after the DML call. If there is none, you have found the cause.
What to take into the next chapter
- A cacheable wire stores its result in the browser and may serve that stored result.
- Changes made through any other path leave the stored result unchanged, including your own DML calls, other users, flows, and triggers.
- The platform's background revalidation cannot be scheduled or relied on for user-triggered changes.
- Only your component knows when its data has changed, so it must request a refresh.
To request a refresh, you need a reference to what the wire gave you. The next chapter looks at that result object.
Exercise
A component wires the cacheable method getContacts and also calls the non-cacheable method updateEmail. After the update succeeds, the page still shows the old email, but a full page reload shows the new one. What does this tell you about where the problem is, and why did the wired data not change by itself?
Show answer
The save worked and the database holds the new value, since the reload shows it. The problem is the client-side cache. The wire provisioned the result before the save, and the updateEmail call goes directly to the server without touching the cache entry for getContacts. The platform cannot tell which cached Apex results a given DML call affects, so it does not invalidate them. The component must request a refresh itself after the save.
Exercise
Name three changes, other than your own component's DML call, that can leave a cached Apex wire result out of date.
Show answer
Any three of these: another user editing or deleting the records, a flow, trigger, or batch job changing them on the server, the user editing the record in another tab, and a sibling component saving data that a list component displays through a cacheable Apex result. In all cases the server data changed, and the browser cache entry was not told.
Exercise
A teammate proposes adding the current timestamp as an extra parameter to getContacts so the data is always fresh. Give two reasons this is a poor fix.
Show answer
Each call has a different parameter value, so each call creates a new cache entry and the cache can no longer share results or speed up rendering. It also hides the actual problem, which is that the component never asks for a refresh after changing data. In a wire it would also make the parameters reactive in a way that causes extra server calls.