governor-limits

Use when writing, reviewing, or troubleshooting Apex that risks hitting Salesforce governor limits. Triggers: 'too many SOQL queries', 'too many DML statements', 'CPU time limit', 'bulkification', 'Queueable vs Batch'. NOT for trigger architecture decisions unless the core problem is limit consumption.

Best use case

governor-limits is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

Use when writing, reviewing, or troubleshooting Apex that risks hitting Salesforce governor limits. Triggers: 'too many SOQL queries', 'too many DML statements', 'CPU time limit', 'bulkification', 'Queueable vs Batch'. NOT for trigger architecture decisions unless the core problem is limit consumption.

Teams using governor-limits should expect a more consistent output, faster repeated execution, less prompt rewriting.

When to use this skill

  • You want a reusable workflow that can be run more than once with consistent structure.

When not to use this skill

  • You only need a quick one-off answer and do not need a reusable workflow.
  • You cannot install or maintain the underlying files, dependencies, or repository context.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/governor-limits/SKILL.md --create-dirs "https://raw.githubusercontent.com/PranavNagrecha/AwesomeSalesforceSkills/main/skills/apex/governor-limits/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/governor-limits/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How governor-limits Compares

Feature / Agentgovernor-limitsStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

Use when writing, reviewing, or troubleshooting Apex that risks hitting Salesforce governor limits. Triggers: 'too many SOQL queries', 'too many DML statements', 'CPU time limit', 'bulkification', 'Queueable vs Batch'. NOT for trigger architecture decisions unless the core problem is limit consumption.

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

SKILL.md Source

You are a Salesforce expert in Apex transaction design. Your goal is to keep Apex bulk-safe, limit-aware, and operationally predictable under real production volume. Use this skill when you see too many SOQL queries errors or need to bulkify a trigger to avoid limits.

## Before Starting

Check for `salesforce-context.md` in the project root. If present, read it first.
Only ask for information not already covered there.

Gather if not available:
- Is this trigger, synchronous service, Queueable, Batch, or `@AuraEnabled` Apex?
- What operation is failing: SOQL, DML, CPU, heap, callouts, or async chaining?
- What record volume is realistic in production, not just in the failing example?
- Is the code called by Flow, Process, Platform Events, or integrations in the same transaction?

## How This Skill Works

### Mode 1: Build from Scratch

1. Assume 200-record bulk execution unless the entry point proves otherwise.
2. Design the transaction around the collect -> query once -> map -> process -> DML once pattern.
3. Decide whether the work belongs in synchronous Apex, Queueable, Batch, or Platform Events.
4. Keep callouts, cross-object fan-out, and large data movement out of fragile trigger paths.
5. Add limit checkpoints or test assertions where the volume risk is non-trivial.

### Mode 2: Review Existing

1. Find any SOQL, DML, callout, JSON parsing, or heavy string work inside loops.
2. Check whether trigger logic, Flow-invoked Apex, and helper classes share the same limit budget.
3. Verify async selection: Queueable for controlled background work, Batch for large-scale processing, `@future` only for small legacy patterns.
4. Flag transactions that assume single-record behavior when Salesforce can send 200.
5. Review tests for bulk scenarios, not just happy-path singles.

### Mode 3: Troubleshoot

1. Start from the exact limit exception or debug log checkpoint.
2. Identify the real transaction boundary and every automation layer inside it.
3. Count where queries, DML, CPU, or heap are consumed.
4. Fix the pattern first, then choose async offload if the business flow still exceeds a safe synchronous budget.
5. Re-test with realistic batch size and related automation enabled.

## Governor Limit Control

### Limits That Matter Most

| Limit | Synchronous | Asynchronous | Why It Matters |
|-------|-------------|--------------|----------------|
| SOQL queries | 100 | 200 | Loop-driven query patterns fail first |
| DML statements | 150 | 150 | Repeated `update` or `insert` in loops burns budget quickly |
| DML rows | 10,000 | 10,000 | Large fan-out often needs Batch |
| CPU time | 10,000 ms | 60,000 ms | Complex transforms and nested loops fail here |
| Heap size | 6 MB | 12 MB | Large collections and JSON payloads dominate memory |
| Callouts | 100 | 100 | Integration loops still hit a hard cap |
| Queueable jobs enqueued | 50 | 1 child/job | Matters for fan-out and chaining strategy |

### Bulkification Pattern

Use this order every time:

1. Collect IDs or keys from the input records.
2. Query once outside the loop.
3. Build maps or grouped collections for O(1) lookup.
4. Process in memory.
5. Perform DML once per object/action where possible.

If a design cannot follow that pattern, justify why and re-check whether the work should move async.

### Async Decision Matrix

| Mechanism | Use When | Avoid When |
|-----------|----------|------------|
| `Queueable` | Need controlled async work, SObject context, chaining, or callouts | You must process very large data sets |
| `Batch Apex` | More than 10,000 rows, scheduled cleanup, or large reprocessing | The work is really one user transaction and must finish immediately |
| `@future` | Small legacy callout or fire-and-forget pattern | New feature work that needs chaining, tracking, or richer payloads |
| Platform Event | Need decoupling across systems or automation layers | You need immediate same-transaction guarantees |

### Callout and DML Rule

Do not treat callout failures as a last-minute patch.

- If the transaction already performed DML, move the callout to Queueable or another async boundary.
- If the callout result is required before commit, redesign the flow so the transaction order is explicit and safe.
- If the trigger path depends on an external system, document the business fallback before shipping.

#
## Recommended Workflow

Step-by-step instructions for an AI agent or practitioner activating this skill:

1. Gather context — confirm the org edition, relevant objects, and current configuration state
2. Review official sources — check the references in this skill's well-architected.md before making changes
3. Implement or advise — apply the patterns from Core Concepts and Common Patterns sections above
4. Validate — run the skill's checker script and verify against the Review Checklist below
5. Document — record any deviations from standard patterns and update the template if needed

---

## Review Checklist

- [ ] No SOQL inside loops
- [ ] No DML inside loops
- [ ] No repeated JSON parse or string-heavy work inside loops
- [ ] Related automation layers are counted in the same transaction budget
- [ ] Async choice matches volume and recovery needs
- [ ] Bulk tests cover 200 records and realistic related data

## Salesforce-Specific Gotchas

| Gotcha | Why it bites |
|---|---|
| Limits are per transaction, not per method | Trigger code, service classes, Flow-invoked Apex, and utilities all share the same governor budget. |
| Apex is bulk-called even when users work one record at a time | Data loads, list views, integrations, and platform internals can still hand you 200 records. |
| `@future` is a narrow tool | Primitive-only parameters, no chaining, weak observability — a poor default for new work. |
| Callout after DML causes `uncommitted work pending` | If the transaction already changed data, offload the callout or redesign the process. |
| Batch resets limits per execute chunk, not per job | Expensive code can still fail inside one chunk even though the whole job is "async." |

## Proactive Triggers

Surface these WITHOUT being asked:

| Pattern | Severity | Reason |
|---|---|---|
| SOQL or DML inside loops | Critical | Fastest path to production limit failures. |
| Trigger or service code written for one record only | High | Salesforce can bulk-invoke it with 200 records. |
| CPU-heavy string/JSON logic inside nested loops | High | CPU failures are often harder to diagnose than SOQL overages. |
| Async used as a band-aid over bad synchronous design | Medium | Offloading broken logic still creates broken jobs. |
| No bulk test coverage or no limit assertions in risky code | Medium | The design has not been proven at realistic scale. |

## Output Artifacts

| When you ask for... | You get... |
|---------------------|------------|
| Bulkification review | Findings on SOQL, DML, CPU, heap, and async misuse |
| New Apex scaffold | A bulk-safe pattern with transaction boundaries called out |
| Limit exception triage | Root cause plus the smallest safe design change |

## Related Skills

- **apex/trigger-framework**: Trigger structure decides whether limit-safe patterns are even possible.
- **apex/soql-security**: Query refactors still need CRUD/FLS enforcement, not just lower SOQL counts.
- **flow/fault-handling**: Flow-invoked Apex and record-triggered automation can share the same budget.

Related Skills

callout-limits-and-async-patterns

8
from PranavNagrecha/AwesomeSalesforceSkills

Use when designing or troubleshooting Apex callouts that approach governor limits: choosing between synchronous callouts, @future, Queueable, Continuation, or async chaining strategies. NOT for HTTP request construction or Named Credential setup (use named-credentials-setup).

api-governance-and-rate-limits

8
from PranavNagrecha/AwesomeSalesforceSkills

Monitor and govern Salesforce API consumption: per-user limits, org allocation, lightning-rest limits, and backoff. NOT for designing new endpoints.

flow-governor-limits-deep-dive

8
from PranavNagrecha/AwesomeSalesforceSkills

Compute and budget governor-limit consumption per Flow type with worked math: SOQL, DML rows, CPU time, heap. Includes per-entry-point budget tables, cross-automation shared-limit math, and tuning strategies when a flow hits a ceiling. NOT for general bulkification (use flow-bulkification). NOT for Apex limits (use apex-governor-limits).

org-limits-monitoring

8
from PranavNagrecha/AwesomeSalesforceSkills

Use when designing or implementing proactive monitoring of Salesforce org-level limits such as API call consumption, storage usage, custom object counts, or platform event allocations. Trigger phrases: 'how do I monitor org limits programmatically', 'set up alerts before we hit API limits', 'REST Limits resource usage', 'OrgLimits.getAll() in Apex', 'scheduled limit checks', 'proactive limit threshold alerting', 'Company Information limits dashboard', 'we keep getting surprised by limit breaches in production'. NOT for per-transaction governor limit planning (use limits-and-scalability-planning). NOT for Connected App API throttling or rate limiting policies (use api-security-and-rate-limiting). NOT for individual Apex code optimization against transaction limits (use apex-cpu-and-heap-optimization).

limits-and-scalability-planning

8
from PranavNagrecha/AwesomeSalesforceSkills

Use when planning a new org build for scale, auditing an existing org for governor limit exposure, or investigating a limit-related incident. Trigger phrases: 'org is hitting governor limits', 'how many custom objects can we have', 'will our data volume cause performance issues', 'batch job keeps failing with limit errors', 'planning for 10 million records', 'platform event throughput limits', 'SOQL limit exceeded in production'. NOT for code-level optimization (use apex-cpu-and-heap-optimization), NOT for individual SOQL query tuning (use apex/soql-optimization), NOT for Batch Apex authoring mechanics (use apex/batch-apex).

governor-limit-recovery-patterns

8
from PranavNagrecha/AwesomeSalesforceSkills

Recovering from and preventing Apex governor limit errors: proactive Limits class checkpoints, savepoint-based partial recovery, BatchApexErrorEvent scope recovery, CPU timeout analysis, limit-safe coding patterns. Use when diagnosing LimitException failures or designing limit-safe Apex. NOT for general limits overview (use limits-and-scalability-planning). NOT for bulkification patterns (use governor-limits).

formula-field-performance-and-limits

8
from PranavNagrecha/AwesomeSalesforceSkills

Use when diagnosing SOQL performance problems caused by formula fields, hitting formula compile-size limits, or deciding whether to replace a formula field with a stored field for indexing. Triggers: 'formula field slowing SOQL', 'compile size limit', 'cross-object formula spanning limit', 'formula field not indexable', 'LDV query full table scan', 'SOQL WHERE on formula'. NOT for formula syntax help, building formula expressions, or authoring new formulas from scratch — use admin/formula-fields for that.

apex-limits-monitoring

8
from PranavNagrecha/AwesomeSalesforceSkills

Use this skill when writing Apex that must check governor limits at runtime before executing expensive operations — guard clauses, early-exit patterns, Queueable re-queue on limit approach, and batch scope sizing. Trigger keywords: check governor limits before SOQL apex, defensive coding against limits apex, Limits.getDMLStatements getLimitDMLStatements, Limits class usage, guard clause governor limits, remaining SOQL queries Apex, heap size check before DML, LimitException handling. NOT for limit values themselves — see apex-cpu-and-heap-optimization. NOT for async job design choices — use the async-selection decision tree. NOT for org-level aggregate limit consumption — see architect/org-limits-monitoring.

xss-and-injection-prevention

8
from PranavNagrecha/AwesomeSalesforceSkills

Use when writing or reviewing Visualforce pages, Apex controllers, or LWC components that output user-supplied data, build dynamic queries, or construct HTTP responses. Triggers: 'XSS in Visualforce', 'SOQL injection vulnerability', 'how to encode output in Apex', 'JSENCODE Visualforce', 'open redirect prevention'. NOT for Apex CRUD/FLS enforcement (use soql-security or apex-crud-and-fls), NOT for Shield encryption (use shield-encryption-key-management), NOT for AppExchange security review process (use secure-coding-review-checklist).

visualforce-security-and-modernization

8
from PranavNagrecha/AwesomeSalesforceSkills

Use when hardening or modernizing legacy Visualforce pages — covers the platform CSRF token model and when disabling it is a security regression, view state encryption guarantees and the 170 KB ceiling, FLS/CRUD enforcement gaps on `<apex:outputField>` and on getters that return sObjects, `<apex:includeScript>` interaction with the org Content Security Policy, hosting LWC inside a VF page via `lightning:container` / `lightning-out`, and the retire-vs-harden-vs-leave-alone decision for an inventory of legacy pages. Triggers: 'should I rewrite this Visualforce page in LWC', 'CSRF protection disabled on Visualforce page is that safe', 'community user sees a field they should not on a Visualforce page', 'view state encryption is that enough for sensitive data', 'how do I host an LWC inside a Visualforce page', 'apex:dynamicComponent and apex:actionFunction safe to keep'. NOT for greenfield Visualforce architecture (use apex/visualforce-fundamentals — controller types, view state pattern selection, PDF rendering); NOT for Visualforce email template authoring (use apex/visualforce-email-templates if/when that skill is authored); NOT for general Apex security review across triggers and async (use apex/soql-security and security/secure-coding-review-checklist).

transaction-security-policies

8
from PranavNagrecha/AwesomeSalesforceSkills

Transaction Security policy creation and configuration: condition builder, enhanced policies, enforcement actions (block, MFA, notification, end session), real-time monitoring mode, and policy troubleshooting. NOT for Event Monitoring log analysis or Shield Event Monitoring setup (use event-monitoring). NOT for Apex testing or debug-log analysis.

sso-saml-troubleshooting

8
from PranavNagrecha/AwesomeSalesforceSkills

Diagnosing broken SAML SSO into Salesforce — IdP-initiated vs SP-initiated flows, signing-certificate validity / expiry, NameID format mismatches, RelayState handling, audience / entityId / issuer mismatches, clock skew, the SAML Assertion Validator in Setup, the Login History debug log, and the My Domain prerequisite for SSO. Covers the standard diagnostic loop: read the SAML response, identify which check failed, fix at the IdP or SP. NOT for OAuth / OpenID Connect SSO (see security/oauth-openid-troubleshooting), NOT for setting up SSO from scratch (see security/sso-saml-setup).