grzmol/vibe-force/sf-async-apex-patterns

Claude Code and agent skill by grzmol/vibe-force

Trust tier 2
  • community
  • ext:[{"type":"hook","description":"Pre/post lifecycle hooks"}]
LLM review pending
Source check pending

Checking that the SKILL.md file is still in the repository.

Selects and implements the right Salesforce asynchronous execution model - Queueable Apex with Finalizers, Batch Apex, Apex Cursors, Schedulable Apex with CRON expressions, future methods, Platform Events, and Change Data Capture - and covers chaining limits, scope sizing, Database.Stateful, transaction boundaries, idempotency, duplicate delivery, and job monitoring or abort through AsyncApexJob and CronTrigger. Use this skill when work involves System.enqueueJob, System.attachFinalizer, Database.executeBatch, Database.getQueryLocator, Database.getCursor, System.schedule, System.scheduleBatch, System.abortJob, EventBus.publish, EventBus.RetryableException, setResumeCheckpoint, @future, BatchApexErrorEvent, ChangeEventHeader, a *__e platform event, a *ChangeEvent trigger, an AsyncApexJob or CronTrigger query, or when a long-running or high-volume process must move off the synchronous transaction.

Install

npx vskill@latest install grzmol/vibe-force/sf-async-apex-patterns

Semi-extensibleMentions customization, but needs skill-specific knowledge. Read the extensible skills standard

SKILL.md

The same SKILL.md was published earlier as grzmol/vibe-force/sf-async-apex-patterns.

Asynchronous Apex Patterns

When to use

Use this skill when a Salesforce requirement cannot finish inside one synchronous transaction: callouts from a trigger, data volumes above 50,000 query rows, scheduled maintenance, long-running integration work, or cross-system event propagation. It owns the choice of async mechanism and the correctness concerns that choice creates (retries, duplicate delivery, state, transaction boundaries).

Related skills: sf-apex-development (trigger/handler structure, with sharing, user mode), sf-apex-testing (all async test mechanics), sf-governor-limits (full per-transaction limit tables), sf-soql-sosl-optimization (query locator and cursor query tuning), sf-integration-patterns (callout design, Named Credentials), sf-debugging-logs (debug logs for async contexts), sf-deployment-strategies (deploying classes with pending scheduled jobs).

Decision table

Pick the leftmost row whose constraints all hold.

MechanismMax data reachStateCalloutsChainingTransaction boundaryChoose when
Queueable50,000 query rows per execution (50M rows with Database.Cursor)full object state; non-primitive members serializedyes, with Database.AllowsCallouts1 child per job; stack depth unlimited in prod, 5 in Developer/Trialone transaction per executedefault async choice; complex arguments; ordered steps; needs a job id
Queueable + Database.Cursor50M rows per cursorfullyesself re-enqueue per chunkone per chunklarge volume without consuming Batch Apex slots
Database.Batchable50M rows via QueryLocatoronly with Database.Stateful (instance members)yes, with Database.AllowsCallouts, 100 callouts per methodDatabase.executeBatch from finishone transaction per execute chunkrecord-set processing with per-chunk limit resets and per-chunk error isolation
Schedulabledelegatespersists between runs unless transientno synchronous calloutsschedules batch/queueablesynchronous limits applyclock-driven work; CRON schedule
@future50,000 query rowsnone; primitives and primitive collections onlyyes, with @future(callout=true)cannot call another futureone transactionlegacy only, or mixed-DML isolation. Salesforce recommends Queueable instead
Platform event (*__e)subscriber batch up to 2,000 messagesnoneno callouts from event triggerspublish from subscriberpublisher and subscriber are separate transactionsdecoupled fan-out, retry semantics, external subscribers
Change Data Capture (*ChangeEvent)1 event may carry many recordIdsnonenopublish from triggerchange event trigger runs after the DB transaction completesreplicate record deltas without writing publish code
Record-triggered flow async pathflow limitsflow variablesvia invocable actionsubflowruns immediately after the triggering save completesdeclarative async; see skill sf-flow-automation

Hard numbers behind the table: Queueable allows up to 50 System.enqueueJob calls per synchronous transaction but only 1 from an asynchronous transaction; Developer and Trial orgs cap the chained stack depth at 5 (the parent plus four children); Database.QueryLocator may return up to 50 million records and the job fails immediately above that; executeBatch scope caps at 2,000 with a QueryLocator and has no upper bound with an Iterable; five batch jobs may be queued or active at once with up to 100 more held in the Apex flex queue; 100 scheduled Apex jobs may exist at one time; every async execution counts against the shared org limit of 250,000 async executions per 24 hours or user licences x 200, whichever is greater.

Core patterns

1. Queueable with callouts, delay, and duplicate suppression
apex
public with sharing class SyncAccountQueueable implements Queueable, Database.AllowsCallouts {
private final List<Id> accountIds;
public SyncAccountQueueable(List<Id> accountIds) {
this.accountIds = accountIds;
}
public void execute(QueueableContext context) {
System.attachFinalizer(new SyncAccountFinalizer(context.getJobId(), accountIds));
List<Account> accounts = [
SELECT Id, Name, External_Id__c
FROM Account
WHERE Id IN :accountIds
WITH USER_MODE
];
HttpRequest request = new HttpRequest();
request.setEndpoint('callout:ERP_Named_Credential/accounts');
request.setMethod('POST');
request.setHeader('Content-Type', 'application/json');
request.setBody(JSON.serialize(accounts));
HttpResponse response = new Http().send(request);
if (response.getStatusCode() >= 300) {
throw new CalloutException('ERP sync failed: ' + response.getStatusCode());
}
}
}

Enqueue with a minimum delay (0-10 minutes, ignored in tests) and a duplicate signature so a second identical job is rejected with DuplicateMessageException:

apex
AsyncOptions options = new AsyncOptions();
options.MinimumQueueableDelayInMinutes = 2;
options.MaximumQueueableStackDepth = 10;
options.DuplicateSignature = QueueableDuplicateSignature.Builder()
.addString('SyncAccountQueueable')
.addId(UserInfo.getUserId())
.build();
try {
Id jobId = System.enqueueJob(new SyncAccountQueueable(accountIds), options);
} catch (DuplicateMessageException e) {
// An equivalent job is already enqueued. Nothing to do.
}

A queueable signature is cleared when the job is dequeued, so duplicates of an already running job are still possible. Treat the signature as contention control, not as an exactly-once guarantee.

2. Finalizer as the failure boundary
apex
public with sharing class SyncAccountFinalizer implements Finalizer {
private final Id originalJobId;
private final List<Id> accountIds;
public SyncAccountFinalizer(Id originalJobId, List<Id> accountIds) {
this.originalJobId = originalJobId;
this.accountIds = accountIds;
}
public void execute(FinalizerContext ctx) {
if (ctx.getResult() == ParentJobResult.SUCCESS) {
return;
}
insert as system new Integration_Error__c(
Job_Id__c = ctx.getAsyncApexJobId(),
Request_Id__c = ctx.getRequestId(),
Message__c = ctx.getException().getMessage()
);
// A finalizer may re-enqueue the failed job up to 5 consecutive times.
System.enqueueJob(new SyncAccountQueueable(accountIds));
}
}

The finalizer runs in its own Apex and database transaction, so DML buffered in the finalizer's state survives a queueable that blew its limits. Only one finalizer per queueable job; a finalizer may enqueue exactly one async job; the retry chain caps at 5 consecutive failures and resets on success.

3. Batch Apex with stateful aggregation and chaining
apex
public with sharing class ArchiveClosedCasesBatch
implements Database.Batchable<SObject>, Database.Stateful, Database.AllowsCallouts {
public Integer archived = 0;
public Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator(
'SELECT Id, Status FROM Case WHERE IsClosed = true AND ClosedDate < LAST_N_DAYS:365',
AccessLevel.USER_MODE
);
}
public void execute(Database.BatchableContext bc, List<Case> scope) {
List<Case_Archive__c> archives = new List<Case_Archive__c>();
for (Case c : scope) {
archives.add(new Case_Archive__c(Case_Id__c = c.Id));
}
Database.SaveResult[] results = Database.insert(archives, false, AccessLevel.USER_MODE);
for (Database.SaveResult r : results) {
if (r.isSuccess()) {
archived++;
}
}
}
public void finish(Database.BatchableContext bc) {
AsyncApexJob job = [
SELECT Status, NumberOfErrors, JobItemsProcessed, TotalJobItems
FROM AsyncApexJob
WHERE Id = :bc.getJobId()
WITH USER_MODE
];
if (job.NumberOfErrors == 0) {
Database.executeBatch(new PurgeArchivedCasesBatch(), 200);
}
}
}
apex
Id jobId = Database.executeBatch(new ArchiveClosedCasesBatch(), 200);

Only instance members survive between chunks under Database.Stateful; statics are reset. Use a scope size that is a factor of 2,000 (100, 200, 400...). Avoid relationship subqueries in the QueryLocator: a QueryLocator without subqueries uses the fast chunked implementation, while an Iterable or a subquery forces the slower non-chunking path. FOR UPDATE in the start query does not apply to Batch Apex; requery with FOR UPDATE inside execute when you need row locks.

4. Apex Cursor plus chained Queueable for high volume
apex
public with sharing class ContactPurgeCursorQueueable implements Queueable {
private final Database.Cursor cursor;
private Integer position;
public ContactPurgeCursorQueueable() {
this.cursor = Database.getCursor(
'SELECT Id FROM Contact WHERE LastActivityDate = LAST_N_DAYS:400',
AccessLevel.USER_MODE
);
this.position = 0;
}
private ContactPurgeCursorQueueable(Database.Cursor cursor, Integer position) {
this.cursor = cursor;
this.position = position;
}
public void execute(QueueableContext ctx) {
Integer remaining = cursor.getNumRecords() - position;
if (remaining <= 0) {
return;
}
List<Contact> chunk = (List<Contact>) cursor.fetch(position, Math.min(200, remaining));
delete as user chunk;
Integer next = position + chunk.size();
if (next < cursor.getNumRecords()) {
System.enqueueJob(new ContactPurgeCursorQueueable(cursor, next));
}
}
}

A cursor spans up to 50 million rows, allows at most 100 Cursor.fetch() calls per transaction, and each fetch counts against the SOQL query and query-row limits. Cursors consume no Batch Apex slots and never queue behind the flex queue. System.TransientCursorException is retryable; System.FatalCursorException is not.

5. Schedulable with CRON and one-shot batch scheduling
apex
public with sharing class NightlyArchiveScheduler implements Schedulable {
public void execute(SchedulableContext sc) {
Database.executeBatch(new ArchiveClosedCasesBatch(), 200);
}
}
apex
// Seconds Minutes Hours Day_of_month Month Day_of_week Optional_year
String cron = '0 0 2 * * ?'; // every day at 02:00 in the scheduling user's time zone
Id cronTriggerId = System.schedule('VF Nightly Archive', cron, new NightlyArchiveScheduler());
// One-shot batch 30 minutes from now, no Schedulable class required
Id oneShot = System.scheduleBatch(new ArchiveClosedCasesBatch(), 'VF Archive One Shot', 30, 200);

Job names must be unique or System.AsyncException: The Apex job named "..." is already scheduled for execution is thrown. Apex cannot be scheduled more often than hourly. Scheduled Apex runs under synchronous governor limits and cannot make synchronous web-service callouts - delegate callouts to Queueable or Batch with Database.AllowsCallouts.

6. Platform events with an idempotent subscriber

This is the start of the file. Read the full SKILL.md on GitHub.

Security

  • Security scanPassed, 100 of 100Pattern checks on the skill's files.
  • Model reviewNot runA model review is scheduled for the next rescan.

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

7-day trend score
0

Not refreshed yet.

Extension points

  • hookPre/post lifecycle hooks

Works with

Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.

  • Claude Code
  • Cursor
  • GitHub Copilot
  • Windsurf
  • Codex
  • Gemini CLI
  • Cline
  • Amp
  • Roo Code
  • Goose
  • Continue
  • Kilo Code
  • Junie
  • Trae
  • OpenHands
  • Qwen Code
  • AI Agent
  • Tabnine Chat
  • Sourcegraph Cody
  • Amazon Q
  • Firebase Genkit
  • Sweep
  • Devin
  • Phind
  • Mentat
  • Claude Desktop
  • Aider
  • GPT Pilot
  • Plandex
  • bolt.new
  • v0
  • Replit Agent
  • Anse
  • TypingMind
  • BetterChatGPT
  • LibreChat
  • Warp AI
  • Pieces
  • Fig AI
Embed badge
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/grzmol/vibe-force/sf-async-apex-patterns/badge)](https://verified-skill.com/skills/grzmol/vibe-force/sf-async-apex-patterns)

Something wrong with this skill or its page? Tell us.