Sub topic 13
Design practices and known limitations
This chapter closes the tutorial. It collects the design rules that keep invocable Apex maintainable, and the platform limits you will run into. It assumes you can write an @InvocableMethod with request and result wrapper classes, that you know why the method must be bulk-safe, and that you have configured an Apex action in Flow Builder.
Decide whether Apex is the right tool
Every invocable method adds code that an admin cannot see or change in Flow Builder. It needs tests, deployment, and a developer to maintain it. Use Apex when the flow cannot do the job reasonably, not because Apex is more familiar.
Good reasons to call Apex:
- You need complex logic, such as recursion, string parsing, or calculations that take many Assignment and Loop elements.
- You need a platform feature that Flow does not expose, such as certain callouts, Apex-only APIs, or
Databasemethods with partial success. - Many flows must share the same logic, and one tested class is easier to keep correct than copies of flow elements.
- You need performance in a bulk context where a flow loop would become hard to read or reason about.
Poor reasons to call Apex:
- Creating, updating, or querying records that Get Records, Create Records, and Update Records already handle.
- Simple branching and formulas.
- Logic that admins need to change often. Moving it into Apex puts a deployment between the admin and the change.
The diagram shows one way to make the decision.
Keep the invocable method thin
An invocable method is an entry point, like a trigger handler or a REST resource. It should translate flow inputs into plain Apex calls and translate the results back. Put the business logic in a separate service class.
This split has three benefits:
- Triggers, batch jobs, and other Apex can reuse the service without going through wrapper classes.
- You can unit test the logic without building request objects.
- Changing the flow-facing contract does not force changes in the core logic.
public with sharing class FollowUpTaskService {
public static List<Database.SaveResult> createFollowUps(List<Id> accountIds, List<String> subjects) {
List<Task> tasks = new List<Task>();
for (Integer i = 0; i < accountIds.size(); i++) {
String subject = subjects[i];
tasks.add(new Task(
WhatId = accountIds[i],
Subject = String.isBlank(subject) ? 'Follow up' : subject,
ActivityDate = Date.today().addDays(7)
));
}
return Database.insert(tasks, false);
}
}public with sharing class CreateFollowUpAction {
public class Request {
@InvocableVariable(label='Account Id' required=true)
public Id accountId;
@InvocableVariable(label='Task Subject')
public String subject;
}
public class Result {
@InvocableVariable(label='Task Id')
public Id taskId;
@InvocableVariable(label='Is Success')
public Boolean isSuccess;
@InvocableVariable(label='Error Message')
public String errorMessage;
}
@InvocableMethod(
label='Create Follow-up Tasks'
description='Creates one follow-up task per request and returns one result per request.'
category='Account'
)
public static List<Result> run(List<Request> requests) {
List<Id> accountIds = new List<Id>();
List<String> subjects = new List<String>();
for (Request req : requests) {
accountIds.add(req.accountId);
subjects.add(req.subject);
}
List<Database.SaveResult> saved = FollowUpTaskService.createFollowUps(accountIds, subjects);
List<Result> results = new List<Result>();
for (Database.SaveResult sr : saved) {
Result res = new Result();
res.isSuccess = sr.isSuccess();
if (res.isSuccess) {
res.taskId = sr.getId();
} else {
res.errorMessage = sr.getErrors()[0].getMessage();
}
results.add(res);
}
return results;
}
}The invocable class holds only mapping code. The service does the work, and the two lists passed to it stay aligned by index, so result order matches request order.
Design the contract carefully
The labels, descriptions, and variable names you publish become a contract with every flow that uses the action. Treat them like a public API.
- Name for admins, not developers. The
labelanddescriptionappear in the Flow Builder action picker. Write "Create Follow-up Tasks", not "AccountTaskHelper.run". - Use
categoryto group actions. In a large org the action list gets long, and a category makes your actions findable. - Mark only truly required inputs as
required=true. An admin cannot save the flow without them. Handle optional inputs in code, as the subject default above does. - Prefer explicit result fields over exceptions for expected failures such as validation errors. Reserve exceptions for conditions the whole flow should treat as faults.
- Avoid renaming or removing published members. Flows store references to the action and its variable names. Renaming a field in a request class can break flows that already map to it. Add new optional fields instead of changing old ones. If a change is incompatible, create a second class or method with a new label, move the flows over, and retire the old one afterward.
- Use
globalonly for managed packages. In a package, the invocable method and its wrapper classes must be visible to subscribers. In your own org,publicis enough.
Known limitations
These are the rules and platform limits that most often surprise developers. Check the current Apex Developer Guide for details, because Salesforce changes this area between releases.
| Limitation | What it means in practice |
|---|---|
| One `@InvocableMethod` per class | Create a separate outer class for each action. Do not try to group several actions in one class. |
| One parameter, and it must be a list | Anything beyond a single list of inputs has to live in a wrapper class. |
| The method must be `static` and `public` or `global` | Instance methods and private methods are not exposed. |
| Return type is `void` or a list | You cannot return a single object or a map. Return a list with one entry per input. |
| Wrapper fields support limited types | Maps and sets are not supported in `@InvocableVariable` fields. Use lists, primitives, Ids, sObjects, or supported wrapper types. |
| Result list must match input size and order | If the sizes differ, the flow cannot tell which result belongs to which interview. |
| Shared governor limits | The method runs inside the flow's transaction and uses its SOQL, DML, and CPU budget. |
| No control over batching | Flow decides how many interviews go into one call. You cannot request a batch size. |
| Limited debugging inside Flow | Flow debug shows inputs and outputs, but you need Apex debug logs to see inside the method. |
Failure modes in bulk
Bulk behavior is where most production defects appear. Keep these cases in mind when you design a method.
- One bad input fails the whole batch. If the method throws an exception, every interview in that call fails together. Where possible, catch expected per-record problems, use partial-success DML (
Database.insert(records, false)), and report each outcome in the result list. - Null inputs. Optional fields arrive as
null. Check them before calling methods such asString.trim(), as theSlugGeneratorexample did. - Duplicate inputs. Two interviews in the same batch can pass the same record Id. Decide whether to deduplicate, and if you do, still return one result per original request.
- Result misalignment. If you filter or skip invalid requests, you can end up with fewer results than requests. Add a placeholder result for each skipped request instead of leaving it out.
- Queries inside loops. A loop that runs a query once per request works with one record and fails with 200. Collect Ids first, query once, and use a map to look up the data.
A defensive pattern for skipped requests is to pre-fill the result list and fill in each entry by index:
List<Result> results = new List<Result>();
for (Integer i = 0; i < requests.size(); i++) {
Result res = new Result();
res.isSuccess = false;
res.errorMessage = 'Not processed';
results.add(res);
}Then update results[i] for each request you do process. Any entry you never touch still reports a clear outcome and the list keeps its size.
Transaction and callout limitations
The method does not control when its transaction starts or ends. Two consequences matter most for design.
First, in a record-triggered flow the action runs inside the save transaction of the triggering record. Slow or heavy Apex there slows every save of that object, and an unhandled exception can roll back the user's save. Flow's asynchronous paths can move work out of the save transaction. Consider them for anything heavy.
Second, callouts have ordering rules. Apex cannot make a callout while uncommitted DML is pending in the same transaction, and before-save record-triggered flows cannot run callouts. A method that calls an external service is safest in a context where no DML came before it, or on an asynchronous path. If the method makes callouts, set callout=true on the annotation so the platform knows.
Sharing and security
An invocable class runs with the sharing mode you declare. Use with sharing by default so the method respects the running user's record access. Use without sharing only when the logic must see records the user cannot, and document why in a comment. Sharing does not enforce field-level security or object permissions on its own. If users with limited permissions can trigger the flow, use WITH USER_MODE in SOQL, Database.insert(records, AccessLevel.USER_MODE), or Security.stripInaccessible as your policy requires.
A review checklist
Before releasing an invocable method, confirm each point:
- The flow could not reasonably do the job with built-in elements.
- The method is a thin wrapper, and the logic lives in a service class.
- The label, description, and category make sense to an admin.
- The result list has one entry per request, in the same order.
- There are no SOQL or DML statements inside loops.
- Expected failures appear in results. Unexpected ones throw, so the fault path can handle them.
- Sharing and field access match the intended security.
- A test calls the method with 200 requests, and another covers null and invalid inputs.
- Flows that use the action have been tested in their real trigger context, including callouts.
Exercise
A teammate puts three @InvocableMethod methods in one class, each for a different task, and asks why the code will not save. Explain the problem and describe how you would restructure the code so the shared logic stays in one place.
Show answer
A class can contain only one @InvocableMethod, so the save fails. Create one outer class per action, each with a single thin invocable method and its own request and result classes. Move the logic the actions share into a separate service class that each invocable class calls. The shared code stays in one place, and each action gets its own label and description in Flow Builder.
Exercise
Your invocable method receives 200 requests, and 5 have a blank accountId that you decide to skip. A flow later reads the results by position and shows wrong outcomes. What went wrong, and how do you fix it?
Show answer
The method returned only 195 results, so every result after the first skipped request shifted out of position, and the sizes no longer matched the inputs. The fix is to return exactly one result per request, in input order. For each skipped request, add a result with isSuccess = false and a clear error message, either by pre-filling the result list or by adding a failure result at that index.