Optimize Performance
By the end of this lesson, you'll be able to:
- Identify and fix an N+1 query risk if the dashboard is later extended to multiple accounts
- Confirm the current single-account design has no such risk
- Explain the trade-off between cacheable=true and always-fresh data
Prerequisites: "Handle Edge Cases"
Confirming the current design is efficient
getHealthSummary runs a small, fixed number of queries per call — one for open Cases, one for closed Cases, one for the Account's revenue field, one for Contact activity — regardless of how much data exists within those results. For a single-Account dashboard, this is already efficient: no query inside a loop, no unbounded growth (Module 25).
The N+1 risk if extended to a list of accounts
// DON'T DO THIS — if a future "list of accounts" dashboard called this per row
for (Account acc : accountsShownOnDashboard) {
AccountHealthSummary summary = new AccountHealthService().getHealthSummary(acc.Id); // 4 queries EACH time!
}
If this dashboard were later extended to show health summaries for, say, 50 Accounts in a list view, calling getHealthSummary once per Account would run 4 × 50 = 200 queries — this is the classic "N+1 query problem," a variant of Module 25's SOQL-in-a-loop danger, worth naming explicitly even though today's single-Account version doesn't hit it.
The cacheable trade-off
cacheable=true means a support manager might briefly see slightly stale health data (from the client cache) before Salesforce silently refreshes it in the background — an entirely acceptable trade-off for a dashboard showing rollup metrics, but worth naming explicitly: cacheable=true genuinely means "eventually consistent," not "always instantly accurate to the second."
Exercise
As a comment, sketch (without full implementation) how getHealthSummary would need to change to support a bulk version, given a List<Id> of accountIds, avoiding the N+1 problem.
Show hint
Think about Module 25's "collect, then act once" pattern applied to this scenario.
Optimize Performance Quiz
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
This lesson checks the dashboard's performance characteristics deliberately — confirming the current design is efficient, and naming the risk that would appear if it were extended to show multiple accounts at once.