Close Menu
SalesforceCodex
    Facebook X (Twitter) Instagram
    Trending
    • Introducing Agentforce3 to Salesforce Developers
    • The Ultimate Guide to Apex Order of Execution for Developers
    • How to Handle Bulkification in Apex with Real-World Use Cases
    • How to Confidently Manage Transactions in Salesforce Apex
    • Building a Dynamic Tree Grid in Lightning Web Component
    • 10 Salesforce Chrome Extensions to Boost Your Productivity
    • How to Build a Generic Modal Window in Lightning Web Component
    • Top 10 Salesforce Flow Features of Salesforce Summer ’25
    Facebook X (Twitter) Instagram
    SalesforceCodex
    Subscribe
    Monday, July 21
    • Home
    • Blogs
      • Architecture
      • Apex
      • Lightning Web Components
      • Integration
      • Flows & Automation
      • Best Practices
      • Questions
      • News
      • Books Testimonial
    • Hire Me
    • Certification
      • How to Prepare for Salesforce Integration Architect Exam
      • Certification Coupons
    • Downloads
    • About Us
      • Privacy Policy
    SalesforceCodex
    Home»Salesforce»Apex»The Ultimate Guide to Apex Order of Execution for Developers

    The Ultimate Guide to Apex Order of Execution for Developers

    Dhanik Lal SahniBy Dhanik Lal SahniJuly 20, 2025No Comments14 Mins Read
    Facebook Twitter Pinterest LinkedIn Tumblr Email
    Order of Execution | Salesforce
    Share
    Facebook Twitter LinkedIn Pinterest Email

    The order of execution is a sequence of events that is triggered behind the scenes to ensure data consistency and integrity. The order of execution is crucial for Salesforce developers and administrators to prevent unintended behaviors, such as recursive trigger calls, validation rule failures, or data integrity issues. In this post, we will explain the order of execution, its importance, and best practices to follow.

    Why is the order of execution important?

    Salesforce provides many features that will be impacted by the order of execution. If we implement features properly by understanding the order of execution, then it will ensure data integrity, predictable automation behavior, and efficient performance; otherwise, we will face conflicts between automation. Below are Salesforce features that will be impacted by the order of execution.

    1. Validation Rules

    Validation rules are declarative tools for ensuring data integrity, such as preventing a record from saving if a required field is empty. These checks data against set criteria at specific points, and their placement can lead to failures if data is modified earlier in the sequence.

    2. Triggers (Before and After)

    Triggers are custom code executed before and after any DML operation performed on object.

    Before triggers are ideal for data validation, setting default values, or modifying the record itself. For example, we want to ensure a field meets a specific format. Since the record isn’t saved yet, any field changes in this event are part of the current transaction and don’t require additional DML operations.

    After triggers are executed after the record is saved but before the database commit. After triggers are required when we need to perform some action on related records. For example, we want to update child records, send notifications, or integrate with external systems via callouts.

    3. Workflow Rules and Field Updates

    Workflows are used to automate simple tasks based on criteria, such as updating a field or sending an email alert. If a workflow field update occurs, it can trigger additional steps, like re-running duplicate rules or triggers, but custom validation rules are not re-evaluated. It can potentially cause recursion if not managed properly. Salesforce will soon retire this feature, and it is recommended to use Flow instead.

    4. Flows

    Flows (record-triggered flows) let us automate tasks without writing code. Before Save flows can set field values or do calculations before the record is saved. After Save flows run after the record is saved and can update related records. Salesforce suggests using flows for most business logic to avoid using Apex code.

    5. Assignment and Auto-Response Rules

    These features are specific to the lead and case objects. Assignment rules are used to automate ownership, and auto-response rules send email notifications. So, if any ownership assignment is required for the lead object or the email needs to be sent for the case object, we can utilize these features. No need to create a flow or any custom Apex class.

    6. Escalation Rules

    This feature is also related to the case object. It automatically escalates cases based on specific conditions and time-based criteria. Escalation Rules are processed after the record is saved and after workflow rules and flows. It won’t interfere with validation rules, triggers, or before-save flows.

    7. Roll-Up Summary Fields

    Roll-Up Summary fields are calculated fields on a parent object (like Account or Opportunity) that summarize data from related child records (like Contacts or OpportunityLineItems). This feature is triggered after child records are inserted, updated, or deleted.

    8. Sharing Rules

    Sharing rules are impacted by the order of execution. Sharing rules are evaluated after the record is committed to the database, so users gain or lose access only when the data is finalized. We should consider the order of execution while creating a custom Apex sharing rule.

    9. Asynchronous Processes

    Asynchronous processes are used to complete time-consuming operations like callouts, complex calculations, or large data processing. This is triggered after the main transaction is complete, improving both performance and user experience.

    These Salesforce features are impacted by the order of execution, and vice versa. The order of execution helps keep data accurate, but if not planned properly, it can cause problems like validation errors, unexpected results, or slow performance. For example, if a trigger changes a field before saving, it might cause a validation rule to fail. Also, workflow rules that update records can run triggers again, which may lead to repeated or looping actions.

    Detailed Steps in the Order of Execution

    1. Loads Initial record

    In this event, the original record is loaded from the database, or the record is initialized for an upsert statement.

    2. System Validation (for UI edits)

    During this step, the field values on the record are updated. If a new record is being inserted, the field values are set from those provided in the request. In this step, below system validation is performed

    1. Field Data Types Are Checked—Ensures the entered data matches the field’s data type
    2. Required Fields Are Verified—All fields marked as “Required” on the object level (not just page layout) must have values.
    3. Maximum Field Lengths Are Enforced—If the user exceeds the allowed character limit (e.g., 255 characters for a text field), the system throws an error.
    4. Unique Constraints Are Checked—Ensures fields marked as unique don’t have duplicate values in the database.
    5. Foreign Key (Lookup) Constraints Are Validated—Ensures referenced records (like Account in Contact) exist and are valid.

    If the request is passed from the standard UI page, then validation from 1 to 4 is performed. And if the request is from custom code or an API, then all 5 validations are performed.

    Note: System validations run even if triggers are bypassed.

    3. Executes before record-triggered flows

    In this step, Salesforce executes any flows (for the current record object) that are set to run before the record is saved to the database. Key characteristics of this step

    • The changes made in these flows are saved without the need for a DML operation, which improves performance.
    • We can update only the triggering record.
    • No records are yet committed to the database at this point.

    4. Executes all before triggers

    In this step, before triggers (before insert, before update, or before delete) that are created for the current record object are fired.

    1. We can use this step to modify the record values, like setting default values or correcting data.
    2. We can validate input values and throw validation errors. If validation errors are thrown, then execution stops here.
    3. Any changes made to the record here will be saved automatically; we don’t need to write another DML statement.

    5. Runs most custom validation

    As values are updated using the before trigger and flow, in this step, all system validations are performed again. The below tasks are performed in this step

    1. All system validations performed again
    2. Salesforce evaluates any custom validation rules that are set up using formulas.
    3. If a validation rule fails, the operation is stopped, and the user sees an error message.

    6. Executes duplicate rules

    In this step, Salesforce checks whether the current record being saved matches existing records based on predefined duplicate rules. These rules help prevent or alert users about possible duplicate data.

    Salesforce uses matching rules to compare the new or updated record with existing records. If a potential duplicate is found, and the Duplicate Rule is set to:

    • Block: The operation will be stopped, and an error message will be shown.
    • Allow but Alert: The operation continues, but a warning is shown (mostly in UI, not in code).
    • Allow: The record is saved without any warning.

    7. Saves the record to the database but doesn’t commit yet

    In this step, the record is saved in the database. Below are key points for this step

    1. Salesforce temporarily saves the record to memory (called the savepoint),
    2. record is not permanently written (committed) to the database yet.
    3. This is done so after triggers, processes, and other post-save logic can access the record
    4. The actual commit happens only at the end of the full transaction

    This step important as

    1. It allows after triggers to access the record with an assigned ID and pretend it’s already in the database.
    2. If something fails later (like a failed flow or unhandled exception), Salesforce can roll back to this point without corrupting data.

    8. Executes all after triggers

    In this step, all after triggers (after insert, after update, and after delete) are created on the current record object are executed. Key points for this step are

    1. Record IDs (for newly inserted records) are accessible.
    2. We can access auto-calculated fields like formulas or roll-up summaries
    3. We can perform DML operations on related records

    9. Execute assignment rules

    This step is performed only for Lead and Case object records. Ownership of a Lead or Case record is assigned automatically based on predefined active assignment rules. These rules check record conditions and assign the record to a user or queue accordingly.

    10. Executes auto-response rules

    In this step, Salesforce checks and runs auto-response rules that are set up for Lead and Case objects. The following tasks are performed:

    • Salesforce evaluates any active auto-response rules based on the criteria.
    • If a rule matches, it sends an email response automatically to the person who submitted the record.
    • The email content is based on the configured email template.
    • Auto-response rules are only triggered when a new record is inserted, not on update

    11. Executes workflow rules

    In this step, Salesforce checks for any active workflow rules that meet the criteria based on the current state of the record and then performs the defined actions. The following tasks are performed in this step.

    1. Evaluate Workflow Rules: Salesforce checks all active workflow rules that apply to the object and event (insert, update).

    2. If the criteria are met, Salesforce executes the associated actions, which may include:

    • Field Updates
    • Email Alerts
    • Tasks
    • Outbound Messages

    3. Re-run system validations, but don’t re-run custom validation rules, flows, duplicate rules, processes built with, and escalation rules.

    4. Workflow Field Updates: If any field updates happen:

    • The record is updated again internally.
    • Salesforce re-evaluates validation rules and before/after triggers once more.
    • May cause recursion if not handled carefully

    4. Queue Time-Based Actions: Any time-dependent actions (e.g., send an email after 3 days) are queued to run later.

    12. Executes escalation rules

    This step is only executed for the case object. Salesforce checks if any active escalation rules apply to the Case record being created or updated.

    If the rule conditions are met:

    • Escalation actions are scheduled to trigger based on defined time limits.
    • The Case can be reassigned to another user or queue.
    • Email notifications can be sent.
    • If no escalation rules are defined, Salesforce skips this step.

    13. Executes Salesforce Flow automations

    In this step, Salesforce runs flows configured to execute after the record is saved. These are flows which executed by workflows or other flows. Orders for the execution of these flows are not guaranteed.

    14. Executes record-triggered flows after save

    This step occurs after the record is saved to the database but before the transaction is fully committed. In this step, flows can

    • Access the final version of the record (after DML).
    • Perform actions like updating related records, sending emails, or creating tasks.
    • Access related records using Get Records.
    • Can trigger additional DML, which may initiate another order of execution cycle.

    15. Execute entitlement rules

    This step is also performed for only case records and is part of the service process in Salesforce.

    • When a Case is created or updated, Salesforce checks whether any active Entitlement Processes or Milestone rules apply based on the case criteria.
    • Entitlement Rules automatically assign entitlements (like support contracts or service levels) and milestones (time-based actions) to Case records.
    • If a match is found, it starts tracking milestones like “First Response Due” or “Resolution Due” based on your service-level agreements (SLAs).

    16. Roll-up summary calculations

    In this step, Salesforce updates the roll-up summary fields on the parent record when related child records are added, changed, or removed. Roll-up summaries are only supported natively on master-detail relationships. Updating the parent due to roll-up summary can execute after triggers, workflows, and flows on the parent record.

    17. Grandparent roll-up calculations

    In this step, the rollup summary is calculated for the grandparent record. When a child record is updated, and that update triggers roll-up summary fields on the parent object, Salesforce also checks and updates roll-up summaries on the grandparent object.

    18. Criteria-based sharing evaluation

    This step ensures that record access (sharing) is correctly updated based on the criteria-based sharing rules.

    • Salesforce re-evaluates sharing rules that are based on specific field values or criteria.
    • It checks whether the record still meets or no longer meets the conditions for those sharing rules.
    • Based on the updated sharing rule, Salesforce grants or revokes access to users or groups accordingly.

    19. Commits all DML operations to the database

    This is the final step in the Apex Order of Execution. It means Salesforce permanently saves all the changes made during the transaction into the actual database.

    Key points for this step are

    1. Inserts/Updates/Deletes committed to the database
    2. Triggers and Automations Stop Running. No further logic (like triggers, flows, workflows) will run after this point.
    3. For new records, Record IDs are finalized
    4. If everything succeeds:, the user gets a success confirmation.
    5. If there’s an error (e.g., DML exception not caught), the whole transaction rolls back.

    20. Executes all after-commit logic

    In this stage, Salesforce runs logic that doesn’t affect the current transaction, but happens after the data is permanently stored.

    Action can be performed during this step

    1. Sending Emails – Emails triggered by workflow rules, flows, approval processes, or email alerts.
    2. Asynchronous Code – Queued future methods, Queueable, Batch Apex, and @future jobs start execution.
    3. Enqueued Platform Events- Platform events that were published during the transaction are now delivered to subscribers.
    4. Post-commit logic in Managed Packages – Any logic from managed packages that is set to run after the commit.
    5. Chained Queueables – If a Queueable job enqueues another Queueable, it happens after the commit
    Order of Execution | SalesforceCodex
    Order of Execution Source: Salesforce.com

    Other Considerations with Apex Order of Execution

    Besides the main steps, the following points should also be considered along with Apex Order of Execution in Salesforce. These help make sure your automation works smoothly, runs efficiently, and doesn’t cause unexpected problems.

    1. Trigger Recursion

    • Updates from workflows, flows, or triggers can re-fire the same or other triggers.
    • Use static variables or recursion control patterns to prevent infinite loops.

    2. Bulk Operations

    • Always design triggers and automation to handle bulk data (e.g., 200 records at once).
    • Avoid using SOQL or DML inside for loops to prevent governor limits. Check out our post to handle DML inside a loop.

    3. Validation Rule Dependencies

    • Field changes in before triggers can impact validation rule outcomes.
    • Ensure field values are finalized before validation rules run.

    4. Order of Trigger Execution (Multiple Objects)

    • There’s no guaranteed order when triggers on different objects are involved in the same transaction.
    • Design triggers with a one-trigger-per-object pattern to manage execution order.
    • Plan your logic with minimal cross-object dependencies.

    5. Duplicate Rule Behavior

    • Duplicate rules run after triggers but before workflow rules.
    • This can stop record creation or update unless configured properly.

    6. Flow Timing

    • Flows (especially record-triggered ones) may run before or after triggers depending on their configuration.
    • Understand when your flows fire and what fields they modify.

    7. Rollback Behavior

    • If any error occurs before the commit, the entire transaction is rolled back.
    • But errors after commit (e.g., in future methods, async jobs) do not roll back the main transaction.

    8. Record Changes Post-Commit

    • Any logic run after the commit (like sending emails or handling platform events) can’t change the current transaction’s data.

    9. Chained Automation Complexity

    • A trigger can call a flow, which updates a record, which re-triggers another trigger. This chain reaction can be hard to debug.
    • Use logs and debug statements to trace execution paths.

    Summary

    The Apex Order of Execution helps you understand how Salesforce handles record changes like insert, update, or delete. It’s useful for both developers and admins because it allows them to:

    🔄 Create reliable automation by knowing the right time triggers, flows, and rules run.
    🛡️ Avoid problems like endless loops, failed checks, or unexpected changes.
    ⚙️ Improve system performance by cutting out extra steps and staying within limits.
    🧪 Test and fix issues more easily by following the exact order in which things happen.
    📊 Keep data accurate and consistent across related records and processes.

    References

    Triggers and Order of Execution

    Related Posts

    • Optimizing Salesforce Apex Code
    • Efficient Ways to Debug Salesforce Platform Events
    • How to Handle Bulkification in Apex with Real-World Use Cases
    • Handle Heap Size for Apex Code Optimization
    • Build Scalable Solutions with Salesforce
    • How to Correctly Publish Platform Event Using Salesforce Apex

    apex apex best practices apex code apex code optimization Apex logging apex order of execution apex performance apex trigger best practices batch apex external callout flow one trigger per object optimize apex trigger optimize trigger salesforce salesforce apex trigger helper class trigger order of execution
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticleHow to Handle Bulkification in Apex with Real-World Use Cases
    Next Article Introducing Agentforce3 to Salesforce Developers
    Dhanik Lal Sahni
    • Website
    • Facebook
    • X (Twitter)

    With over 18 years of experience in web-based application development, I specialize in Salesforce technology and its ecosystem. My journey has equipped me with expertise in a diverse range of technologies including .NET, .NET Core, MS Dynamics CRM, Azure, Oracle, and SQL Server. I am dedicated to staying at the forefront of technological advancements and continuously researching new developments in the Salesforce realm. My focus remains on leveraging technology to create innovative solutions that drive business success.

    Related Posts

    By Dhanik Lal Sahni5 Mins Read

    Introducing Agentforce3 to Salesforce Developers

    July 21, 2025
    By Dhanik Lal Sahni6 Mins Read

    How to Handle Bulkification in Apex with Real-World Use Cases

    July 15, 2025
    By Dhanik Lal Sahni7 Mins Read

    How to Confidently Manage Transactions in Salesforce Apex

    July 13, 2025
    Add A Comment
    Leave A Reply Cancel Reply

    Ranked #1 Salesforce Developer Blog by SalesforceBen.com
    SFBenTopDeveloper
    Ranked #4 Salesforce Developer Blog by ApexHours.com
    ApexHoursTopDevelopers
    Categories
    Archives
    Tags
    apex (115) apex best practices (4) apex code best practice (9) apex code optimization (5) Apex logging (4) apex rest (11) apex trigger best practices (5) architecture (22) Asynchronous apex (9) AWS (5) batch apex (10) batch processing (4) code optimization (9) custom metadata types (5) design principle (9) flow (16) google (6) google api (4) integration (19) integration architecture (6) lighting (8) lightning (66) lightning-combobox (5) lightning-datatable (10) lightning component (32) Lightning web component (64) lwc (53) named credential (8) optimize apex (4) optimize apex code (5) optimize apex trigger (4) Permission set (4) Queueable (9) rest api (23) S3 Server (4) salesforce (147) salesforce apex (51) salesforce api (4) salesforce api integration (5) Salesforce Interview Question (4) salesforce news (5) salesforce question (5) solid (6) tooling api (5) Winter 20 (8)

    Get our newsletter

    Want the latest from our blog straight to your inbox? Chucks us your detail and get mail when new post is published.
    * indicates required

    MailChimp

    Facebook X (Twitter) Instagram Pinterest YouTube Tumblr LinkedIn Reddit Telegram
    © 2025 SalesforceCodex.com. Designed by Vagmine Cloud Solution.

    Type above and press Enter to search. Press Esc to cancel.

    Ad Blocker Enabled!
    Ad Blocker Enabled!
    Our website is made possible by displaying online advertisements to our visitors. Please support us by disabling your Ad Blocker.