How does client-side caching operate within Lightning Data Service and wired LWC adapters?
Answer
Basics: Caching avoids repeat server calls: two components showing the same account trigger one request and show consistent values. LDS adapters (getRecord, getRecordUi, getObjectInfo, getPicklistValues, uiListApi) use the shared cache automatically; wired Apex methods marked cacheable=true are also cached on the client.
How it works: When a wire runs, the framework checks its cache first and only goes to the server for a miss or stale entry. Updating through LDS (updateRecord, lightning-record-edit-form) updates the cache and re-provisions all components that use that record. Changes made elsewhere (Apex DML, another user, a flow, a trigger) are not known to LDS, so the cache can be stale until it expires or you invalidate it. For wired Apex use refreshApex(this.wiredResult) (pass the entire wired result, not .data). For LDS records after Apex DML use notifyRecordUpdateAvailable([{ recordId }]) (the newer replacement for getRecordNotifyChange; verify availability in your API version).
Advanced / deep dive: Cached Apex means repeat calls with identical parameters can return old data, which is why only read-only methods are allowed to be cacheable=true (no DML). Cache entries have a limited lifetime and are cleared on logout or refresh; exact TTLs are not guaranteed, so never rely on them. Imperative calls to cacheable methods may return cached responses. To force fresh data, use a non-cacheable method, add a cache-busting parameter, or refresh explicitly. Cache is per browser/user session, so it never leaks between users but also never reflects other users' changes in real time; use empApi or Change Data Capture for push updates. The shared cache also means returned objects are immutable; copy before editing.
Code / config example:
import { LightningElement, wire } from 'lwc';
import { refreshApex } from '@salesforce/apex';
import getTasks from '@salesforce/apex/TaskCtrl.getTasks';
import completeTask from '@salesforce/apex/TaskCtrl.completeTask';
export default class Tasks extends LightningElement {
@wire(getTasks) wiredTasks; // keep the whole result for refresh
async handleDone(e) {
await completeTask({ taskId: e.target.dataset.id }); // Apex DML, non-cacheable
await refreshApex(this.wiredTasks);
}
}
Hidden gotchas & must-remember points:
- Apex DML does not automatically invalidate LDS or wired Apex caches.
refreshApexneeds the original wired result object, not the data.cacheable=truemethods cannot do DML.- Other users' edits do not appear until a refresh or push mechanism.
- Cached data is shared and immutable; clone before changing.
- Do not rely on exact cache duration; treat it as an optimization.
Best practice: Prefer LDS and cacheable wires for reads, and explicitly refresh after every write that bypasses LDS.