---
url: https://trigger.beyondthecloud.dev/after-insert/add-ons/finalizer.md
description: >-
  Run once per chunk after an after insert Writer or Dispatcher, with the
  qualified records.
---

# AfterInsert.Finalizer

Run code once per chunk with the records that qualified, such as one write per parent.

**Signature**

```apex
public interface Finalizer {
    void finalizeOnAfterInsert(TriggerTypes.InsertRecords records);
}
```

* `finalizeOnAfterInsert(records)`: called once per chunk, after this handler’s records, only if at least one record qualified; after the dispatch for a Dispatcher.

**Example**

::: code-group

```apex [Skeleton]
public with sharing class ContactWriter implements AfterInsert.Writer, AfterInsert.Finalizer {
    private TriggerTypes.UnitOfWork unitOfWork;

    public Boolean writeOnAfterInsertWhen(TriggerTypes.InsertRecord record) {
        return record.isNotNull(Contact.AccountId);
    }

    public void writeOnAfterInsert(TriggerTypes.InsertRecord record, TriggerTypes.UnitOfWork unitOfWork) {
        this.unitOfWork = unitOfWork;
        unitOfWork.toInsert(new Task(WhatId = ((Contact) record.getNewSObject()).AccountId, Subject = 'Review contact'));
    }

    public void finalizeOnAfterInsert(TriggerTypes.InsertRecords records) {
        for (Id accountId : records.getIdsOf(Contact.AccountId)) {
            this.unitOfWork.toUpdate(new Account(Id = accountId, Description = 'Contacts changed'));
        }
    }
}
```

:::

## Rules {#rules}

* **Keep the unit in a field.** The Finalizer gets no unit of work. Save the `unitOfWork` from the action in an instance field.
* **Not once per statement.** A 1,000-record insert can call it 5 times.
* **Registrations commit with the rest.** By default after the last handler; with OwnUnitOfWork or ContinueOnError, right after the Finalizer.

::: warning
Direct DML runs at once and skips the unit of work.
:::
