Ask Krrish Contact
Home
Developer & Admin
Apex Triggers Mastery Asynchronous Apex SOQL & SOSL Governor Limits Flows & Process Builder
Advanced Topics
LWC Essentials Security & Sharing Managed Packages Deployment & CI/CD Integration Patterns
Interview Prep
Practice interview questions
Resources
Sales Cloud Class Diagram
Blog AI News
Available Now
Agentforce Pricing Calculator New Debug Log Analyzer SFX Forge New SFX Grove SFX Travel Manager
Salesforce + AI
AI Agent Development Salesforce Agentforce Development Custom RAG Solutions AI + Salesforce Integration Customer Support AI Agents AI Lead Qualification AI Knowledge Base Assistant AI Workflow Automation
Salesforce work
Issue Fix Sprint Automation Sprint LWC & integrations Overflow support for partners Agentforce & AI usage review All services →
About Ask Krrish Contact

Salesforce Governor Limits: The Full List, Common Errors and How to Avoid Them

Understanding and adhering to Salesforce Governor Limits is crucial for writing scalable, efficient, and deployable Apex code. This module will explain what governor limits are, why they exist, and how to write code that respects them.

Need hands-on help?

What are governor limits in Salesforce?

Governor limits are runtime caps Salesforce enforces on every Apex transaction so one org can't overload shared servers. The most common are 100 SOQL queries (200 async), 150 DML statements, 50,000 queried rows, 10,000 DML rows and 10 seconds of CPU time (60 async). Exceeding one throws System.LimitException, which can't be caught.

  • Heap size: 10 MB synchronous, 25 MB asynchronous, per the current Apex Developer Guide.
  • Callouts: 100 per transaction, with 120 seconds of cumulative timeout.
  • Trigger recursion depth: 16 levels of triggers firing other triggers.
  • Batch Apex gets a fresh set of limits for every execute chunk.
  • Use the Limits class, for example Limits.getQueries(), to check usage at runtime.

1. Introduction to Governor Limits

Salesforce operates on a multi-tenant architecture, meaning that a single instance of the software serves multiple customers (tenants). To ensure that no single customer monopolizes the shared resources (like CPU, memory, database, network), Salesforce enforces strict runtime limits on Apex code and other platform features. These are known as Governor Limits.

Why do Governor Limits Exist?

  • Resource Sharing: Prevents any single organization from consuming all available resources, ensuring fair usage for all tenants on the shared infrastructure.
  • Scalability & Stability: Helps maintain the overall performance, stability, and reliability of the Salesforce platform for everyone.
  • Code Efficiency: Encourages developers to write efficient, bulkified, and optimized code — it forces good programming practices.
  • Security: Limits the potential impact of malicious or poorly written code.

Understanding these limits is not just about avoiding errors; it's about writing high-quality, performant, and scalable applications on the Salesforce platform. Failing to adhere to governor limits will result in runtime exceptions that halt code execution.

2. Types of Governor Limits

Salesforce imposes various types of governor limits, each targeting different aspects of code execution and resource consumption. Here are the most common ones:

a. Per-Transaction Apex Limits

These limits apply to a single Apex transaction, from when a trigger fires or an anonymous block executes until the associated operations complete. Scheduled Apex uses synchronous limits even though it is scheduled asynchronously. Bulk API and Bulk API 2.0 transactions generally use the higher effective synchronous or asynchronous limit; their CPU allowance is 60,000 ms.

  • SOQL Queries:
    • Total SOQL queries issued: 100 (synchronous), 200 (asynchronous)
    • Total records retrieved by SOQL queries: 50,000
  • SOSL Queries:
    • Total SOSL queries issued: 20
  • DML Operations:
    • Total DML statements issued: 150
    • Total records processed by DML: 10,000
  • CPU Time:
    • Total CPU time: 10,000 ms (synchronous), 60,000 ms (asynchronous)
  • Heap Size:
    • Maximum heap size: 10 MB (synchronous), 25 MB (asynchronous); email services have 50 MB
  • Callouts:
    • Total callouts (HTTP/web service): 100
    • Maximum cumulative callout timeout: 120 seconds
  • Future Methods:
    • @future calls per invocation: 50 in synchronous and Queueable contexts, and 0 in Batch and future contexts
  • Queueable Jobs:
    • Maximum Queueable jobs added in a single transaction: 50 synchronously and 1 asynchronously; Bulk API and Bulk API 2.0 transactions use the higher effective limit

How are limits shared within a transaction?

Flow, triggers, and Apex that run in the same transaction consume the transaction's shared resources. A governor limit exception cannot be caught, and the failed transaction rolls back its database changes.

Consider the full automation path when estimating queries, DML, CPU, and heap, including work started by record changes. Certified managed packages can receive separate per-transaction allowances for certain limits within their namespaces, subject to cumulative cross-namespace limits. CPU time and heap remain shared across namespaces. Review the combined workload and leave headroom for other automation rather than budgeting each component in isolation.

b. Per-Organization Limits

These limits apply across your entire Salesforce organization, not just a single transaction.

  • Scheduled Jobs: Up to 100 Apex classes can be scheduled concurrently; Developer Edition allows 5
  • Batch Apex Jobs: Maximum Batch Apex jobs queued or active at one time: 5
  • Daily Async Apex Executions: The standard allocation for asynchronous Apex executions (future, Queueable, batch, and scheduled) per 24 hours is the greater of 250,000 or 200 times the number of applicable licenses.

c. Other Important Limits

  • Maximum trigger recursion depth: 16 (limits recursively fired triggers)
  • Method call stack depth: Method calls are also subject to a stack depth limit; avoid uncontrolled recursion.
  • Org-wide Apex code size: 6 MB; scratch orgs have 10 MB

For the most up-to-date and complete list of governor limits, always refer to the official Salesforce Apex Developer Guide: Governor Limits.

3. Common Governor Limit Errors

When governor limits are exceeded, Salesforce throws runtime exceptions that stop code execution. Understanding these errors helps you diagnose and fix problems quickly:

  • System.LimitException: Too many SOQL queries — Occurs when more than 100 SOQL queries are executed in a synchronous transaction.
  • System.LimitException: Too many DML statements — Occurs when a transaction exceeds 150 DML statements. DML rows have a separate limit.
  • System.LimitException: Apex CPU time limit exceeded — The transaction exceeded its application-server CPU allowance, normally 10,000 ms synchronously or 60,000 ms asynchronously. Database execution and callout waiting are excluded.
  • System.LimitException: Heap size too large — The Apex heap size exceeded 10 MB synchronously or 25 MB asynchronously; email services have a 50 MB limit.
  • System.LimitException: Too many callouts — More than 100 callouts were made in a transaction. The cumulative callout timeout has a separate 120-second limit.

Recognizing these exceptions early helps avoid costly debugging and improves code performance and reliability.

4. Strategies & Best Practices

Writing governor-limit-aware Apex requires following best practices to keep your code efficient, maintainable, and scalable:

  • Bulkify Your Code: Always design code to handle multiple records at once — never put SOQL or DML inside loops.
  • Use Collections Wisely: Use lists, maps, and sets to reduce queries and DML operations.
  • Avoid Recursive Triggers: Use idempotent logic, field-change checks, and narrowly scoped guards. Test re-entry and multiple trigger chunks; a blanket static Boolean can skip later chunks.
  • Optimize SOQL Queries: Select only required fields, filter records with indexed fields, and avoid unnecessary queries.
  • Use Asynchronous Processing: Choose Queueable or Batch Apex for work suited to asynchronous processing, and use Scheduled Apex to start work at a specified time. Generally prefer Queueable to future methods.
  • Limit Data Returned: Use selective queries and pagination to limit heap usage and improve CPU time.
  • Test with Large Data Volumes: Write tests with bulk data and check resource headroom to prevent limit failures.

How does Batch Apex handle large data sets?

Each Batch Apex execute invocation is a separate transaction with fresh per-transaction limits. A Database.QueryLocator returned from the batch start method can select up to 50 million rows.

Choose a scope size that leaves room for all automation invoked by each batch, and account for failures in individual transactions. For other queries, a SOQL for-loop can reduce heap pressure by retrieving records in batches, but it does not remove the normal query-row limit. Use selective filters and the Query Plan tool to assess queries on large data volumes, and avoid processing records that the operation does not need.

5. Testing for Governor Limits

Effective testing is essential to ensure your Apex code respects governor limits under real-world conditions:

  • Use @TestSetup Methods: Create reusable test data to simulate bulk processing.
  • Write Bulk Tests: Test triggers and classes with collections of records, not just single instances.
  • Prevent Limit Exceptions: Test bulk workloads and resource headroom to prevent limit exceptions. Test proactive fallback behavior separately.
  • Measure Performance: Use debug logs to track CPU time, heap size, and query counts during test execution.
  • Leverage Salesforce Tools: Use Developer Console, Apex Test Execution, and the Limits class to monitor resource usage.
  • Continuous Integration: Integrate tests into CI/CD pipelines to catch limit-related issues early in the development cycle.

How do you test limits and asynchronous work?

Use Test.startTest() to begin a fresh governor limit window for the work under test, and Test.stopTest() to end it and run asynchronous work queued in that window before assertions. The original test limits resume after stopTest().

Set up representative data before the window, then exercise bulk records, trigger re-entry, and multiple chunks. Use the Limits methods to inspect consumption and verify that the workload retains sufficient headroom. Assert the resulting data and any deliberate fallback behavior separately. Test asynchronous stages independently where needed, rather than assuming an entire chain will run in a single test.

6. Conclusion & Key Takeaways

Understanding and proactively managing Salesforce Governor Limits is paramount for any developer working on the platform. They are not merely obstacles to overcome, but fundamental guardrails that ensure the stability, scalability, and fairness of a multi-tenant environment.

Key Takeaways

  • Multi-Tenancy is Key: Limits exist to protect shared resources and ensure optimal performance for all Salesforce customers.
  • Bulkify Everything: The golden rule — avoid SOQL queries and DML statements inside loops. Process data in collections.
  • One Trigger, One Handler: Centralize your trigger logic for better maintainability and control over execution order.
  • Go Async When Necessary: Use Queueable or Batch Apex for suitable long-running work, callouts, or large data transformations. Scheduled Apex cannot make synchronous callouts directly; enqueue a Queueable or start a Batch job that implements Database.AllowsCallouts.
  • Be Selective: Write SOQL queries that efficiently use indexed fields to retrieve only the data you need.
  • Guard Against Recursion: Use idempotent logic, field-change checks, and narrowly scoped guards; test re-entry and multiple trigger chunks.
  • Test Thoroughly: Include unit tests for bulk workloads and check that the transaction has sufficient governor limit headroom.

By internalizing these best practices, you'll not only avoid hitting governor limits but also become a more skilled, confident, and effective Salesforce developer, capable of building high-quality, scalable solutions.

Frequently asked questions

Can you catch a governor limit exception?

No. System.LimitException can't be caught by try/catch, and the whole transaction rolls back. Prevent it by bulkifying code and checking usage with the Limits class before expensive work.

What causes 'Too many SOQL queries: 101'?

More than 100 SOQL queries ran in one synchronous transaction, almost always because a query sits inside a loop or a trigger fires recursively. Query once outside the loop, store results in a Map and look them up inside the loop.

How do you fix 'Apex CPU time limit exceeded'?

Remove nested loops over large lists, use Maps for lookups, avoid repeated work across triggers and flows on the same object, and move heavy processing to Queueable or Batch Apex, which get 60,000 ms of CPU time.

Do managed packages share governor limits with my code?

Certified managed packages from AppExchange get their own per-transaction limits for most counters, such as SOQL and DML. CPU time, heap size and transaction time are shared across the whole transaction. Uncertified packages share all limits with your code.

Do custom metadata queries count toward the SOQL limit?

No. SOQL queries on custom metadata types don't count toward the 100-query limit, which makes them a good place for configuration.

Are governor limits different in tests?

Each test method gets its own set of limits. Wrap the code under test in Test.startTest() and Test.stopTest() to give it a fresh set of limits and to run queued async jobs.

Sources: Execution governors and limits · Limits class

Get Expert Help

SFX Support — Salesforce + AI solutions. Independent: not affiliated with, endorsed by, or a partner of Salesforce, Inc. Salesforce and Agentforce are trademarks of Salesforce, Inc.