An Account trigger enqueues an ERP credit-limit sync every time the limit changes. Then a data load sends the same Accounts through in several chunks, a sales rep saves twice, and the integration user retries an update that timed out. The ERP now receives three identical calls for one change. AsyncOptions.DuplicateSignature stops most of this at enqueue time, with one gap: it only compares against jobs still waiting in the queue, so you also need a guard inside the job for the ones already running.
Where the duplicates come from, and the 50-job ceiling
If you need the interface itself first, read Queueable Apex basics. The usual first version of the trigger looks like this:
trigger AccountCreditSync on Account (after update) {
for (Account acc : Trigger.new) {
if (acc.Credit_Limit__c != Trigger.oldMap.get(acc.Id).Credit_Limit__c) {
System.enqueueJob(new ErpCreditSyncJob(acc.Id)); // one job per changed Account
}
}
}
Several paths run it more than once for the same Account:
- A workflow field update or a recursive update re-fires the after-update trigger in the same transaction. On a workflow re-fire,
Trigger.oldMapstill holds the original values, so the comparison passes again. - A bulk load arrives in 200-record chunks, and the same Account appears in more than one file or batch.
- Two users, or a user and an integration, save the same record seconds apart. Each save runs in its own transaction.
- Middleware retries a request it thinks failed, after the first attempt has already committed.
Each path creates a separate job, and each job makes its own callout, so one credit-limit change can reach the ERP several times. For a call that only sets a value, that wastes callouts. For a call that creates something, such as a credit review case, every duplicate creates another record.
A synchronous transaction can add at most 50 jobs with System.enqueueJob, so this trigger also fails outright on any chunk with more than 50 credit-limit changes. The 51st call throws System.LimitException: Too many queueable jobs added to the queue: 51, no catch block can handle it, and the whole chunk rolls back. A signature cannot prevent this, because every per-record signature is different.
Instead of enqueuing per record, have the before-update branch flag the changed Accounts, which needs no DML because it edits Trigger.new in place. The after-update branch makes one call, whatever the chunk size:
trigger AccountCreditSync on Account (before update, after update) {
if (Trigger.isBefore) {
for (Account acc : Trigger.new) {
if (acc.Credit_Limit__c != Trigger.oldMap.get(acc.Id).Credit_Limit__c) {
acc.Needs_ERP_Sync__c = true;
}
}
return;
}
for (Account acc : Trigger.new) {
if (acc.Needs_ERP_Sync__c) {
ErpCreditSyncEnqueuer.enqueueSweep(); // one call per chunk at most
break;
}
}
}
The job carries no Ids. It reads every Account with Needs_ERP_Sync__c = true when it runs, so one queued sweep covers every change made before it starts.
Build a signature that names the work
A duplicate signature is a short byte string that the platform compares when you enqueue a job. You build it with QueueableDuplicateSignature.Builder: chain addString, addId and addInteger, then call build().
The right key depends on what the job carries. A job built around one record wants the purpose string plus that record's Id, because two Accounts are two pieces of work. A sweep carries no Ids, so the purpose string alone is correct: a queued sweep already covers every flagged Account, and a second one would add nothing. Leave out anything that changes between enqueues (the new credit limit, a timestamp, Crypto.getRandomInteger(), a counter). Signatures that never match never block anything, and no error tells you.
public without sharing class ErpCreditSyncJob implements Queueable, Database.AllowsCallouts {
@TestVisible static final String PURPOSE = 'ERP_CREDIT_SYNC';
@TestVisible static final Integer BATCH_SIZE = 100; // one callout per Account, 100 per transaction
public static QueueableDuplicateSignature signature() {
return new QueueableDuplicateSignature.Builder()
.addString(PURPOSE)
.build();
}
public void execute(QueueableContext ctx) {
// Shown in the running-job section below.
}
}
Signatures have a size limit measured in bytes. The Builder documentation does not publish the number, so read it at runtime with getMaxSize(). getSize() reports what you have used and getRemainingSize() what is left. If part of a key has a variable length, such as a list of sales regions for a quota recalculation job, check the remaining budget and fall back to a digest:
QueueableDuplicateSignature.Builder sig = new QueueableDuplicateSignature.Builder()
.addString('REGION_QUOTA_RECALC');
List<String> regions = new List<String>(regionCodes);
regions.sort(); // same set, same order, same signature
String regionKey = String.join(regions, ',');
if (Blob.valueOf(regionKey).size() > sig.getRemainingSize()) {
regionKey = EncodingUtil.convertToHex(
Crypto.generateDigest('SHA-256', Blob.valueOf(regionKey)));
}
sig.addString(regionKey);
QueueableDuplicateSignature signature = sig.build();
The UTF-8 length only estimates how the builder counts a string, so leave headroom. The hex digest is 64 characters, so make sure the remaining size can hold it before you rely on the fallback. Without the sort, EMEA,APAC and APAC,EMEA produce different signatures for the same work.
Enqueue once and treat DuplicateMessageException as success
Assign the signature to the DuplicateSignature property of an AsyncOptions instance and pass both to System.enqueueJob. If a job with the same signature is already enqueued, the call throws DuplicateMessageException.
public with sharing class ErpCreditSyncEnqueuer {
private static Boolean sweepRequested = false;
public static void enqueueSweep() {
if (sweepRequested) {
return;
}
if (Limits.getQueueableJobs() >= Limits.getLimitQueueableJobs()) {
return; // flags stay set; the next sweep picks these Accounts up
}
AsyncOptions opts = new AsyncOptions();
opts.DuplicateSignature = ErpCreditSyncJob.signature();
try {
System.enqueueJob(new ErpCreditSyncJob(), opts);
} catch (DuplicateMessageException e) {
System.debug(LoggingLevel.INFO,
'ERP credit sync already queued, signature ' + opts.DuplicateSignature.toString());
}
sweepRequested = true;
}
}
The exception means the work you asked for is already waiting to run, so log it and carry on. Rethrowing it inside a trigger rolls back the user's save to guard against a job that already exists. toString() is the only method on QueueableDuplicateSignature, and putting its output in the log line lets you match a rejected enqueue to the accepted job.
The static Boolean stops repeat calls, because one Apex DML statement on 1,000 Accounts fires the trigger five times in a single transaction. If other code has already used the Queueable allowance (inside an async job it is 1), the Limits check returns early and the flags wait for the next sweep.
When an enqueue is rejected, the queued job wins and the newer request is discarded. For the sweep, nothing is lost. The queued sweep has not run its query yet, so it finds the Account the rejected request flagged and sends the current credit limit. A job that copied field values into its constructor would send stale data in the same situation.
AsyncOptions also has MaximumQueueableStackDepth and MinimumQueueableDelayInMinutes. A one-minute delay lets more changes collapse into each sweep during a data load, and every sync then arrives a minute later.
Close the running-job gap
The platform removes the signature from a job when it is first dequeued. A running job therefore has no signature, and a new enqueue that would have matched it succeeds. Salesforce says this guarantees that at least one job for a given signature runs. Treat that as a minimum with no upper limit. A typical sequence: sweep A is dequeued and starts its callouts, a user edits a credit limit, the trigger flags the Account and enqueues sweep B, and the platform accepts B. B runs after A, or alongside it.
Make the sweep idempotent
public void execute(QueueableContext ctx) {
List<Account> flagged = [
SELECT Id, ERP_Customer_No__c, Credit_Limit__c, Last_ERP_Sync_Hash__c
FROM Account
WHERE Needs_ERP_Sync__c = true
ORDER BY Id
LIMIT :BATCH_SIZE
];
Map<Id, String> sent = new Map<Id, String>();
for (Account acc : flagged) {
String hash = payloadHash(acc);
if (hash != acc.Last_ERP_Sync_Hash__c) {
ErpClient.putCreditLimit(acc.ERP_Customer_No__c, acc.Credit_Limit__c);
}
sent.put(acc.Id, hash);
}
// Every callout is done. DML starts here.
List<Account> updates = new List<Account>();
for (Account cur : [
SELECT Id, ERP_Customer_No__c, Credit_Limit__c
FROM Account WHERE Id IN :sent.keySet() FOR UPDATE
]) {
Account upd = new Account(Id = cur.Id, Last_ERP_Sync_Hash__c = sent.get(cur.Id));
if (payloadHash(cur) == sent.get(cur.Id)) {
upd.Needs_ERP_Sync__c = false; // unchanged since this sweep read it
}
updates.add(upd);
}
update updates;
if (flagged.size() == BATCH_SIZE) {
ErpCreditSyncEnqueuer.enqueueSweep(); // more flagged Accounts may be waiting
}
}
@TestVisible
static String payloadHash(Account acc) {
Decimal amount = acc.Credit_Limit__c == null ? null : acc.Credit_Limit__c.setScale(2);
String payload = acc.ERP_Customer_No__c + '|' + String.valueOf(amount);
return EncodingUtil.convertToHex(
Crypto.generateDigest('SHA-256', Blob.valueOf(payload)));
}
The hash check skips any Account whose current payload the ERP already accepted, so B does nothing for records A has sent. All callouts happen before the first DML statement, because Apex does not allow a callout after uncommitted DML, and LIMIT 100 keeps the sweep within 100 callouts per transaction. The setScale(2) keeps an in-memory 75000 and a queried 75000.00 from hashing differently.
The flag is cleared only where the re-queried Account still produces the hash A sent. If a user changed the credit limit while A was mid-callout, A stores what it sent but leaves the flag set, and B (enqueued by that edit) sends the new value. Without the re-check, A would clear a flag it never acted on, and B's query would not find the record.
If A and B read the same flagged record before either writes the hash, both call the ERP. For a "set the credit limit to X" call that is harmless, because the second call writes the same value. Here idempotency is enough, and this is where I would stop. The chained sweep at the end of execute() carries the same signature as A and is accepted, since A no longer holds one while it runs.
Use a lock record when the side effect cannot repeat
Some calls create something, such as a credit review case in the ERP when a limit crosses a threshold. A hash cannot make that safe, because a second call creates a second case. Take a lock that both queued and running jobs respect: a custom object Async_Lock__c with a text field Lock_Key__c marked Unique and External ID, plus a datetime Acquired_At__c.
The lock must be committed before the protected work starts, and inserting it inside the job would put uncommitted DML ahead of the callout. So acquire the locks in the trigger transaction and enqueue one job for every Id that won:
public with sharing class CreditReviewLocks {
public static String keyFor(Id accId) {
return 'ERP_CREDIT_REVIEW:' + accId;
}
public static Set<Id> acquire(List<Id> accountIds) {
List<Async_Lock__c> locks = new List<Async_Lock__c>();
for (Id accId : accountIds) {
locks.add(new Async_Lock__c(Lock_Key__c = keyFor(accId), Acquired_At__c = System.now()));
}
Set<Id> won = new Set<Id>();
Database.SaveResult[] results = Database.insert(locks, false);
for (Integer i = 0; i < results.size(); i++) {
if (results[i].isSuccess()) {
won.add(accountIds[i]);
} else if (results[i].getErrors()[0].getStatusCode() != StatusCode.DUPLICATE_VALUE) {
throw new DmlException(results[i].getErrors()[0].getMessage());
}
}
return won; // DUPLICATE_VALUE means a review is queued or running for that Account
}
}
public with sharing class CreditReviewEnqueuer {
static final Decimal REVIEW_THRESHOLD = 1000000;
// Called once from the trigger's after-update branch.
public static void onAfterUpdate(List<Account> rows, Map<Id, Account> oldMap) {
List<Id> crossed = new List<Id>();
for (Account acc : rows) {
Decimal previous = oldMap.get(acc.Id).Credit_Limit__c;
if (acc.Credit_Limit__c >= REVIEW_THRESHOLD
&& (previous == null || previous < REVIEW_THRESHOLD)) {
crossed.add(acc.Id);
}
}
if (crossed.isEmpty()) {
return;
}
Set<Id> won = CreditReviewLocks.acquire(crossed);
if (!won.isEmpty()) {
System.enqueueJob(new CreditReviewJob(won)); // one job for the whole chunk
}
}
}
The job attaches a Finalizer first and sends the whole set in one bulk callout, so a 200-record chunk costs one job and one callout:
public with sharing class CreditReviewJob implements Queueable, Database.AllowsCallouts {
private final Set<Id> accountIds;
public CreditReviewJob(Set<Id> accountIds) { this.accountIds = accountIds; }
public void execute(QueueableContext ctx) {
System.attachFinalizer(new CreditReviewLockRelease(accountIds));
List<String> customerNos = new List<String>();
for (Account acc : [SELECT ERP_Customer_No__c FROM Account WHERE Id IN :accountIds]) {
customerNos.add(acc.ERP_Customer_No__c);
}
ErpClient.openCreditReviews(customerNos);
}
}
public class CreditReviewLockRelease implements Finalizer {
private final Set<Id> accountIds;
public CreditReviewLockRelease(Set<Id> accountIds) { this.accountIds = accountIds; }
public void execute(FinalizerContext ctx) {
List<String> keys = new List<String>();
for (Id accId : accountIds) {
keys.add(CreditReviewLocks.keyFor(accId));
}
delete [SELECT Id FROM Async_Lock__c WHERE Lock_Key__c IN :keys];
if (ctx.getResult() == ParentJobResult.UNHANDLED_EXCEPTION) {
System.debug(LoggingLevel.ERROR,
'Credit review failed for ' + keys + ': ' + ctx.getException().getMessage());
}
}
}
The locks are released whether the job succeeds or throws. If the trigger transaction rolls back, the lock inserts and the enqueue roll back with it. The cost is lost updates: an edit that arrives while the review runs finds the lock held and enqueues nothing. If that matters, have the Finalizer re-check the Accounts after releasing the locks and enqueue a follow-up job.
| Approach | Queued duplicates | Running duplicates | Extra cost | Failure mode |
|---|---|---|---|---|
| Per-record enqueue with signatures | Rejected at enqueue | Accepted and run | One job per record | LimitException at 51 jobs rolls back the chunk |
| Flag and one purpose-keyed sweep | Rejected; the queued sweep covers them | Accepted, then skipped per record by the hash | A checkbox, a hash field, one re-query | Exact overlap can repeat a set-value call |
| Lock record and Finalizer | Never enqueued | Never enqueued | Lock DML, a custom object, cleanup | A stale lock blocks work until removed |
My default is to flag the records, enqueue one purpose-keyed sweep per transaction, and make execute() idempotent. I add a lock record only for side effects that create something.
Testing it
How DuplicateSignature behaves inside Apex test context is not documented and not yet confirmed, so no test here depends on a second enqueue throwing. The tests assume ErpClient makes its callouts with HttpRequest:
@IsTest
private class ErpCreditSyncTest {
static Integer calls = 0;
private class CountingErpMock implements HttpCalloutMock {
public HttpResponse respond(HttpRequest req) {
calls++;
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
return res;
}
}
@IsTest
static void signatureLeavesHeadroom() {
QueueableDuplicateSignature.Builder b = new QueueableDuplicateSignature.Builder()
.addString(ErpCreditSyncJob.PURPOSE);
Assert.areEqual(b.getMaxSize() - b.getSize(), b.getRemainingSize());
Assert.isTrue(b.getRemainingSize() > 0, 'Key leaves no room for growth');
}
@IsTest
static void unchangedPayloadSkipsCallout() {
Account acc = new Account(Name = 'Idem Co', ERP_Customer_No__c = 'C-1001',
Credit_Limit__c = 50000, Needs_ERP_Sync__c = true);
acc.Last_ERP_Sync_Hash__c = ErpCreditSyncJob.payloadHash(acc);
insert acc;
Test.setMock(HttpCalloutMock.class, new CountingErpMock());
Test.startTest();
System.enqueueJob(new ErpCreditSyncJob());
Test.stopTest();
Assert.areEqual(0, calls, 'Unchanged payload should not reach the ERP');
Assert.isFalse([SELECT Needs_ERP_Sync__c FROM Account WHERE Id = :acc.Id].Needs_ERP_Sync__c);
}
@IsTest
static void changedPayloadCallsOnce() {
Account acc = new Account(Name = 'Change Co', ERP_Customer_No__c = 'C-1002',
Credit_Limit__c = 75000, Needs_ERP_Sync__c = true, Last_ERP_Sync_Hash__c = 'stale');
insert acc;
Test.setMock(HttpCalloutMock.class, new CountingErpMock());
Test.startTest();
System.enqueueJob(new ErpCreditSyncJob());
Test.stopTest();
Account synced = [SELECT Last_ERP_Sync_Hash__c, Needs_ERP_Sync__c FROM Account WHERE Id = :acc.Id];
Assert.areEqual(1, calls, 'Changed payload should reach the ERP once');
Assert.areEqual(ErpCreditSyncJob.payloadHash(acc), synced.Last_ERP_Sync_Hash__c);
Assert.isFalse(synced.Needs_ERP_Sync__c, 'Flag should clear after a clean sync');
}
@IsTest
static void bulkChangeEnqueuesOneSweep() {
List<Account> accs = new List<Account>();
for (Integer i = 0; i < 80; i++) {
accs.add(new Account(Name = 'Bulk ' + i, ERP_Customer_No__c = 'B-' + i, Credit_Limit__c = 10000));
}
insert accs;
for (Account a : accs) {
a.Credit_Limit__c = 20000;
}
Test.setMock(HttpCalloutMock.class, new CountingErpMock());
Test.startTest();
update accs; // 80 changes: the per-record trigger would throw at job 51
Assert.areEqual(1, Limits.getQueueableJobs(), 'One sweep per transaction');
Test.stopTest();
Assert.areEqual(80, calls, 'The sweep should sync every flagged Account');
}
@IsTest
static void heldLockBlocksSecondAcquire() {
Account acc = new Account(Name = 'Lock Co');
insert acc;
insert new Async_Lock__c(Lock_Key__c = CreditReviewLocks.keyFor(acc.Id), Acquired_At__c = System.now());
Set<Id> won = CreditReviewLocks.acquire(new List<Id>{ acc.Id });
Assert.isTrue(won.isEmpty(), 'A held lock must not be acquired twice');
}
}
The bulk test uses 80 records: past the 50-job line, but under one sweep's BATCH_SIZE, so it does not depend on chaining. To see real duplicate rejection, use a sandbox. Run this snippet twice, as two separate Execute Anonymous calls within the same minute:
AsyncOptions opts = new AsyncOptions();
opts.DuplicateSignature = ErpCreditSyncJob.signature();
opts.MinimumQueueableDelayInMinutes = 1;
try {
System.enqueueJob(new ErpCreditSyncJob(), opts);
System.debug('enqueued');
} catch (DuplicateMessageException e) {
System.debug('rejected as duplicate: ' + opts.DuplicateSignature.toString());
}
The accepted job still runs after the delay and calls the ERP for any flagged Accounts, so point ErpClient at a test endpoint or clear the flags first.
The second run should log the rejection. Confirm that only one job exists:
SELECT Id, Status, CreatedDate
FROM AsyncApexJob
WHERE ApexClass.Name = 'ErpCreditSyncJob'
ORDER BY CreatedDate DESC
LIMIT 5
What to watch for
- If a signature contains a timestamp or a random value, it never matches anything, and the guard fails without any error.
- The review enqueuer adds one job per 200-record chunk on top of the sweep. If that path sees very large Apex DML statements, move it to flag-and-sweep as well, and check
Limits.getQueueableJobs()before any extra trigger-driven enqueue. - When the
Limitsguard skips a sweep, flagged Accounts wait until another credit-limit change enqueues one. A scheduled job that callsenqueueSweep()every hour caps that wait. - A callout that throws fails the whole sweep, and
ORDER BY Idputs the same record first next time. Catch errors per record, clear that record's flag, and log the failure for a person to retry. - If a job is aborted before it starts, it never attaches its Finalizer, so its locks stay in place. Use
Acquired_At__cand a scheduled cleanup that deletes locks older than your longest expected run. - A broad
catch (Exception e)around the enqueue hides real failures along with the expected duplicate. CatchDuplicateMessageExceptionby name.
Leave a Comment