Sub topic 13
Avoiding unnecessary or repeated calls
This chapter assumes you can already call an Apex method imperatively with async/await, track isLoading and error state, and read a basic @AuraEnabled controller. Here you will learn to stop a component from calling Apex more often than it needs to.
Why every call has a cost
An imperative call is a network round trip to the Salesforce server. Each call starts its own Apex transaction, with its own governor limits (for example, 100 synchronous SOQL queries per transaction). The user also waits for each one.
The cost shows up in three places:
- Latency. A call that takes 400 ms on a fast network feels slow when it runs on every keystroke.
- Server load. Many synchronous requests that run longer than five seconds can hit the org-wide concurrent request limit, which is 10 per org. When it is reached, new long-running requests fail.
- Correctness. Parallel calls can finish out of order, so an old response can overwrite a newer one.
The usual causes of excess calls are listed below.
| Cause | Typical symptom | Fix |
|---|---|---|
| Calling on every `input` or `change` event | A request per keystroke | Debounce |
| Calling with empty or too-short input | Queries that return everything or nothing | Guard clauses |
| Double clicks on a button | Duplicate records or duplicate queries | Ignore clicks while loading |
| Repeating a search the user already ran | Same request, same answer | Local cache |
| Several calls for one screen | Many round trips on load | Combine into one Apex method |
| Out-of-order responses | The UI shows stale results | Request token |
Guard clauses: do not call when the answer is known
The cheapest call is the one you do not make. If the input cannot produce a useful result, return early.
if (term.length < 2) {
this.contacts = [];
return;
}Choose the minimum length from the data. A two-character search against a large Contact table returns many rows that the LIMIT 20 in the controller then cuts off, so the user gets arbitrary results. Requiring a longer term improves both cost and result quality.
Debouncing user input
A debounce delays the call until the user has stopped typing for a short time. Each new keystroke cancels the pending timer and starts a new one. A delay of 250 to 400 ms is a common starting point.
Ignoring stale responses
Debouncing reduces calls but does not prevent overlap. If the user pauses, a call starts, and then they type again and pause, two calls are in flight. Network timing does not guarantee that the first finishes first.
The fix is a request token. Increment a counter before each call, remember the value, and apply the response only if the counter has not moved on.
A complete example
This component combines the guard clause, the debounce, a local cache, and a request token. It uses the searchContacts method from earlier in the tutorial.
import { LightningElement } from 'lwc';
import searchContacts from '@salesforce/apex/ContactController.searchContacts';
const DEBOUNCE_MS = 300;
const MIN_LENGTH = 2;
export default class ContactTypeahead extends LightningElement {
contacts = [];
errorMessage;
isLoading = false;
_timerId;
_requestId = 0;
_cache = new Map();
handleTermChange(event) {
const term = event.target.value.trim();
clearTimeout(this._timerId);
if (term.length < MIN_LENGTH) {
this._requestId++; // makes any in-flight response stale
this.contacts = [];
this.errorMessage = undefined;
this.isLoading = false;
return;
}
this._timerId = setTimeout(() => this.runSearch(term), DEBOUNCE_MS);
}
async runSearch(term) {
const requestId = ++this._requestId;
this.errorMessage = undefined;
if (this._cache.has(term)) {
this.contacts = this._cache.get(term);
this.isLoading = false;
return;
}
this.isLoading = true;
try {
const result = await searchContacts({ searchTerm: term });
this._cache.set(term, result);
if (requestId !== this._requestId) {
return; // a newer request superseded this one
}
this.contacts = result;
} catch (error) {
if (requestId !== this._requestId) {
return;
}
this.contacts = [];
this.errorMessage = error?.body?.message || error?.message || 'Unknown error';
} finally {
if (requestId === this._requestId) {
this.isLoading = false;
}
}
}
disconnectedCallback() {
clearTimeout(this._timerId);
}
}Points to check in this code:
- The
finallyblock is conditional. If a stale request clearedisLoading, the spinner would disappear while the newer request is still running. - A stale response still goes into the cache. The response is correct for its own term, so it is useful later. Only the display is skipped.
disconnectedCallbackclears the timer. Without this, a timer can fire after the component is removed from the page and make a call for nothing.- The cache lives in the component instance. It is discarded when the component is destroyed. It is also not shared between instances.
Preventing duplicate submissions
Searches are safe to repeat. Calls that perform DML are not. A user who double-clicks Save can create two records, or run two updates that overwrite each other.
Ignore the click while a call is running, and also disable the button so the user sees the state:
async handleSave() {
if (this.isSaving) {
return;
}
this.isSaving = true;
try {
await updateEmail({ contactId: this.recordId, email: this.email });
this._cache.clear();
} catch (error) {
this.errorMessage = error?.body?.message || 'Save failed';
} finally {
this.isSaving = false;
}
}In the template, bind disabled={isSaving} on the button. The early return is the real protection. The disabled attribute only updates after the next render, so two fast clicks can both reach the handler before the button is disabled.
Combining calls that belong together
A component that needs an account, its contacts, and a count of open cases can make three imperative calls. Each call adds a round trip and a transaction. Two approaches reduce this.
- Run independent calls in parallel. Use
Promise.allso the total time is the slowest call instead of the sum of all calls. - Return one result from one method. Define a wrapper class in Apex with several
@AuraEnabledproperties. One round trip and one transaction then replace three.
const [account, contacts] = await Promise.all([
getAccount({ accountId: this.recordId }),
getContacts({ accountId: this.recordId })
]);Promise.all rejects as soon as any one call fails. If you want partial results, use Promise.allSettled and inspect each outcome.
The single-method approach is better when the data is always needed together and the queries are cheap. It is worse when you would fetch data the user may never view. In that case, load the extra data when the user asks for it, such as when they open a tab.
What `cacheable=true` changes
When an Apex method is marked cacheable=true, Lightning Experience can keep its results in a client-side cache, and repeated calls with the same parameters may be answered without waiting for the server. This applies to imperative calls as well as wire calls. The cache is managed by the platform, so you do not control how long it lives.
This has two consequences:
- A read-only method that you call often benefits from
cacheable=true, which removes some repeated round trips for free. - If you need fresh data after a change, a cacheable method may return the earlier result. For wired data, use
refreshApex(see the earlier chapter on refreshing data). For imperative calls to a cacheable method, do not assume the second call reaches the server. If you need guaranteed fresh data, use a method withoutcacheable=true, and accept that every call then costs a server round trip.
Deciding what to optimize
Not every call needs these techniques. A button that loads data once per click does not need a debounce. Apply them where the call frequency is driven by the user's input or by events that fire in bursts.
A practical order of work:
- Add guard clauses for input that cannot produce a useful result.
- Add the in-flight guard to every handler that performs DML.
- Debounce input handlers that call Apex.
- Add a request token wherever responses can overlap.
- Consider a local cache or
cacheable=trueonly after you have decided how much staleness is acceptable.
Exercise
A typeahead component debounces input by 300 ms, but users sometimes see results for an earlier term after they have typed a longer one. Why can this still happen, and what change fixes it?
Show answer
Debouncing only limits how often calls start. If the user pauses long enough for one call to start and then types again, two calls are in flight, and the first can finish after the second. The component then overwrites the newer results with the older ones. Fix it with a request token: increment a counter before each call, store its value in a local variable, and apply the response (and clear the loading flag) only when the local value still equals the counter.
Exercise
Your Save handler sets this.isSaving = true and binds disabled={isSaving} on the button, but support still reports duplicate records from double clicks. What is missing, and why does the disabled attribute not prevent it?
Show answer
The handler needs an early return when isSaving is already true. The disabled attribute only takes effect after the component re-renders, so two clicks in quick succession can both reach the handler before the button is disabled. The guard inside the handler runs synchronously and blocks the second call.