Ryan Melvin / Salesforce consultant

Case 04 Demo Illustrative rebuild with made-up data: the pattern and the decisions, not client code.

One organization per transaction, and a log of every send

A monthly run that renders and emails a giving statement for every member church, built so it cannot skip a church without saying so.

From the interactive demo, with made-up data.

Problem

Every month, each member church needs a statement of what it gave and what it was billed. Each statement means rendering a PDF, working out who should receive it, sending the email, and recording that it went.

The first version processed a whole batch of churches inside one transaction. It worked, which was the dangerous part: it only worked because the batch size happened to be small.

Constraints

Salesforce puts hard limits on how much one transaction can do (its "governor limits") and on the order some operations can run in. Three of them shape this job:

Limit Why it matters here
Heap memory and CPU time per transaction Every church needs its own PDF, and rendering one (getContentAsPDF) is expensive on both. A few per transaction is fine; a large batch is not
PDF rendering behaves like a callout, so it cannot run after uncommitted database writes in the same transaction The order is fixed: render, then send, then write the log row
10 Messaging.sendEmail invocations per transaction, plus the org's daily email limits One invocation can carry a list of messages, so this is rarely the bottleneck, but a full monthly run still has to fit under the daily cap

The failure mode made this urgent. Raising the batch size, an ordinary settings change that looks completely safe, would pack more PDF renders into one transaction until it hit a limit. A limit exception cannot be caught, so Salesforce rolls back that transaction, which for Batch Apex means the whole execute chunk: those churches get no statement and no log row, and the only trace is an error in a background job log nobody reads.

The platform has standard tools for exactly this, and a naive design ignores them: BatchApexErrorEvent, which a batch job can publish when a chunk fails, and Transaction Finalizers, which run after a Queueable job finishes even when it failed.

Options considered

Keep one transaction per batch and pin the batch size low. Rejected. It makes correctness depend on a setting nobody would think to protect, and the failure is silent.

Platform Events to fan out one message per church. Workable, but it adds another asynchronous step with its own delivery rules, for no gain. The work is already ordered and already runs in the background.

A Schedulable class that starts the chain directly. Simpler, and a fair choice at small volumes. I kept Batch Apex for the scoping step because the in-scope query reads dated affiliations across the whole network, and chunking it keeps that query clear of per-transaction row limits as the network grows.

Batch Apex to list the churches, a chain of Queueable jobs with a Transaction Finalizer to do the work. Chosen.

Decision

A batch job decides which churches are in scope. A chained Queueable job handles exactly one church per transaction.

The batch lists the churches in scope and, when it finishes, hands the list plus a starting position to the first Queueable job. Each job handles one church (find recipients, render, send, then log) in its own transaction.

Before it does any work, each job attaches a Transaction Finalizer. The finalizer runs after the job ends, in a separate transaction, even if the job failed on a limit. If the job failed, it writes the failure log row with the error text. Either way, it queues the next church. One failure never silently ends the chain.

// Illustrative only: invented names, not client code.
public class SendNextStatement implements Queueable {
  List<Id> orgIds; Integer i;
  public SendNextStatement(List<Id> orgIds, Integer i) { this.orgIds = orgIds; this.i = i; }

  public void execute(QueueableContext ctx) {
    System.attachFinalizer(new ContinueChain(orgIds, i));
    StatementResult r = Statements.renderAndSend(orgIds[i]); // render before any DML
    insert Statements.logRow(orgIds[i], r);                  // sent, or a handled failure
  }

  // Runs after the job ends, in its own transaction, even if the job hit a limit.
  public class ContinueChain implements Finalizer {
    List<Id> orgIds; Integer i;
    public ContinueChain(List<Id> orgIds, Integer i) { this.orgIds = orgIds; this.i = i; }

    public void execute(FinalizerContext ctx) {
      if (ctx.getResult() == ParentJobResult.UNHANDLED_EXCEPTION) {
        insert Statements.failureRow(orgIds[i], ctx.getException().getMessage());
      }
      if (i + 1 < orgIds.size()) {
        System.enqueueJob(new SendNextStatement(orgIds, i + 1));
      }
    }
  }
}

The result, stated plainly: the transaction limits no longer depend on the batch size. Whatever the batch size is set to, one church per transaction means one render, one send and one log row. The setting that used to be a trap now does nothing dangerous.

Recipients are worked out in one place

One shared service decides who receives a church's statement, and both the on-screen preview and the monthly send call it. That is deliberate. A preview that shows a different recipient list than the real send is worse than no preview, because it creates false confidence.

Build

Recipients come from dated NPSP affiliations, filtered to a configured list of active titles and the current date window. A treasurer who rotated off in March stops getting statements in April without anyone remembering to remove them.

Every attempt writes a log row: church, recipients, month, year, status, error text and time. Successes and failures both.

The chain also logs the churches it did not reach. If queueing the next job fails, the remaining churches are written to the log as failed, with the reason, instead of the chain simply stopping. And because a failed job rolls back before anything is committed, its email never goes out, so a rerun cannot double-send.

That is the whole point of this project. A run that stops halfway and tells you is a routine fix. A run that stops halfway and does not is a church that quietly stopped getting statements, found out months later by the church.

Evidence

Open the demo with the Try the demo button at the top of this page, or from Selected work on the home page. It rebuilds the one-church-per-transaction pattern and its send log with made-up data.

The log is the evidence, by design. Any month can be reconciled from it: statements sent, statements failed, and churches that appear in neither, which is the category a simple success count can never show. Failures carry their error text, so a rerun targets only the churches that failed instead of re-sending to everyone. The "which church is next" logic is a small pure function with its own tests, so it can be checked without queueing anything.

Outcome

The monthly run is unattended. Limit failures caused by batch-size changes are ruled out by design rather than merely unlikely, and every send can be traced after the fact.

What I'd do differently

Design the log before the sender. The audit trail is the part operations staff actually read, and on my next job like this it comes first. It is easy to build the interesting part first and the useful part second.

Plan the next step for growth. The chain is serial, which suits this volume, but a full run takes as long as the sum of its parts. For a much larger organization I would fan out independent Queueable jobs with a completion tracker and accept the extra bookkeeping.

← All work

Need Salesforce, data or AI help that lasts after launch?

Fixed-price, phased projects for nonprofits, churches and small businesses.