flow-rollback-patterns

Use the Flow Rollback Records element to undo DML inside the current transaction. Covers when rollback is appropriate vs catastrophic, how to combine with fault paths, partial-commit pitfalls, and the interaction with publish-after-commit Platform Events. NOT for external-system rollback (use compensation patterns). NOT for Database.SavePoint in Apex (use apex-transaction-control).

Best use case

flow-rollback-patterns is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

Use the Flow Rollback Records element to undo DML inside the current transaction. Covers when rollback is appropriate vs catastrophic, how to combine with fault paths, partial-commit pitfalls, and the interaction with publish-after-commit Platform Events. NOT for external-system rollback (use compensation patterns). NOT for Database.SavePoint in Apex (use apex-transaction-control).

Teams using flow-rollback-patterns should expect a more consistent output, faster repeated execution, less prompt rewriting.

When to use this skill

  • You want a reusable workflow that can be run more than once with consistent structure.

When not to use this skill

  • You only need a quick one-off answer and do not need a reusable workflow.
  • You cannot install or maintain the underlying files, dependencies, or repository context.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/flow-rollback-patterns/SKILL.md --create-dirs "https://raw.githubusercontent.com/PranavNagrecha/AwesomeSalesforceSkills/main/skills/flow/flow-rollback-patterns/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/flow-rollback-patterns/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How flow-rollback-patterns Compares

Feature / Agentflow-rollback-patternsStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

Use the Flow Rollback Records element to undo DML inside the current transaction. Covers when rollback is appropriate vs catastrophic, how to combine with fault paths, partial-commit pitfalls, and the interaction with publish-after-commit Platform Events. NOT for external-system rollback (use compensation patterns). NOT for Database.SavePoint in Apex (use apex-transaction-control).

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

SKILL.md Source

# Flow Rollback Patterns

## Core concept — rollback is transaction-scoped

The Flow **Rollback Records** element undoes DML that happened in the CURRENT transaction. It does not:
- Undo DML from previous transactions (records created by a Scheduled Path yesterday are safe).
- Undo DML from a different top-level caller (if this flow was called by another flow, rollback only scopes the current flow's work in some cases; behavior varies).
- Undo external API calls already made.
- Stop Platform Events published with "Publish Immediately" semantics.

### What gets rolled back

- Create Records within this transaction.
- Update Records within this transaction.
- Delete Records within this transaction.
- Record saves propagated through triggers fired from this flow.

### What does NOT get rolled back

- Email sends (already queued at Send Email element time).
- HTTP callouts (already completed at the vendor).
- Platform Events published with Publish Immediately.
- File uploads already committed to ContentVersion.
- Sharing rule applications for those records (they're computed async).

## Recommended Workflow

1. **Map the DML sequence.** List every Create / Update / Delete in the flow, in order.
2. **Identify failure modes** that should trigger all-or-nothing rollback. Not every failure wants rollback — a logging failure shouldn't roll back the business work.
3. **Place Rollback Records in the fault path** of the element where the critical-failure could occur. Don't rollback preemptively.
4. **Combine with logging.** Rollback erases the records but not the audit trail — log to `Integration_Log__c` or similar BEFORE the rollback so you can forensically reconstruct what happened.
5. **Audit publish-after-commit events.** If the flow publishes Platform Events with Publish Immediately, rollback doesn't retract them. Switch to Publish After Commit or accept the phantom-event risk.
6. **Test the rollback path.** Force a fault in test and verify records are absent.

## Key patterns

### Pattern 1 — Create + Create + rollback-on-second-failure

```
[Get Account]
     │
     ▼
[Create Opportunity]    ────── fault path ──────►  [Rollback Records] → [End]
     │
     ▼
[Create OpportunityLineItem]  ─── fault path ────►  [Log to Integration_Log__c]
                                                          │
                                                          ▼
                                                    [Rollback Records]
                                                          │
                                                          ▼
                                                    [Send Email Alert]
                                                          │
                                                          ▼
                                                          [End]
     │
     ▼
[End] (success — both commits)
```

Design notes:
- On first-element fault: roll back and end (nothing to preserve, log not required for platform save failure).
- On second-element fault: log first (to capture the Opportunity Id that got created), THEN rollback, THEN notify.
- The admin gets an email with the log link; records never persist.

### Pattern 2 — Screen flow cancel

```
Screen 1: Gather inputs
Screen 2: [Create Records — Case]  ──►  session.caseId = {!Case.Id}
Screen 3: [Create Records — Task]   ──►  session.taskId = {!Task.Id}
Screen 4: "Confirm submit?"  ──►  [Yes] → End
                                   [No]  → [Rollback Records] → [End]
```

If the user hits "No" at the confirm step, both created records get undone. This is superior to "Delete Records" because it handles compound writes atomically — deletes would need separate DML statements with their own failure modes.

### Pattern 3 — Rollback with compensating Platform Event

When a Platform Event is published Publish Immediately and downstream subscribers have already acted, rolling back the local DML creates an inconsistency.

```
[Create Order]
     │
     ▼
[Publish Order_Created__e: Publish Immediately]  ◄── external billing system already charged
     │
     ▼
[Update Account — fault]
     │
     fault path
     ▼
[Rollback Records]      ◄── undoes Order + Account
[Publish Order_Cancelled__e] ◄── tell subscribers to undo their side
```

Publish-After-Commit would be better, but sometimes business constraints prevent the change. A compensating event is the recovery pattern.

### Pattern 4 — Don't rollback on logging failure

```
[Business DML: Create + Update] ─── success ─►
     │
     ▼
[Log success to Integration_Log__c]  ─── fault path ─►  [Silent End]
```

A logging failure should NOT trigger rollback of the business work. The Silent End on the fault path is deliberate — the business work committed, the log failed, an admin can reconstruct from system logs later.

## Bulk safety

- Rollback Records undoes all DML in the transaction, not just one record. Bulk is handled automatically.
- In a record-triggered flow processing 200 records, a fault in record #150 rolls back ALL 200 by default. If you need per-record rollback, use Apex (SavePoint) — Flow can't do per-record scope within a batch.
- Rollback counts against the transaction limits (the undo operations still use DML slots).

## Error handling

- **Rollback itself succeeds almost always.** It's a platform primitive with minimal failure modes.
- **Log BEFORE rolling back,** not after — the log record would itself be rolled back.
- **Fault path on the element AFTER rollback** should capture rollback failures (rare, but possible if the session is corrupt).

## Well-Architected mapping

- **Reliability** — rollback is the only way to get all-or-nothing semantics in Flow. Without it, partial commits accumulate garbage data that requires manual cleanup.
- **Security** — incomplete records may violate business rules (a Case without Account) that bypass validation. Rollback restores the invariant.

## Gotchas

See `references/gotchas.md`.

## Testing

In Apex test classes that invoke the flow:

```apex
@IsTest
static void testRollbackOnSecondDMLFailure() {
    // Setup: trigger a condition that makes the 2nd DML fail.
    Account a = new Account(Name='Test');
    insert a;
    // Pre-create a record that will collide with the flow's 2nd DML.
    ...

    Test.startTest();
    // Invoke flow; expect the whole transaction to rollback.
    try {
        Flow.Interview.MyFlow flow =
            new Flow.Interview.MyFlow(new Map<String, Object>{'accountId' => a.Id});
        flow.start();
    } catch (Exception e) {
        // Expected.
    }
    Test.stopTest();

    // Assert no Opportunity was created.
    System.assertEquals(0, [SELECT COUNT() FROM Opportunity WHERE AccountId = :a.Id]);
}
```

## Official Sources Used

- Salesforce Help — Flow Rollback Records Element: https://help.salesforce.com/s/articleView?id=sf.flow_ref_elements_rollback.htm
- Salesforce Help — Flow Fault Connector Paths: https://help.salesforce.com/s/articleView?id=sf.flow_ref_faults.htm
- Salesforce Developer — Transaction Control in Flow and Apex: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_transaction_control.htm
- Salesforce Developer — Platform Events Developer Guide: https://developer.salesforce.com/docs/atlas.en-us.platform_events.meta/platform_events/

Related Skills

mfa-enforcement-patterns

8
from PranavNagrecha/AwesomeSalesforceSkills

Design MFA enforcement: auto-enablement, Salesforce Authenticator rollout, exceptions, service accounts, API-only users, SSO interop, and audit. Trigger keywords: MFA, multi-factor, two-factor, Salesforce Authenticator, MFA exception, MFA SSO, api-only MFA. Does NOT cover: end-user password policies, device-trust posture, or non-Salesforce IdP configuration.

ip-range-and-login-flow-strategy

8
from PranavNagrecha/AwesomeSalesforceSkills

Design and implement Salesforce Login Flows (Screen Flows assigned to profiles or Experience Cloud sites) that run post-authentication to enforce conditional MFA, IP-based branching, terms-of-service acceptance, or user data collection. Covers Login Flow creation in Flow Builder, profile/site assignment, IP-aware decision logic, and ConnectedAppPlugin extension points. NOT for static IP allowlisting or profile Login IP Ranges (see network-security-and-trusted-ips), org-wide session policies, or SSO/SAML IdP configuration.

encrypted-field-query-patterns

8
from PranavNagrecha/AwesomeSalesforceSkills

Design SOQL, filters, reporting, and indexes against Shield Platform Encryption fields. Trigger keywords: Shield Platform Encryption, encrypted field query, probabilistic vs deterministic encryption, encrypted SOQL filter, encrypted field index. Does NOT cover: Classic Encryption (deprecated), field-level security policy, or tenant secret key rotation.

customer-data-request-workflow

8
from PranavNagrecha/AwesomeSalesforceSkills

Implement GDPR/CCPA data subject rights (access, deletion, rectification) using Salesforce Privacy Center and/or custom workflow. NOT for general backup or org-level data retention policy.

apex-managed-sharing-patterns

8
from PranavNagrecha/AwesomeSalesforceSkills

Grant row-level access programmatically via __Share records when declarative sharing rules cannot express the policy. NOT for OWD, role hierarchy, or criteria-based sharing rule design.

omnistudio-vs-flow-decision

8
from PranavNagrecha/AwesomeSalesforceSkills

Use when choosing between OmniStudio (OmniScript / Integration Procedure / FlexCard / DataRaptor) and Flow / Screen Flow / Apex for a given capability. Triggers: 'omnistudio or flow', 'omniscript vs screen flow', 'integration procedure vs subflow', 'flexcard vs lightning page'. NOT for general automation selection across Workflow/Process Builder/Apex (see automation-selection tree).

omnistudio-testing-patterns

8
from PranavNagrecha/AwesomeSalesforceSkills

Use when testing or validating OmniStudio components — OmniScript preview, Integration Procedure step debugging, DataRaptor field-mapping validation, and end-to-end UTAM-based automation. NOT for Apex unit testing or standard Flow debugging.

omnistudio-error-handling-patterns

8
from PranavNagrecha/AwesomeSalesforceSkills

Use when designing fault behavior across Integration Procedures, DataRaptors, OmniScripts, and FlexCards — error routing, user-facing messaging, retry semantics, and idempotency. Triggers: 'omnistudio error', 'integration procedure fault', 'dataraptor error handling', 'omniscript retry', 'flexcard action failure'. NOT for general Apex exception design or Flow fault paths.

omnistudio-ci-cd-patterns

8
from PranavNagrecha/AwesomeSalesforceSkills

Use when designing or implementing CI/CD pipelines for OmniStudio components — DataPack export/import, versioning, environment promotion, and automated deployment. NOT for standard Salesforce metadata CI/CD or Apex-only pipelines.

omniscript-design-patterns

8
from PranavNagrecha/AwesomeSalesforceSkills

Use when designing or reviewing OmniScripts for guided experiences, step structure, branching, save/resume, and the boundary between OmniScript, Integration Procedures, DataRaptors, and custom LWCs. Triggers: 'omniscript design', 'too many steps in omniscript', 'save and resume omniscript', 'branching in omniscript', 'when should this be an integration procedure'. NOT for deep Integration Procedure or DataRaptor design when the guided interaction layer is not the main concern.

integration-procedure-cacheable-patterns

8
from PranavNagrecha/AwesomeSalesforceSkills

Use when designing Integration Procedures (IPs) with platform cache to cut latency and callout load. Covers cache key design, TTL selection, per-user vs org-wide partitions, invalidation on data changes, and safe fallback on cache miss/stale. Does NOT cover general IP authoring (see omnistudio-error-handling-patterns) or LWC client-side caching.

flexcard-design-patterns

8
from PranavNagrecha/AwesomeSalesforceSkills

Use when designing, building, or reviewing OmniStudio FlexCards — including data source selection, card states, actions, conditional visibility, flyout configuration, and child card iteration. Triggers: 'FlexCard', 'card template', 'flyout', 'card action', 'card state', 'data source', 'child card', 'conditional visibility'. NOT for OmniScript design, standalone LWC development, or Apex controller architecture outside the FlexCard context.