Governor limits scenario-based interview questions
"Too many SOQL queries: 101" is the most famous error in Salesforce. These scenarios show how to diagnose limit errors and fix them the way a senior developer would.
On this page (4 sections)
Interview questionsRelated Governor Limits Interview QuestionsFrequently Asked Questions about Governor Limits InterviewsRelated ResourcesNew to this topic? Learn Apex step by step before you practise.
Governor limits are tested in almost every Salesforce technical interview. Interviewers want to know you can write efficient, production-ready code that works within platform constraints. These 16 scenario-based questions cover the most common limit violations and the strategies to solve them. Understanding governor limits deeply separates junior developers from senior ones.
01What are the most important governor limits every developer should know?
What are the most important governor limits every developer should know?
The critical limits per synchronous transaction: 100 SOQL queries, 150 DML statements, 50,000 records retrieved by SOQL, 10,000 records processed by DML, 6 MB heap size, 10-second CPU time, 100 callouts, and 12 MB total callout response size. For async (batch/future): limits are higher; 200 SOQL queries, 60-second CPU time. Knowing these numbers cold shows interviewers you write production-aware code.
02Why does Salesforce enforce governor limits?
Why does Salesforce enforce governor limits?
Salesforce is a multi-tenant platform: thousands of organizations share the same infrastructure. Without limits, one poorly written trigger could consume all server resources and affect every other customer. Governor limits ensure fair resource distribution. They force developers to write efficient, scalable code. Think of them as guardrails, not obstacles. The best Salesforce developers design with limits in mind from the start.
03How do you avoid hitting the 100 SOQL query limit?
How do you avoid hitting the 100 SOQL query limit?
The #1 cause is SOQL inside a for loop. Fix: move queries outside loops. Collect all IDs you need, then run one query with WHERE Id IN :idSet. Store results in a Map<Id, SObject> for O(1) lookups inside the loop. Also: use relationship queries to get related data in one call (SELECT Id, (SELECT Id FROM Contacts) FROM Account). Avoid trigger recursion that re-executes queries. Monitor SOQL usage with Limits.getQueries().
04What is the difference between synchronous and asynchronous governor limits?
What is the difference between synchronous and asynchronous governor limits?
Asynchronous contexts (Batch, Future, Queueable) get higher limits because they run on dedicated resources. Key differences: SOQL queries; 100 sync vs 200 async. CPU time: 10 sec sync vs 60 sec async. Heap: 6 MB sync vs 12 MB async. Callout timeout: 120 sec sync vs 120 sec async (same). Use async for resource-intensive operations. But async has its own limits: 50 future calls per transaction, 250K batch executions per 24 hours.
06How do you handle the 50,000 record query limit for large datasets?
How do you handle the 50,000 record query limit for large datasets?
Options:
- Use more selective WHERE clauses to reduce the result set.
- Use SOQL FOR loops: 'for (Account a : [SELECT ...])' processes records in chunks of 200.
- Use Batch Apex which can query up to 50 million records with QueryLocator.
- Use OFFSET and LIMIT for pagination (but OFFSET has a 2000 limit).
- For very large datasets, use the Bulk API. The key insight: if you're hitting 50K, you probably need async processing.
07What is heap size and how do you manage it?
What is heap size and how do you manage it?
Heap is the memory used by your Apex code during execution. Common heap consumers: large collections (Lists, Maps), SOQL results loaded into memory, and string concatenation. To manage:
- Use SOQL FOR loops instead of loading all records into a List.
- Process in batches and clear collections.
- Avoid storing unnecessary fields: SELECT only what you need.
- Use transient variables in Visualforce controllers.
- Monitor with Limits.getHeapSize() and Limits.getLimitHeapSize().
08How do you handle governor limits in batch Apex?
How do you handle governor limits in batch Apex?
Each execute() method gets fresh governor limits for the batch of records it processes. Start() can return a QueryLocator (up to 50M records) or an Iterable (50K records). Best practices: set appropriate batch size; smaller for complex processing (10-50), larger for simple operations (200-2000). Use Database.Stateful carefully; it persists state across batches but increases heap usage. Handle partial failures with Database.insert(records, false) for graceful error handling.
09What monitoring tools exist for governor limits?
What monitoring tools exist for governor limits?
- Debug Logs: show limit consumption after each transaction.
- Limits class in Apex: Limits.getQueries(), Limits.getDMLStatements() for runtime monitoring.
- Developer Console: real-time log analysis with limit consumption.
- Event Monitoring: track limit-related events across the org.
- AppExchange tools like Salesforce Inspector for quick limit checks.
Best practice: add limit monitoring to your logging framework to catch issues before they hit production.
10How do you design a system that handles 10,000 records in a trigger?
How do you design a system that handles 10,000 records in a trigger?
A data loader operation can fire a trigger with up to 200 records per batch, but the total job might process 10,000+. Design:
- Bulkify everything: no SOQL or DML inside loops.
- Use Maps for efficient lookups.
- Consider the total transaction limits: 100 SOQL queries across all 200 records.
- If processing is too complex for synchronous limits, trigger should enqueue async processing (Queueable or Batch).
- Test with 200 records in your test class to validate bulk behavior.
11What is CPU time limit and how do you reduce CPU consumption?
What is CPU time limit and how do you reduce CPU consumption?
The CPU time limit is 10 seconds for synchronous and 60 seconds for async transactions. Common CPU consumers: complex string operations, nested loops, JSON parsing, and formula field evaluation. To reduce:
- Avoid nested loops: use Maps for lookups.
- Move complex processing to async context.
- Optimize string operations: use String.join() instead of concatenation in loops.
- Cache expensive calculations.
- Reduce the number of trigger executions by consolidating logic.
12How do you handle the 10 DML statements limit for different objects in a single transaction?
How do you handle the 10 DML statements limit for different objects in a single transaction?
Each DML statement on a different object counts as one DML operation against the 150 limit (not 10: that's a common misconception). The 10-DML confusion comes from the 10 different object types in DML limit which doesn't exist. The real constraint: 150 total DML statements per transaction. Group DML by object: insert all Accounts, then all Contacts, then all Opportunities. Each bulk insert/update counts as one DML regardless of how many records are in the list.
13What happens when a governor limit is exceeded?
What happens when a governor limit is exceeded?
Salesforce throws a LimitException which cannot be caught with try-catch: the entire transaction rolls back. All DML operations in that transaction are undone, and the user sees an error. This is why prevention is critical. Use the Limits class to check consumption before expensive operations. For batch jobs, exceptions in execute() don't kill the entire job: just that batch. For integrations, design idempotent operations that can be safely re-executed after failures.
14How do you optimize a trigger that makes callouts?
How do you optimize a trigger that makes callouts?
Callouts can't be made directly from triggers. Use @future(callout=true) or Queueable (implementing Database.AllowsCallouts). Optimization:
- Batch multiple records into a single callout when the API supports it.
- Use Queueable chaining for sequential callouts.
- Limit to 100 callouts per transaction.
- Set appropriate timeout values (default 10s, max 120s).
- Consider Platform Events for decoupling: publish an event from the trigger, handle the callout in a subscriber.
15What is the mixed DML error and how do you solve it?
What is the mixed DML error and how do you solve it?
A mixed DML error occurs when you perform DML on both setup objects (User, Group, PermissionSetAssignment) and non-setup objects (Account, Contact) in the same transaction. Solution: separate the operations into different execution contexts. Use @future or Queueable to perform one set of DML asynchronously. In test classes, use System.runAs() to create a separate execution context. Common trigger scenario: avoid updating User records in the same trigger that updates Accounts.
16How do you handle governor limits when calling external APIs?
How do you handle governor limits when calling external APIs?
Callout limits: 100 callouts per transaction, 120-second timeout per callout, 12 MB total response size. Strategies:
- Batch multiple data points in a single callout.
- Use Queueable chaining for many sequential callouts.
- Implement caching: store API responses in Custom Settings or Platform Cache.
- Use async processing (Batch/Queueable) for bulk callouts.
- Handle timeouts and errors with retry logic.
- Consider middleware for high-volume integrations to stay within limits.
Frequently Asked Questions about Governor Limits Interviews
Why are governor limits the most asked Salesforce topic in interviews?
Because they're the single biggest cause of production incidents. Interviewers use them as a proxy for production readiness: anyone who can write Apex that doesn't blow up under bulk loads has clearly worked on real systems, not just toy projects.
What's the difference between synchronous and asynchronous limits?
Asynchronous Apex (Batch, Queueable, Future, Schedulable) gets roughly 2x the limits of synchronous: 200 SOQL queries vs 100, 60-second CPU vs 10, and 12 MB heap vs 6 MB. The trade-off is latency: async runs 'eventually,' so user-facing operations should still stay synchronous when possible.
How do I avoid the SOQL 100 limit in real code?
Three rules: (1) never put SOQL inside a for-loop; (2) collect all needed IDs into a Set first, then run a single bulk query with WHERE Id IN :idSet; (3) store the results in a Map<Id, SObject> for O(1) lookups inside the loop.
What's the safest way to handle 1M+ records?
Batch Apex with Database.QueryLocator (supports up to 50M records). Set a small batch size for complex execute() logic (10–50) and a larger one for simple updates (200–2000). Use Database.Stateful sparingly because it increases heap.
Can governor limit exceptions be caught with try/catch?
No. LimitException is uncatchable by design: the entire transaction rolls back. Prevention is the only strategy: use the Limits class (Limits.getQueries(), Limits.getCpuTime()) to monitor consumption proactively before expensive operations.