Sub topic 9
Testing Flows with Bulk Data
This chapter covers how to test a flow with many records at once, so you can find limit problems before users do. It assumes you can build a record-triggered flow, read basic Apex, and have already seen how governor limits apply to flows in the earlier chapter on transactions.
Why Bulk Testing Matters
A flow that works when you edit one record in the UI can still fail in production. Many things send records in groups: data loads, the Bulk API, list views with inline edit, imports, integrations, and Apex code that updates a list.
Salesforce processes a group of records as a batch inside one transaction. A record-triggered flow handles up to 200 records per batch. Each batch shares one set of governor limits. If an element runs a query or a DML statement once per record, it uses 200 queries or 200 DML statements for 200 records. The synchronous limits are 100 SOQL queries and 150 DML statements per transaction, so the flow fails.
A single-record test never shows this. The flow runs the loop once, uses one query, and passes.
The table below shows how the same design behaves at two batch sizes.
| Design | 1 record | 200 records | Result |
|---|---|---|---|
| Get Records element inside a loop | 1 query | 200 queries | Fails: over 100 SOQL queries |
| Create Records element inside a loop | 1 DML statement | 200 DML statements | Fails: over 150 DML statements |
| Collection built in loop, one Create Records after it | 1 DML statement | 1 DML statement | Passes |
How Flows Bulkify
Flow Builder bulkifies most work for you. When a record-triggered flow starts for a batch of records, Salesforce runs each element for all records in the batch before moving on. A single Get Records or Create Records element outside a loop therefore runs once per batch.
The problem appears only when you put those data elements inside a Loop element. The loop runs once per item in a collection, and the data element runs once per iteration. You remove the problem by moving the element out of the loop.
Writing a Bulk Apex Test
Flow Builder tests (covered in the previous chapter) run one record at a time, so they cannot check bulk behavior. Use an Apex test for this. The test inserts or updates 200 records in one DML statement, which is the maximum batch size for a trigger-style transaction.
This example assumes an active record-triggered flow on Opportunity. When the stage changes to Closed Won, the flow creates one follow-up task.
@IsTest
private class OpportunityFlowBulkTest {
@IsTest
static void flowHandlesTwoHundredRecords() {
Account acc = new Account(Name = 'Bulk Test Account');
insert acc;
List<Opportunity> opps = new List<Opportunity>();
for (Integer i = 0; i < 200; i++) {
opps.add(new Opportunity(
Name = 'Bulk Opp ' + i,
AccountId = acc.Id,
StageName = 'Prospecting',
CloseDate = Date.today().addDays(30)
));
}
insert opps;
Test.startTest();
for (Opportunity o : opps) {
o.StageName = 'Closed Won';
}
update opps;
Test.stopTest();
Integer taskCount = [SELECT COUNT() FROM Task WHERE WhatId IN :opps];
Assert.areEqual(200, taskCount, 'Each opportunity should get one task without hitting limits');
}
}Several details in this test matter.
- The setup runs before
Test.startTest(). This keeps setup work from counting against the limits of the code you are testing. Test.startTest()andTest.stopTest()give the code between them a fresh set of governor limits. The update of 200 records is the transaction under test.- The update is a single
update oppsstatement. If you updated records one at a time in a loop, Salesforce would run 200 small transactions and the flow would never see a batch. Test.stopTest()also forces any asynchronous work to finish, such as flow paths that run after the save. The assertions after it then see the final data.- If the flow hits a limit, the update throws a
System.DmlException, and the test fails with the limit error in the message. That failure is the signal you want.
Check the Result, Not Just the Absence of Errors
A test that only runs the update proves the flow did not crash. It does not prove the flow did the right thing. Assert on the outcome, as the Assert.areEqual line does. In a bulk test, also check that each record got the correct result, not only that the total is right.
Map<Id, Integer> tasksByOpp = new Map<Id, Integer>();
for (Task t : [SELECT WhatId FROM Task WHERE WhatId IN :opps]) {
Integer current = tasksByOpp.containsKey(t.WhatId) ? tasksByOpp.get(t.WhatId) : 0;
tasksByOpp.put(t.WhatId, current + 1);
}
for (Opportunity o : opps) {
Assert.areEqual(1, tasksByOpp.get(o.Id), 'Opportunity ' + o.Name + ' should have exactly one task');
}This catches a flow that creates 200 tasks but attaches several to the wrong record, a mistake that can come from a collection that is not cleared between iterations.
Mixed Data: Vary the Records
If every test record is identical, you test one path 200 times. Real batches contain records that take different branches. Make some records match the flow's entry conditions and others not.
@IsTest
private class OpportunityFlowMixedBulkTest {
@IsTest
static void onlyClosedWonRecordsGetTasks() {
Account acc = new Account(Name = 'Mixed Test Account');
insert acc;
List<Opportunity> opps = new List<Opportunity>();
for (Integer i = 0; i < 200; i++) {
opps.add(new Opportunity(
Name = 'Mixed Opp ' + i,
AccountId = acc.Id,
StageName = 'Prospecting',
CloseDate = Date.today().addDays(30)
));
}
insert opps;
Test.startTest();
for (Integer i = 0; i < opps.size(); i++) {
if (Math.mod(i, 2) == 0) {
opps[i].StageName = 'Closed Won';
}
}
update opps;
Test.stopTest();
Integer taskCount = [SELECT COUNT() FROM Task WHERE WhatId IN :opps];
Assert.areEqual(100, taskCount, 'Only the 100 Closed Won records should get a task');
}
}Mixed batches expose a second class of bug. A flow might use a single variable to hold a value from one record and then reuse it for the next. With uniform data the bug stays hidden, because every record has the same value.
Reading a Bulk Failure
When the test fails, the message tells you which limit was reached. Common messages include:
Too many SOQL queries: 101. A Get Records element is running inside a loop, or several flows and triggers on the same object together exceed 100.Too many DML statements: 151. A Create, Update, or Delete Records element is running inside a loop.Too many DML rows: 10001. The transaction changes more than 10,000 records. This can happen when a flow updates a large related collection for each record.Apex CPU time limit exceeded. The flow, together with Apex and other automation in the transaction, uses too much processing time. Large loops with many assignments are a typical cause.
To find the offending element, run the test again with a debug log, as described in the earlier chapter on debug logs. The log lists the flow elements that ran and the limit usage at each step. Look for an element that appears 200 times in a row.
Testing Beyond 200 Records
A trigger-style batch holds at most 200 records, but a larger data load is split into several batches inside one transaction. When you insert 400 records with one insert statement in Apex, Salesforce runs the flow twice, once for each 200 records, and both runs share the same limits. Flow interviews do not get a fresh budget for the second batch.
You can test this by raising the count in your test.
@IsTest
private class OpportunityFlowLargeBulkTest {
@IsTest
static void flowHandlesFourHundredRecords() {
Account acc = new Account(Name = 'Large Bulk Account');
insert acc;
List<Opportunity> opps = new List<Opportunity>();
for (Integer i = 0; i < 400; i++) {
opps.add(new Opportunity(
Name = 'Large Opp ' + i,
AccountId = acc.Id,
StageName = 'Prospecting',
CloseDate = Date.today().addDays(30)
));
}
Test.startTest();
insert opps;
Test.stopTest();
Assert.areEqual(400, [SELECT COUNT() FROM Opportunity WHERE AccountId = :acc.Id]);
}
}A flow that uses 40 queries per batch passes with 200 records and fails at 400, because two batches use 80 queries together. Use this kind of test to see how much headroom the flow has, not only whether it passes at 200.
Bulk Testing Autolaunched and Scheduled Flows
Record-triggered flows get bulk batches from the platform. Other flow types need different handling.
- Autolaunched flows called from Apex. The Apex code controls the batching. Test the calling code with a list of 200 records and confirm it starts the flow with a collection input, not once per record. Starting one interview per record in a loop can reach the limit on flow interviews or the DML limit.
- Autolaunched flows called from another flow. A subflow inside a loop runs once per iteration, and each run uses the shared limits. Test the parent flow with a bulk update.
- Scheduled-triggered flows. The platform runs these in batches of records from the scheduled query. Test with enough records in the sandbox to cover several batches, using the data you load before running the flow from the Flow Builder debugger or after activating it.
- Screen flows. These run for one user at a time, so batch size is rarely the issue. Loops over large collections can still hit CPU or DML limits.
Bulk Test Checklist
Use this list when you review a flow before activation.
- Find every Loop element and check what is inside it.
- Confirm no Get Records, Create Records, Update Records, or Delete Records element, and no subflow with data elements, sits inside a loop.
- Check that Update and Delete Records elements target a collection variable, not a single record, when the flow works on many records.
- Write an Apex test that updates 200 records in one DML statement.
- Mix records so some take each decision branch.
- Assert the outcome for each record.
- Repeat with 400 or more records to measure headroom.
- Run the test in a sandbox that has the same triggers and flows as production.
Exercise
A record-triggered flow on Case contains a Loop over the triggering records. Inside the loop, a Get Records element reads the related Account, and an Update Records element sets a field on the Case. Your Apex test inserts one Case and passes. What happens when 200 Cases are updated in one statement, which limits are reached, and how do you restructure the flow?
Show answer
The Get Records element runs once per loop iteration, so 200 Cases use 200 SOQL queries and the transaction fails with "Too many SOQL queries: 101" (the limit is 100). The Update Records element would run 200 times too, which exceeds the 150 DML statement limit. To fix it, move Get Records before the loop and read all needed Accounts in one query using a collection of Account Ids. Inside the loop, use an Assignment element to set values and add each changed Case to a collection variable. After the loop, run one Update Records element on that collection. Then write a bulk Apex test with 200 Cases and assert the field value on each one. For simple field updates on the triggering record, you can also use a before-save flow, which needs no Update Records element.
Exercise
Why does a bulk test put record setup before Test.startTest() and the update between Test.startTest() and Test.stopTest()?
Show answer
Test.startTest() resets governor limits for the code that follows it. Setup before it uses its own limits, so the flow under test is measured on its own. The update inside the pair is the transaction being tested. Test.stopTest() also waits for asynchronous work, so the assertions that follow see the final data.