Content last updated July 2022.
Read about our update schedules here.

Introduction

Systems demonstrate automated behavior by enabling the business to meet key goals and objectives faster and at scale. Healthy automation enables users to focus on high-value work and reduces time spent on repetitive, manual tasks or complex data entry.

Most often, automation means translating business processes from one form to another: from paper-based form to digital form, from an old system to a new one. With every business process translation comes an opportunity for transformation.

Transformation is not about using new technologies to introduce disruptive and confusing changes for users. Transformation is about creating simpler ways for work to get done, enabling business to grow without friction, and empowering business users to focus more deeply on what really matters to their stakeholders. From an architectural point of view, this involves identifying tasks that can be eliminated altogether, or handled automatically. It requires a clear connection between how technology is used and its measurable impact on the business.

Something important to note about automation with Salesforce: it can be done with a variety of tools, using programmatic and declarative skill sets. Designing automations that are well-architected is not about choosing to build with just one automation tool. It is about using approaches that are consistent and predictable, and enabling teams to develop, test, deploy, and maintain the automations you design. Your automations should take the most simple form possible.

This section covers how to design and refactor automations to enable businesses to meet key objectives faster and at scale. To learn more about choosing the right tool for your automation use case, see the Architect’s Decision Guide to Record-Triggered Automation.

You can improve the architecture of your automations in Salesforce by focusing on three key habits: clear logic, data integrity, and alignment to business value.

Clear Logic

Having clear logic in your automations isn’t about dutifully re-creating business as usual with Salesforce technologies. It’s about deeply understanding the key metrics and business outcomes that teams will be accountable for meeting or tracking, and stepping back to see business capabilities within and across the work that you’re automating. It’s about identifying how you can create patterns with your automations that enable the business to operate more effectively and quickly.

Clear automation logic will make your systems:

You can clarify the logic in your automations through process optimization and planning for scale.

Business Process Optimization

Business process optimization involves increasing the efficiency of your organization by improving the ways work gets done. Optimized processes should create measurable business value (see KPIs) without unnecessary steps. Unclear or unnecessary steps will likely create technical debt and result in unmaintainable automations.

Often, the responsibility for discovering and documenting business processes will fall under the responsibility of a business analyst or even a system administrator. Architects are responsible for partnering with these members of your team to make sure your process designs are technically sound and well structured. Applying your knowledge of the Salesforce platform as early as possible will help your team identify processes to streamline through automation or processes that need to change to avoid costly customizations.

To build optimized processes for Salesforce, consider:

The list of patterns and anti-patterns below shows what proper (and poor) optimization looks like in a Salesforce org. You can use these to validate your automation designs before you build, or identify automations that need to be optimized further.

To learn more about process automation tools available from Salesforce, see Tools Relevant to Automated.

Planning for Scale

Scalable automations continue to perform well, regardless of spikes in transaction volumes or the number of concurrent instances that are running. Scalable automations help organizations to grow by supporting increasing demand for their products and services. Building scalability into your automations is directly related to the overall reliability of your system.

Automations that do not scale provide poor user and customer experiences, leading to both potential revenue losses and loss of customer trust. They also have higher maintenance costs and can become bottlenecks that delay related processes, contributing to overall system performance issues.

To design scalable automations, consider:

The list of patterns and anti-patterns below shows what proper (and poor) scalability looks like in Salesforce automation. You can use these to validate your automation designs before you build, or identify automations that need to be optimized further.

To learn more about tools available from Salesforce that can help you plan for scale, see Tools Relevant to Automated.

Logic Patterns and Anti-Patterns

The following table outlines patterns to look for (or build) in your org and anti-patterns to avoid or target for remediation.

Patterns Anti-Patterns
Optimization In your org:
- Each flow serves a single, specific purpose
- Each step performs a specific, granular task
- Flows are organized in a hierarchical structure consisting of a main flow and supporting subflows
- All user inputs have a clear purpose within the flow
- Users are only asked to provide data when existing system data can’t be used
In your org:
- Flows serve multiple purposes and require additional inputs to provide context
- Flows require inputs whose data is not used
- Groups of related steps contain functionality that overlaps with groups of steps in other flows
- Flows ask for user inputs when stored data can be used instead
In Apex:
- Each class serves a single, specific purpose
- Each method performs a specific, granular task
- All input variables have a clear purpose within the class
- Code execution requires a minimal number of resources
In Apex:
- Classes serve multiple purposes
- Methods perform multiple tasks or methods perform tasks that don’t align to the stated purpose of the class they’re part of
- Input variables aren’t actually used in methods
- Methods unnecessarily retrieve data from the database or from external systems
Scalability In Flow:
- No variables refer to hard-coded values (for record types, users, etc.)
- All autolaunched flows and processes use decision and/or pause elements to evaluate entry criteria and prevent infinite loops or executions against large data volumes
- Flows (including processes) hand logic off to Apex in large data volume contexts
- Subflows are used for the sections of a processes that need to be reused across the business
In Flow:
- Variables have hard-coded values
- Flows (including processes) must be manually deactivated prior to bulk data loads
- Flows (including processes) trigger "unhandled exception" notices
- Even simple flows regularly cause errors related to governor limits
- Portions of a flow are repeated across flows rather than using subflows
In Apex:
- No variables refer to hard-coded values (for record types, users, etc.)
- SOQL is wrapped in try-catch blocks
- All SOQL is assigned to a collection variable
- No SOQL appears within a loop
- All * criteria appear in SOSL
- No SOQL statements with LIKE filter criteria exist (SOSL is used instead)
In Apex:
- Variables have hard-coded values
- SOQL is not wrapped in try-catch
- SOQL uses LIMIT 1 to allow for singleton patterns
- Query limits are regularly thrown throughout applications
- SOSL is not used
- * criteria appear in SOQL
In your design standards and documentation:
- Planned and potential execution paths for automations are outlined clearly
- The use cases for synchronous and asynchronous operations within automations are outlined clearly as part of design standards
In your design standards and documentation:
- Automation invocation is not documented
- Use cases for synchronous and asynchronous operations are not addressed

Data Integrity

Data integrity is about how well a system maintains accurate and complete data. The Salesforce Platform maintains robust, built-in processing logic designed to protect the integrity of data stored in an individual org’s relational database. One of the fundamentals of building healthy automations is understanding the built-in data integrity behaviors of Salesforce, and making sure all your automation designs align with (and acknowledge) these behaviors.

The biggest anti-patterns in automation design arise from failing to recognize the powerful data integrity services already provided by Salesforce and failing to use standard functionality that takes advantage of these services. To design automations that protect and maintain data integrity you must be familiar with the fundamental order of operation behaviors of Salesforce.

Properly extending data integrity into your custom automations means your system can:

You can build better data integrity into your Salesforce automations through proper transaction handling and error handling.

Transaction Handling

The first step to designing for proper transaction handling in Salesforce is understanding how the multitenant platform handles transactions. This includes understanding the built-in order of execution behaviors that the Salesforce Platform uses to ensure data integrity during record-level data operations. For more on the impacts of this behavior, see Database Manipulation in Salesforce Architecture Basics.

Poor transaction handling in your automations can be one of the most difficult anti-patterns to identify and fully remediate. The recursive and overlapping nature of the platform’s order of execution can make it difficult to see where issues originate. The specific section of code or flow that throws a fatal error or exceeds governor limits may not be the root cause of an underlying issue.

Transaction awareness is key to building automations that perform reliably and at scale with Salesforce. This means making sure that every step in an automation is designed with the knowledge of where it is in relation to the platform-controlled order of execution, can carry out its function correctly, and passes on information to the next step correctly.

Regardless of the automation tool you are using, proper transaction awareness follows similar patterns and requires common considerations:

Beyond transaction awareness, there is a second dimension to transaction handling: knowing when to carry out logic in different execution contexts. Common reasons to break automations up into different transactions and execution contexts include:

The list of patterns and anti-patterns below shows what proper (and poor) transaction awareness looks like in a Salesforce org. You can use these to validate your automation designs before you build, or identify automations that need to be refactored to improve transaction handling.

To learn more about tools available from Salesforce for handling transactions, see Tools Relevant to Automated.

Error Handling

Error handling is critical for data integrity. Strong error handling also helps your system scale and age with more resilience.

Improper error handling in automations can lead to:

Error handling in automations requires giving any running process the capability to parse an error for information, access logic about what the next steps should be based on error information, and then follow the correct path. These capabilities don’t need to be built over and over in every automation (that’s an optimization anti-pattern). Instead, every automation in the system should have the ability to connect to the relevant error handling components.

To build proper error handling controls into your automations, ask these questions:

Once you’ve decided how to handle these errors, you can start to build effective error handling into your automations. The list of patterns and anti-patterns below shows what proper (and poor) error handling looks like in a Salesforce automation. You can use these to validate your automation designs before you build, or identify automations that need to be refactored to improve error handling.

To learn more about tools available from Salesforce for error handling, see Tools Relevant to Automated.

Data Integrity Patterns and Anti-Patterns

The following table outlines patterns to look for (or build) in your org and anti-patterns to avoid or target for remediation.

Patterns Anti-Patterns
Transaction Handling In your Apex:
- All synchronous DML statements or Database class methods are carried out in before trigger execution contexts
- Async Apex invocations use queueable to 'chain' complex DML across transactions
- Batch Apex is used exclusively for large data volumes
- Future Apex is used sparingly, for callouts or system object DML
In your Apex:
- DML statements regularly appear in code that will be invoked in after trigger contexts
- Async Apex is rarely used
- Async Apex features are used arbitrarily; it is not clear developers know when to use future vs queueable Apex, when to hand off DML to batch jobs
In Flow:
- All flows launched in user context abstract all system context transactions to subflows, which are consistently placed after a Pause element, to create a new transaction
- Complex sequences of related data operations are created with Orchestrator (instead of invoking multiple subflows within a monolithic flow)
- All record-triggered flows have trigger order values populated
- Flows involving external system callouts or long-running processes use asynchronous paths
In Flow:
- Flows run into errors due to mixed DML operations
- Large, monolithic flows attempt to coordinate complex sequences of related data operations (with or without subflows)
- Record-triggered flows do not use trigger order attributes at all or do not use trigger order values consistently
- Asynchronous paths are not used consistently or at all
Error Handling In Apex:
- Code wraps all DML, callouts, and other critical process steps in try-catch blocks
- Custom exceptions are used to create advanced error messaging and logic
- In async and bulk contexts, Database class methods are used instead of DML
- Database class methods may be used exclusively for all data operations (instead of DML)
In Apex:
- try-catch blocks are not used consistently or at all
- DML, callouts, or other critical process steps are not consistently wrapped in try-catch blocks
- System.debug statements appear in production code (and are not commented out)
- No Database class methods are used
- Data operations are done exclusively with DML
In Lightning Web Components (LWC):
- JavaScript wraps all data operations and critical process steps in if ()/else if () blocks
- All @wire functions use data and error properties provided by the API
- All if (error)/else if (error) statements contain logic to process errors and provide informative messages
In LWC:
- JavaScript does not consistently use if ()/else if () blocks with data operations or critical process steps
- @wire functions do not use data and error properties provided by the API (or do not use them consistently)
- If used at all, if (error)/else if (error) statements do not actually contain logic to process errors and provide useful error messages
In Aura:
- JavaScript wraps all data operations and critical process steps in try-catch blocks
- Within try-catch blocks, native JavaScript Error is used in throw statements (no usage of $A.error())
- All recoverable error logic appears within catch statements, and provides clear user messages
In Aura:
- JavaScript does not consistently wrap data operations and critical process steps in try-catch blocks
- Components use $A.error()
- Recoverable error logic does not consistently appear within catch statements, and error messages to users are not clear
In Flow:
- Screen flows consistently use fault connectors to show errors to users
- Custom error messages are configured for errors that will appear on screen
- Flows with data operations, callouts, and other critical processing logic have fault paths for all key actions
In Flow:
- Flows do not use fault paths consistently or at all
- Custom error messages are not used, so users see the default "An unhandled fault has occurred in this flow" message

Alignment to Business Value

The concept of business value, in the context of automation, is about how well processes create measurable, positive impact for business stakeholders. Ideally, process automation enables users to spend less time on repetitive, low-value tasks. It also helps boost data integrity by eliminating manual processing activities that could introduce errors. Much like Business Process Optimization, identifying and delivering automations that will drive real business value requires work beyond basic discovery and business analysis.

At times, it may seem like the best way to deliver value to the business is to simply automate every process requested by a business user, either in the order they appear in your backlog (or ticketing queue) or based on political factors in your organization. This can lead to two related problems: building automations in a suboptimal order and building the wrong automations altogether. The first problem, poor prioritization, prevents high-value processes from getting implemented when they should, potentially slowing growth. The second problem, building the wrong automations, not only delays the delivery of high-value automations, it also leads to misspent time, unnecessary costs, and increased frustration among delivery teams.

You can deliver greater alignment to business value through automation with KPIs and prioritization.

KPIs

Automation KPIs measure the impact of an automation over time. Without them, you’ll have no way to tell if an automation is truly adding business value or creating unintended complexity for your users. Every automation you build should be tied to a clear, measurable set of KPIs.

Good KPIs are defined by a measurable value along with an associated time frame. Examples include:

Once you have clear, measurable KPIs, you have to also understand if and how an automation in Salesforce will generate data that is relevant to reporting against those KPIs.

The list of patterns and anti-patterns below shows what proper (and poor) KPIs look like when it comes to Salesforce automations. You can use these to validate your existing KPIs, or identify where you need to better identify KPIs before you build.

To learn more about tools available from Salesforce for help with KPIs, see Tools Relevant to Automated.

Prioritization

Prioritization means planning the order and scope of the automations you will deliver. Prioritization involves understanding the true impact of automations on the business, and evaluating those impacts against the work laid out in your roadmap (see intentionality).

One way to evaluate the impact of a given automation is to look at the actual cost or benefit to the business. Once you’ve identified the KPIs (see above) for the automation, you can use a business impact calculation worksheet to evaluate the overall cost or benefit of implementation. These calculations can help you get alignment and buy-in from your stakeholders about what automations to build and in what order. They can also help you identify automations to postpone or avoid. See optimization for more about identifying what to automate.

Establishing a prioritization framework for automation delivery will also help you and your maintenance teams manage user expectations and stay aligned with your roadmap.

Some considerations you can use for prioritization include:

The list of patterns and anti-patterns below shows what proper (and poor) prioritization looks like when it comes to Salesforce automations. You can use these to validate your automation plans, or identify where you need to better identify priorities before you build.

To learn more about tools available from Salesforce for help with prioritization, see Tools Relevant to Automated.

Align to Business Value Patterns and Anti-Patterns

The following table outlines patterns to look for (or build) in your org and anti-patterns to avoid or target for remediation.

Patterns Anti-Patterns
KPIs Within your documentation:
- Outputs for every automation are measurable and timebound
- Accountable stakeholders are listed for each KPI
Within your documentation:
- KPIs do not exist for automations or have unclear time frames for measurements
- KPIs exist without accountable stakeholders
Within reports and dashboards:
- All metrics related to KPIs are included in at least one report or dashboard
Within reports and dashboards:
- KPI reporting does not exist or reports are missing metrics related to some KPIs
Prioritization Within your documentation:
- All KPIs related to automations have clear business value (for example, revenue increases, cost savings from process optimizations, and so on)
- Roadmaps show that automations are prioritized based on business value
Within your documentation:
- Business value associated with automations is unclear or nonexistent
- Roadmaps for process automation don't exist
Within your company:
- Implementation and maintenance costs have been identified for all KPIs
- Requests for process automation are prioritized based on business impact, amount of new work required to deliver, and amount of work required to maintain
Within your company:
- Costs associated with implementing and maintaining automations are unclear
- Requests for process automation are delivered on an ad hoc or first-in/first-out basis

Tools Relevant to Automated

ToolDescriptionClear LogicData IntegrityBusiness Value
Apex BatchingBatch records together and process them maneagable chunksXX
Apex Future MethodsAsynchronously execute apex methods in the backgroundXX
Apex Queueing Add apex jobs to a queue and monitor themXX
Apex SchedulerAsynchronously execute apex classes at specified timesXX
ApprovalsSpecify the required steps to approve recordsXX
Asynchrounous ApexRun Apex code asynchronouslyXX
Automated ActionsPerform field updates, email sends and other actions in the backgroundXX
Einstein Next Best ActionDisplay the right recommendations to the right people at the right timeXX
Email AlertCreate and send automated emailsXX
Escalation ActionsSpecify automated actions to take for case escalationsXX
Field UpdateUpdate field values based on automationXX
Flow BuilderBuild automations with a point-and-click interfaceXX
Flow ExtensionsAccess stored variables as component inputs in flowsX
Flow Templates LibraryUse templates to design industry specific flowsXX
Flow TriggerAutomate complex business processesX
Invocable ActionsAdd Apex functionality to flowsXX
OrchestratorCreate and manage multi-step automationsXX
Outbound MessageSend information from an automated process with receipts and retries X
Publish Platform Events with FlowPublish events via user interactions and automationsX
Query OptimizerUse selectivity and indexes to improve query, report, and list view performanceXX
Salesforce FlowCreate declarative process automations with Flow BuilderXX
Send Notifications with FlowsSend messages over SMS, WhatsApp, or Facebook MessengerXX
Send Notifications with ProcessesSend messages over SMS, WhatsApp, or Facebook MessengerXX
SOQL FOR UPDATE modifierLock records to prevent race conditions and thread safety issuesX
Strategy Builder Identify recommendations to surface on record pagesXX
SubflowsReduce flow complexity through reuseX
Subscribe to Platform Events with FlowReceive messages published through automationsX
Task ActionsDetermine assignment details given to a user by an automationX

Resources Relevant to Automated

ResourceDescriptionClear LogicData IntegrityBusiness Value
Apex Execution Governors & LimitsLearn how the Apex runtime engine enforces limitsXX
Architect's Guide to Record-Triggered AutomationChoose the right tool for record-triggered automationsXX
Batch Management ResourcesCreate, manage, schedule, and monitor batch jobsXX
Best Practices for SOQL and SOSL Improve query performance of applications with large data volumesX
Design Standards TemplateCreate design standards for your organizationXXX
Flow Bulkification in TransactionsDesign flows to operate against collectionsXX
Flow Data ConsiderationsLearn about schedule-triggered flows for batch dataXX
Flow DebuggingTest and troubleshoot flowsX
How Requests are ProcessedLearn how Salesforce processes jobs quickly and minimizes failuresXX
KPI Spreadsheet TemplateDetermine the business value of a particular metricXX
Making Callouts to External Systems from Invocable ActionsCall external systems from a Flow using ApexX
Mixed DML Operations Know which sObjects can be used together for DML in the same transactionXX
Order of ExecutionUnderstand the order of events for inserts, updates, and upsertsXX
Query Plan FAQOptimize queries involving large data volumesXX
Schedule-Triggered Flow ConsiderationsUnderstand the special behaviors of schedule-triggered flowsX
Transaction ControlGenerate a savepoint that specifies the current database stateXX
What Happense When a Flow Fails? Understand error handling in flowsXX
Workflow Automation Best Practice GuideGet started with Salesforce automationXXX
Working with Very Large SOQL QueriesWrite more efficient SOQL QueriesX

Tell us what you think

Help us keep Salesforce Well-Architected relevant to you; take our survey to provide feedback on this content and tell us what you’d like to see next.