Sub topic 1
When Flow needs Apex
Flow Builder covers most automation needs without code. Some jobs are awkward or impossible to build from flow elements. In those cases you can write an Apex method and expose it to the flow as an action. This chapter helps you decide when that is worth doing. Later chapters cover how to write the method.
Prerequisites
This chapter assumes you already know:
- Basic Apex syntax: classes, methods, collections, and SOQL.
- Basic Flow Builder concepts: record-triggered flows, screen flows, variables, and elements such as Decision, Loop, and Get Records.
- That Apex governor limits exist, and that DML (insert, update, delete) counts against them.
You don't need to have written an invocable method before.
What "calling Apex from Flow" means
A flow can run actions. Some actions are built in, such as Send Email or Post to Chatter. Others are custom actions that you or your team provide. An Apex class can become one of these custom actions if it has a method annotated with @InvocableMethod.
An annotation is a marker placed before a class, method, or variable that tells the platform to treat it specially. Once the class is saved, the method appears in Flow Builder in the Action element, under the label you gave it. The flow passes values in, the Apex code runs, and values come back to the flow as outputs.
This is the smallest useful example. It is a method that takes text and returns a URL-friendly slug (lowercase words joined by hyphens):
public class SlugGenerator {
@InvocableMethod(label='Make Slug' description='Lowercases text and replaces spaces with hyphens.')
public static List<String> makeSlugs(List<String> inputs) {
List<String> slugs = new List<String>();
for (String input : inputs) {
slugs.add(input == null ? null : input.trim().toLowerCase().replaceAll('\\s+', '-'));
}
return slugs;
}
}Notice that the method takes a list and returns a list, even though a flow might pass only one string. The signature rules and the reason behind them come in the next chapters. For now, treat the shape as a given.
Start with what Flow can already do
Reaching for Apex too early is a common mistake. Every Apex class adds a deployment step, a test requirement, and a maintenance owner who can read code. Before you write one, check whether Flow can do the job natively.
Flow can already:
- Create, update, delete, and query records with Get Records, Create Records, Update Records, and Delete Records.
- Branch with Decision elements and repeat work with Loop elements.
- Filter and sort collections with the Collection Filter and Collection Sort elements.
- Calculate with formula resources, including text, date, and math functions.
- Reshape data with the Transform element.
- Call external systems with the HTTP Callout action or with External Services.
- Run reusable logic through subflows.
Salesforce adds capabilities to Flow in most releases, so a gap you remember may have been closed. Check the current release notes before assuming a limit still applies.
Signs that a flow needs Apex
Apex earns its place when the flow version would be fragile, slow, or impossible. These are the most common reasons.
Logic that is awkward to express as elements
A flow is a graph of elements. Complex logic becomes a sprawling graph that is hard to read and review. Examples are nested loops over several collections, matching records between two lists by key, or an algorithm with many conditional steps. A few dozen lines of Apex with a Map can replace a large cluster of Loop and Assignment elements.
Operations Flow does not offer
Some operations have no equivalent element or formula function. Examples include:
- Aggregate queries such as
GROUP BY, which Get Records does not support. - Regular-expression processing beyond what formula functions allow.
- Cryptographic functions, or Base64 and JSON handling beyond what Flow offers.
- Queries that need a subquery, a polymorphic relationship, or dynamic field lists.
- Access to Apex-only APIs, such as certain
SystemandDatabasemethods, orDatabase.insertwith partial success.
Performance-sensitive loops
Flow loops over large collections can be slow, and the per-element overhead adds up. Apex executes the same work more efficiently, and it gives you finer control over queries and DML.
Fine-grained control of DML and errors
Flow's Create and Update elements either succeed or fault. Apex lets you use Database.insert(records, false) so that valid records save while invalid ones report errors individually. You can then hand the per-record results back to the flow. The chapter on error handling covers this.
Reuse of logic that already exists in Apex
If a trigger handler or service class already contains the business rule, an invocable method lets a flow call that same code. The rule then lives in one place instead of being rebuilt in Flow and drifting out of sync.
Complex external integrations
The HTTP Callout action handles many REST integrations. Apex is still the better fit when the callout needs custom authentication, response parsing that goes beyond a defined schema, retries, or logic that depends on the response before the next step.
A quick decision guide
The following table compares common situations.
| Situation | Prefer | Reason |
|---|---|---|
| Update a field when a record changes | Flow | One Update Records element does it. |
| Branch on a few field values | Flow | Decision elements are readable by admins. |
| Sum child records into the parent | Depends | Flow can loop and sum. Apex can use an aggregate query. |
| Group records and count by category | Apex | Get Records has no `GROUP BY`. |
| Match two lists by a shared key | Apex | A `Map` is simpler than nested loops. |
| Save valid records and report invalid ones | Apex | `Database.insert` with partial success gives per-record results. |
| Call a simple REST API | Flow | The HTTP Callout action avoids code. |
| Call an API with custom signing | Apex | Flow cannot compute custom signatures. |
| Reuse a rule that a trigger already enforces | Apex | One implementation avoids drift. |
The diagram shows the same reasoning as a sequence of questions.
What stays the same when Apex joins the flow
Calling Apex does not put the work in a separate world. Keep these points in mind.
- The Apex runs in the same transaction as the flow that called it. A transaction is a group of operations that either all commit or all roll back. If the Apex method throws an uncaught exception, the flow can handle it through a fault path. Otherwise the whole transaction is rolled back.
- The governor limits, such as SOQL queries and DML statements, are shared between the flow and the Apex it calls. Apex does not get a fresh budget.
- The flow decides when the method runs, and it may run once for many records. A record-triggered flow can process up to 200 records in one batch, and each record has its own flow interview (one running instance of the flow). The platform collects the inputs from those interviews into one list and calls your method once. This is the reason invocable methods take lists.
Costs to weigh
Apex is powerful, but it changes who can maintain the automation. Consider these costs before you commit.
| Cost | What it means in practice |
|---|---|
| Deployment | Apex needs a sandbox, a change set or a source-driven pipeline, and a production deployment. A flow change can be simpler. |
| Test coverage | Production deployments require adequate Apex test coverage. You must write and maintain tests. |
| Ownership | An admin who builds flows may not be able to change the Apex. Document who owns it. |
| Visibility | Logic hidden in Apex is not visible on the flow canvas. Use clear labels and descriptions so the flow still reads well. |
| Contract changes | Renaming or removing an invocable method or variable that a flow uses can break the flow. |
A good compromise is to keep the flow in charge of the process, meaning the sequence and the decisions that admins care about. Use Apex only for the single step that needs it. For example, the flow handles the trigger condition and the follow-up email, and Apex handles one calculation in the middle.
Common mistakes
- Writing Apex for something Flow already does. Check the current element list first. A Transform or Collection Filter element may remove the need.
- Moving the whole process into Apex. If the Apex method does everything, the flow becomes a thin wrapper and loses its value as a visible process.
- Assuming one flow interview means one input. The method may receive many inputs in one call. Design for the list from the start.
- Forgetting that limits are shared. A flow that already runs several queries leaves less room for your method.
- Skipping tests because the logic is small. Even the slug example should have a test, and production deployment needs coverage anyway.
Summary
Use Flow when built-in elements can express the logic clearly. Use an invocable Apex method when you need an Apex-only feature, a clearer or faster implementation of complex logic, per-record error control, or reuse of existing code. The method runs inside the flow's transaction and shares its limits, and it receives a list of inputs.
Exercise
A record-triggered flow on Opportunity needs to count open opportunities per Account owner and write the counts to a custom object. Get Records does not support GROUP BY. Should you reach for Apex, and what single step should it handle?
Show answer
Yes, this is a good case for an invocable method. The flow should keep the trigger condition and the later record updates. The Apex method should handle only the grouping step, using an aggregate SOQL query (GROUP BY) over the whole input list in one query, and return the counts to the flow.
Exercise
Why does the SlugGenerator method accept List<String> and return List<String> when a flow may pass only one string?
Show answer
The platform can run many flow interviews in one transaction, for example when a record-triggered flow processes a batch of up to 200 records. It collects the inputs into one list and calls the method once. The method must therefore accept a list and return one result per input, in the same order.