batch-apex-patterns

Use when designing, reviewing, or debugging Batch Apex contracts, scope sizing, stateful behavior, chaining, and AsyncApexJob monitoring. Triggers: 'Database.Batchable', 'Database.Stateful', 'executeBatch', 'batch scope', 'AsyncApexJob'. NOT for generic async choice discussions where Queueable or Future might still be the better tool.

Best use case

batch-apex-patterns is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

Use when designing, reviewing, or debugging Batch Apex contracts, scope sizing, stateful behavior, chaining, and AsyncApexJob monitoring. Triggers: 'Database.Batchable', 'Database.Stateful', 'executeBatch', 'batch scope', 'AsyncApexJob'. NOT for generic async choice discussions where Queueable or Future might still be the better tool.

Teams using batch-apex-patterns 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/batch-apex-patterns/SKILL.md --create-dirs "https://raw.githubusercontent.com/PranavNagrecha/AwesomeSalesforceSkills/main/skills/apex/batch-apex-patterns/SKILL.md"

Manual Installation

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

How batch-apex-patterns Compares

Feature / Agentbatch-apex-patternsStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

Use when designing, reviewing, or debugging Batch Apex contracts, scope sizing, stateful behavior, chaining, and AsyncApexJob monitoring. Triggers: 'Database.Batchable', 'Database.Stateful', 'executeBatch', 'batch scope', 'AsyncApexJob'. NOT for generic async choice discussions where Queueable or Future might still be the better tool.

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

Use this skill when Queueable is no longer enough and the workload genuinely needs chunked processing across many transactions. Batch Apex is powerful because each `execute()` scope receives fresh limits, but that same power introduces lifecycle, state, chaining, and monitoring choices that teams routinely under-design.

## Before Starting

- Will the record volume exceed what one Queueable or synchronous transaction should safely handle?
- Does the job need `Database.getQueryLocator()`, custom iterable input, callouts, or cross-scope state?
- How will operations know the batch succeeded, partially failed, or should be retried?

## Core Concepts

### `start`, `execute`, And `finish` Are Separate Responsibilities

`start` defines the workload, `execute` processes each scope, and `finish` handles summary or follow-up actions. Treating them as one blurred method creates monitoring and retry pain. Keep `start` lightweight, `execute` idempotent, and `finish` focused on reporting or safe handoff.

### Scope Size Is A Throughput Tradeoff

The default batch size is commonly 200, but that is not always optimal. Large scopes can increase throughput for simple DML work. Smaller scopes may be safer for heavy processing or callouts. Scope sizing is a performance choice tied to payload weight, lock contention, and external system tolerance.

### `Database.Stateful` Is Useful But Not Free

Stateful batch classes retain instance state between `execute()` calls. That is useful for counters, failed IDs, and summary metrics, but it also means more serialization overhead. Use it when the accumulated state changes the outcome or the reporting story, not by default.

### `AsyncApexJob` Is Part Of The Pattern

Operationally, a batch job is not complete just because `Database.executeBatch()` returned an ID. Job status, processed counts, and error counts live in `AsyncApexJob`, and serious batch designs account for that from the start.

## Common Patterns

### QueryLocator Batch For Large Record Sets

**When to use:** Salesforce data volume is large and query-driven.

**How it works:** Use `Database.getQueryLocator()` in `start()`, process a scope at a time in `execute()`, and monitor the resulting job.

**Why not the alternative:** Direct list loading in one transaction defeats the point of Batch Apex.

### Stateful Error Accumulation

**When to use:** The team needs final counts, failed IDs, or summary reporting after all scopes finish.

**How it works:** Add `Database.Stateful` and store lightweight counters or IDs only.

### Dispatch Follow-Up Work In `finish()`

**When to use:** Another batch, Queueable, or notification should happen only after the batch completes.

**How it works:** Query `AsyncApexJob` or accumulated counters in `finish()`, then launch the next safe step.

## Decision Guidance

| Situation | Recommended Approach | Reason |
|---|---|---|
| Very large Salesforce record set must be processed safely | QueryLocator Batch | Fresh limits per scope and large-volume support |
| Need only simple after-save async work for a modest set of records | Not Batch; prefer Queueable | Lower framework overhead |
| Need summary counters across all scopes | `Database.Stateful` | Keeps lightweight cross-scope state |
| Need post-completion reporting or next-stage dispatch | `finish()` + `AsyncApexJob` data | Clear completion boundary |


## 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

- [ ] Batch is used because scale or chunking is truly required.
- [ ] `start()` is lightweight and suitable for the expected record volume.
- [ ] `execute()` is idempotent and safe to retry in part.
- [ ] Scope size is a deliberate choice, not a default carried forward blindly.
- [ ] `Database.Stateful` is used only when cross-scope state is genuinely needed.
- [ ] Monitoring or summary behavior uses `AsyncApexJob` or equivalent visibility.

## Salesforce-Specific Gotchas

1. **Each `execute()` scope gets fresh limits, but `Database.Stateful` still carries serialization cost** — do not store large collections casually.
2. **Callout-enabled batches still need `Database.AllowsCallouts`** — forgetting it breaks valid designs.
3. **A batch job ID is not observability by itself** — you still need job status and error interpretation.
4. **Tests need `Test.stopTest()` for batch completion** — otherwise assertions can run before the batch executes.

## Output Artifacts

| Artifact | Description |
|---|---|
| Batch design review | Findings on lifecycle, state, scope size, and monitoring |
| Batch decision guide | Recommendation for when Batch is justified and how to size and monitor it |
| Batch scaffold | Pattern for `start`, `execute`, `finish`, optional state, and summary behavior |

## Related Skills

- `apex/async-apex` — use when the real design question is whether Batch is needed at all.
- `apex/debug-and-logging` — use when Batch supportability and job diagnostics are the main pain.
- `apex/apex-cpu-and-heap-optimization` — use when the batch already exists and the bottleneck is CPU or heap within `execute()`.

Related Skills

mfa-enforcement-patterns

8
from PranavNagrecha/AwesomeSalesforceSkills

Design MFA enforcement: auto-enablement, Salesforce Authenticator rollout, exceptions, service accounts, API-only users, SSO interop, and audit. Trigger keywords: MFA, multi-factor, two-factor, Salesforce Authenticator, MFA exception, MFA SSO, api-only MFA. Does NOT cover: end-user password policies, device-trust posture, or non-Salesforce IdP configuration.

encrypted-field-query-patterns

8
from PranavNagrecha/AwesomeSalesforceSkills

Design SOQL, filters, reporting, and indexes against Shield Platform Encryption fields. Trigger keywords: Shield Platform Encryption, encrypted field query, probabilistic vs deterministic encryption, encrypted SOQL filter, encrypted field index. Does NOT cover: Classic Encryption (deprecated), field-level security policy, or tenant secret key rotation.

apex-managed-sharing-patterns

8
from PranavNagrecha/AwesomeSalesforceSkills

Grant row-level access programmatically via __Share records when declarative sharing rules cannot express the policy. NOT for OWD, role hierarchy, or criteria-based sharing rule design.

omnistudio-testing-patterns

8
from PranavNagrecha/AwesomeSalesforceSkills

Use when testing or validating OmniStudio components — OmniScript preview, Integration Procedure step debugging, DataRaptor field-mapping validation, and end-to-end UTAM-based automation. NOT for Apex unit testing or standard Flow debugging.

omnistudio-error-handling-patterns

8
from PranavNagrecha/AwesomeSalesforceSkills

Use when designing fault behavior across Integration Procedures, DataRaptors, OmniScripts, and FlexCards — error routing, user-facing messaging, retry semantics, and idempotency. Triggers: 'omnistudio error', 'integration procedure fault', 'dataraptor error handling', 'omniscript retry', 'flexcard action failure'. NOT for general Apex exception design or Flow fault paths.

omnistudio-ci-cd-patterns

8
from PranavNagrecha/AwesomeSalesforceSkills

Use when designing or implementing CI/CD pipelines for OmniStudio components — DataPack export/import, versioning, environment promotion, and automated deployment. NOT for standard Salesforce metadata CI/CD or Apex-only pipelines.

omniscript-design-patterns

8
from PranavNagrecha/AwesomeSalesforceSkills

Use when designing or reviewing OmniScripts for guided experiences, step structure, branching, save/resume, and the boundary between OmniScript, Integration Procedures, DataRaptors, and custom LWCs. Triggers: 'omniscript design', 'too many steps in omniscript', 'save and resume omniscript', 'branching in omniscript', 'when should this be an integration procedure'. NOT for deep Integration Procedure or DataRaptor design when the guided interaction layer is not the main concern.

integration-procedure-cacheable-patterns

8
from PranavNagrecha/AwesomeSalesforceSkills

Use when designing Integration Procedures (IPs) with platform cache to cut latency and callout load. Covers cache key design, TTL selection, per-user vs org-wide partitions, invalidation on data changes, and safe fallback on cache miss/stale. Does NOT cover general IP authoring (see omnistudio-error-handling-patterns) or LWC client-side caching.

flexcard-design-patterns

8
from PranavNagrecha/AwesomeSalesforceSkills

Use when designing, building, or reviewing OmniStudio FlexCards — including data source selection, card states, actions, conditional visibility, flyout configuration, and child card iteration. Triggers: 'FlexCard', 'card template', 'flyout', 'card action', 'card state', 'data source', 'child card', 'conditional visibility'. NOT for OmniScript design, standalone LWC development, or Apex controller architecture outside the FlexCard context.

dataraptor-patterns

8
from PranavNagrecha/AwesomeSalesforceSkills

Use when designing or reviewing OmniStudio DataRaptors, especially Extract versus Turbo Extract versus Transform versus Load, field mapping strategy, performance tradeoffs, and when to move work into Integration Procedures or Apex. Triggers: 'DataRaptor Extract', 'Turbo Extract', 'DataRaptor Load', 'DataRaptor Transform', 'OmniStudio data mapping'. NOT for overall OmniScript journey design or Integration Procedure sequencing when the main question is not the DataRaptor shape itself.

wire-service-patterns

8
from PranavNagrecha/AwesomeSalesforceSkills

Use when designing or reviewing Lightning Web Components that use `@wire`, Lightning Data Service, UI API, or the GraphQL wire adapter, especially for reactive parameters, cache behavior, and refresh strategy. Triggers: 'wire service', 'refreshApex', 'reactive parameter', 'getRecord', 'wire vs imperative Apex'. NOT for component communication or generic lifecycle issues when data provisioning is not the main concern.

message-channel-patterns

8
from PranavNagrecha/AwesomeSalesforceSkills

Use when implementing Lightning Message Service (LMS) to enable cross-DOM communication between LWC, Aura, and Visualforce components on the same Lightning page, using message channels. Triggers: 'communicate between unrelated LWC components', 'send data between Visualforce and LWC', 'lightning message service not working', 'APPLICATION_SCOPE vs default scope', 'message channel metadata deployment'. NOT for parent-child component communication (use component-communication) or server-side events.