ApexSensei

Drills › Work in the background

Make a Queueable retry idempotent

Work in the background · Advanced · 25 min · Runs in your Salesforce Developer org · Apex Path

Scenario. An integration may send the same request again, sometimes much later. The background job must never repeat work it already did.

Keep every applied operation key on the record so a Queueable retry, even a late one, never applies the same work twice.

What you will learn

A retry is idempotent when running it twice has the same effect as once. Keep every key you applied, not just the last.

Set<String> applied = new Set<String>();
if (String.isNotBlank(account.Description)) {
    applied.addAll(account.Description.split(';'));
}
if (applied.contains(key)) continue;
account.Description = String.isBlank(account.Description)
    ? key : account.Description + ';' + key;

Gotcha. Match whole keys with a Set: 'SYNC-42'.contains('SYNC-4') is true.

The task

Complete the Queueable so each operation key adds 1 to an Account's NumberOfEmployees at most once, even when an old key comes back late.

Examples:

  • Description empty, key SYNC-42 → Description SYNC-42, count 1
  • Description SYNC-42;SYNC-43, key SYNC-42 → nothing changes
  • Description SYNC-42, key SYNC-4 → Description SYNC-42;SYNC-4, count 2

Requirements:

  1. Treat Description as the list of applied keys, joined with ;.
  2. Split it into a Set<String> and skip the Account when the set has the key.
  3. Otherwise add ; and the key to the end (just the key when Description is blank), and add 1 to NumberOfEmployees (null counts as 0).
  4. Update only the changed Accounts, with one DML statement. Do nothing for an empty Id set.

Starter code

public class AS_F101E8C41745_IdempotentSyncJob implements Queueable {
    private Set<Id> accountIds;
    private String operationKey;

    public AS_F101E8C41745_IdempotentSyncJob(Set<Id> accountIds, String operationKey) {
        this.accountIds = accountIds;
        this.operationKey = operationKey;
    }

    public void execute(QueueableContext context) {
    }
}

When it passes

A new key adds 1 once. A repeated key, whether it comes right away or after other keys, changes nothing. A key that only looks like an old one still counts as new, and 200 Accounts update in one DML statement.

Try this drill free

You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.

‹ Schedule an Account review