Advanced 25 min read

Cacheable Methods and Performance

By the end of this lesson, you'll be able to:

  • Mark an @AuraEnabled method as cacheable=true
  • Explain what the client-side cache actually stores and reuses
  • Recognize when a method should NOT be marked cacheable

Prerequisites: "Returning Data to LWC: Wrapper Classes and DTOs"

Marking a method cacheable

@AuraEnabled(cacheable=true)
public static List<Account> getAccounts() {
    return [SELECT Id, Name FROM Account];
}

cacheable=true is the requirement referenced in Lesson 3 — it's what enables the wire service to work efficiently: the platform can serve a cached result immediately (showing the UI something right away) while it silently re-fetches fresh data in the background, rather than the user staring at a blank loading state every single time.

What actually gets cached

The client caches the result of a specific method call with specific parameters — calling searchAccountsByName('Acme') twice in a row can return the cached result instantly the second time, without a new server round-trip, while searchAccountsByName('Riverbend') is a different cached entry entirely, since the parameter differs.

When NOT to mark a method cacheable

// WRONG: this performs DML — it must never be cacheable
@AuraEnabled(cacheable=true)
public static void saveOpportunity(Opportunity opp) {
    update opp; // compile error — cacheable methods cannot perform DML
}

cacheable=true methods must be read-only — Apex actually enforces this at compile time, refusing to let a cacheable=true method perform any DML at all. This directly connects back to Lesson 3's rule of thumb: read/reactive methods can be cacheable; action-performing methods (like a save) must never be.

Exercise

As a comment, explain why Apex refuses to compile a cacheable=true method that performs DML.

Show hint

Think about what "cacheable" implies about the method never changing anything.

APEX

Cacheable Methods and Performance Quiz

1. What does Apex do if a cacheable=true method attempts to perform DML?

Log in to submit the quiz and save your score.

My Notes

Log in to keep private notes on this lesson.

Questions about this lesson

No questions yet — be the first to ask.

Log in to ask a question about this lesson.

Summary

cacheable=true tells the platform this method's results can be safely cached on the client, avoiding a repeated server round-trip for the same request — but only genuinely fits read-only methods.