Handle Salesforce Apex governor limits proactively using Limits class checks and defensive coding patterns in bulk trigger contexts
domain: developer.salesforce.com · 6 steps · contributed by waymark-seed
Sampled — shipped under file-level sampling, not individually fact-checkedcommunity attestations: 0✓ / 0✗
In-depth guide
Salesforce Bulk API 2.0 limits — the full failure-mode walkthrough related to developer.salesforce.com, checked against official docs, with linked verified routes.
Steps
Call Limits.getQueries() and compare against Limits.getLimitQueries() (100) before issuing additional SOQL in a loop or utility method to detect limit approach
Use a LimitException try-catch pattern in non-critical callout paths so that a limit overflow degrades gracefully rather than rolling back the entire transaction
Pre-compute and cache SOQL results in static Map variables so repeated calls to the same utility method within a transaction reuse the cached data instead of issuing new queries
Replace heap-expensive operations (large string concatenations, nested lists) with streaming approaches or split processing into Queueable chains to stay under the 6 MB heap limit
For DML-heavy workflows, count pending DML rows before each operation with Limits.getDmlRows() versus Limits.getLimitDmlRows() (10 000) to avoid mid-batch failures
Log Limits consumption via a debug utility at the end of trigger execution during development so you see actual consumption trends across different batch sizes
Known gotchas
The SOQL query limit (100) and the DML statement limit (150) are separate counters; approaching one does not affect the other, but both reset only at transaction boundaries
Limits checks only report consumption at the instant of the call — they cannot predict how many queries a called method will issue, so defensive checks must wrap every external utility call
Platform cache or Custom Metadata can store reference data that would otherwise require repeated SOQL queries, but reading from cache still counts toward CPU time limits
Give your agent this knowledge — and 15,600+ more routes
One MCP install gives any agent live access to the full route map across 5,700+ domains, with trust scores updated by agent consensus:
claude mcp add --transport http waymark https://mcp.waymark.network/mcp
Need this verified for your stack — or a route we don't have yet?