Processing Saved Webhook Payloads with Retries

In my last post the webhook listener only saved payloads. Here's the other half: a batch that works through them, retries failures a limited number of times, and leaves a clear record when something can't be processed.

It picks up logs marked "New", plus anything marked "Failed" that hasn't run out of retries. Each log gets its own savepoint, so a bad payload rolls back only its own work and the rest of the batch keeps going. The log keeps the error message and an attempt counter. After the third failure it stops retrying and waits for a person to look at it.

public class webhookLogProcessor implements Database.Batchable<SObject>, Schedulable {

    public static final Integer MAX_ATTEMPTS = 3; //after this, a person needs to look at it

    public Database.QueryLocator start(Database.BatchableContext context) {
        return Database.getQueryLocator([
            SELECT Id, Request__c, Attempts__c
            FROM Webhook_Log__c
            WHERE Direction__c = 'Inbound'
            AND (Status__c = 'New' OR (Status__c = 'Failed' AND Attempts__c < :MAX_ATTEMPTS))
            ORDER BY CreatedDate //oldest first - webhook events often depend on each other
        ]);
    }

    public void execute(Database.BatchableContext context, List<Webhook_Log__c> logs) {
        for (Webhook_Log__c log : logs) {
            Savepoint sp = Database.setSavepoint(); //a bad payload only rolls back its own work
            try {
                Map<String, Object> event = (Map<String, Object>)JSON.deserializeUntyped(log.Request__c); //the raw payload saved by the listener
                webhookRouter.route((String)event.get('trigger'), event); //hand off to the logic for that event type
                log.Status__c = 'Processed';
                log.Error__c = null; //clear any error from an earlier attempt
            } catch (Exception e) {
                Database.rollback(sp); //undo whatever the router did for this payload
                log.Status__c = 'Failed';
                log.Attempts__c = (log.Attempts__c == null ? 0 : log.Attempts__c) + 1;
                log.Error__c = (e.getTypeName() + ': ' + e.getMessage()).left(255);
            }
        }
        Database.update(logs, false); //record the outcome of every log, even if one update fails
    }

    public void finish(Database.BatchableContext context) {}

    //lets the same class be scheduled
    public void execute(SchedulableContext context) {
        Database.executeBatch(new webhookLogProcessor(), 50); //small batches - see the notes below
    }
}

Some things I learned along the way:

  • Keep the batch size small. Each savepoint counts against the DML statement limit, and so does whatever the router does. Fifty at a time leaves room.
  • Order matters. Systems often send related events close together (created, then renamed, then moved). Processing oldest first avoids applying them out of order, at least within a batch.
  • Schedule it more than once an hour if you need to. A cron expression only fires once per hour per job, so running every 15 minutes means scheduling it four times (at :00, :15, :30 and :45).
  • Make the failed list easy to find. A list view of Status__c = 'Failed' with the error column showing is usually all an admin needs.

The part I like most is how boring it makes failures. A bug in the processing logic used to mean lost events. Now it means a list of failed logs, a fix, and an update of Status__c back to New. No one has to ask the other system to resend anything.