Sub topic 15
Keeping flows bulk-safe and avoiding recursion
This chapter assumes you can build a record-triggered flow and map Workflow Rule or Process Builder criteria to entry conditions. A migrated flow can pass every single-record test and still fail when a data load, an integration, or an Apex batch job touches hundreds of records. It can also fire itself repeatedly. This chapter covers both problems.
How flows process records in bulk
When many records change in one operation, Salesforce hands record-triggered flows the records in batches of up to 200. The platform runs one flow interview per record, but it bundles the database work. Interviews that reach the same Get Records, Update Records, or Create Records element have those operations combined where possible.
Bundling only helps if each interview issues the operation once. A flow that queries or writes inside a loop spends the transaction's limits on every iteration. The limits are shared by everything in the transaction: flows, Apex triggers, and other automation. The most important ones are:
- 100 SOQL queries per synchronous transaction.
- 150 DML statements per transaction.
- 10,000 rows processed by DML.
- 50,000 rows returned by queries.
The same limits applied to Process Builder, which was also bulkified. The difference is that Flow Builder lets you build loops by hand, so you can write a pattern that Process Builder never allowed.
The bulk-safe loop pattern
Never place Get Records, Create Records, Update Records, Delete Records, or an Action element inside a Loop. Instead, follow this order:
- Query everything you need once, before the loop.
- Loop over the collection and change values in memory, using Assignment elements.
- Add each changed or new record to a collection variable.
- After the loop ends, run one Update Records or Create Records element on that collection.
A common migrated example is a Process Builder process that updated all open Cases when an Account's status changed. The unsafe design puts an Update Records element inside a loop over those Cases, so one Account costs one DML per Case. The safe design queries the Cases once, sets the field on each Case in the loop, and updates the whole collection once.
Prefer before-save and direct relationships
You can reduce the cost further by avoiding work in the first place.
- A before-save flow that sets fields on the triggering record uses no DML at all. The platform saves the values as part of the original operation.
- A before-save or after-save flow can read parent fields through
{!$Record.Account.Industry}without a Get Records element. - If you only need a few fields, add a filter to Get Records and store only the fields you use, not all fields.
Watch for hidden limits
Two flow-specific limits catch migrators out. A single flow interview can execute at most 2,000 elements at run time, so a loop over thousands of items can fail even with no DML inside it. Also, a Get Records element returns up to 50,000 rows, which counts against the transaction. If a parent could have thousands of children, a record-triggered flow is the wrong tool. Move that work to a scheduled path, a scheduled flow, or Batch Apex.
Recursion: how flows re-trigger themselves
Recursion means a change made by your automation triggers that same automation again. Three sources matter during a migration.
- After-save flow updates its own record. An Update Records element that writes to
{!$Record}in an after-save flow saves the record again. That save can fire the same flow, other flows, and Apex triggers on the object. - Two automations undo each other. Flow A sets Status to "Active" when Region changes. Flow B changes Region when Status changes. Each save triggers the other.
- Cross-object loops. An Account flow updates its Contacts, and a Contact flow updates the parent Account.
Flows that do re-fire can hit limits or loop until Salesforce stops the transaction with an error. Do not rely on that backstop.
What the old tools did
Each old tool had its own recursion behavior. Check the original setting before you migrate, because it tells you what behavior the business has been relying on.
| Old tool | Re-evaluation setting | What to check |
|---|---|---|
| Workflow Rule | "Re-evaluate Workflow Rules after Field Change" on a field update | If it was on, the rule's update could fire other rules |
| Process Builder | "Recursion: Allow process to evaluate a record multiple times in a single transaction" | If it was on, the process could fire again after its own updates |
| Workflow Rule | Evaluation criteria "created, and every time it's edited" | Fires on every save, even when criteria were already true |
| Process Builder | "Only when specified changes are made to the record" | Prevented firing unless fields changed |
Controlling recursion in Flow
Use these techniques, listed from the most to the least preferred.
- Use a before-save flow when you only update the triggering record. Before-save updates do not cause another save, so they cannot re-trigger the flow.
- Set the trigger to run only when a record is updated to meet the condition requirements. This option fires the flow only when the record moves from not matching to matching. A later save that leaves the record matching does not run it again. This is the usual replacement for "created, and any time it's edited to subsequently meet criteria."
- Make entry conditions test a change. Compare
$Recordwith$Record__Priorso the flow only runs when the field you care about changed. - Add a guard field. Set a checkbox such as
Follow_Up_Created__cand test it in the entry conditions. Use this when the criteria can become true more than once but the action must happen only once. - Avoid unneeded writes. Before updating a record, check whether the value already matches the target. A flow that writes the same value still triggers a save.
For an update-or-create flow, this entry formula runs the flow on create, and on update only when the stage newly became Closed Won:
AND(
TEXT({!$Record.StageName}) = "Closed Won",
OR(
ISNEW(),
TEXT({!$Record__Prior.StageName}) <> "Closed Won"
)
)Compare this with the earlier ISCHANGED translation. ISCHANGED alone would fire for any change to the stage field. The extra test on the new value stops it from firing when the stage changes to some other value.
Break cross-object cycles on purpose
When two objects update each other, decide which side owns the field. The owning flow writes it. The other flow reads it and never writes back. If both sides must write, give each flow an entry condition that names the field it watches, so a change made by the other flow does not satisfy it.
Testing for recursion and bulk behavior
Write one Apex test that covers both concerns. It updates 200 records to fire the flow, then saves them again with an unrelated change, and checks that the flow did not run a second time. This test assumes the Closed Won flow from earlier creates one Task for each Opportunity, and it uses the "updated to meet" trigger option.
@IsTest
private class ClosedWonRecursionTest {
@IsTest
static void secondSaveDoesNotCreateMoreTasks() {
List<Opportunity> opps = new List<Opportunity>();
for (Integer i = 0; i < 200; i++) {
opps.add(new Opportunity(
Name = 'Recursion ' + i,
StageName = 'Prospecting',
CloseDate = Date.today().addDays(30)
));
}
insert opps;
for (Opportunity o : opps) {
o.StageName = 'Closed Won';
}
update opps;
for (Opportunity o : opps) {
o.Description = 'Second save';
}
Test.startTest();
update opps;
Test.stopTest();
System.assertEquals(
200,
[SELECT COUNT() FROM Task WHERE WhatId IN :opps],
'Only the first update should have created tasks'
);
}
}If the count is 400, the flow fires on every save. Fix the trigger setting or the entry conditions. If the test throws a limit exception, look for a query or DML element inside a loop.
Review checklist before cutover
- No Get Records, Create, Update, or Delete element sits inside a Loop.
- Record-triggered flows that write to the triggering record are before-save where possible.
- Every after-save flow that updates its own record has entry conditions that stop a second run.
- Each old re-evaluation or recursion setting has a documented equivalent.
- Large child collections are handled by a scheduled path, scheduled flow, or Apex.
- A 200-record test passed on every migrated object.
Exercise
A migrated after-save flow on Case sets Escalated__c = true on the triggering Case with an Update Records element when Priority is "High". The flow is set to run every time a record is updated. After migration, Cases get stuck with errors during data loads. What are two changes that fix the problem, and which is the better one?
Show answer
Change the flow to run only when a record is updated to meet the condition requirements, or add a guard to the entry conditions so it skips Cases where Escalated__c is already true. Either one stops the flow from re-firing on its own save. The better fix is to rebuild it as a before-save flow, because a before-save update to the triggering record uses no DML and cannot re-trigger the flow.
Exercise
Why is an Update Records element inside a Loop a bulk problem, even though the platform bundles operations from several interviews?
Show answer
Each pass through the loop issues its own DML statement, so one interview can use many of the 150 DML statements allowed per transaction. The platform's bundling only combines the same element across different interviews. It cannot combine repeated runs of the element inside a single loop. Collect the changed records in a collection variable and run one Update Records after the loop.