Skip to content

Declarative vs Programmatic Solutions

The CTA Review Board expects you to articulate why you chose declarative or programmatic for each requirement - not just what you chose. This is a spectrum, not a binary choice, and the best architectures blend both. The core CTA judgment is knowing when to follow the declarative-first principle and when to deliberately break it.

CTA Exam Signal

The review board does not want to hear “I used Flow because declarative is always better.” They want to hear “I chose Flow here because the logic is straightforward CRUD operations with simple branching, the admin team can maintain it, and the governor limit profile is favorable - but I chose Apex for the high-volume integration handler because Flow’s shared CPU time ceiling and per-transaction SOQL/DML limits would be exceeded.”

Flow Builder: The Declarative Powerhouse

Flow Builder is Salesforce’s primary declarative automation tool, and it has evolved dramatically. Understanding its capabilities and limits is essential.

Foundational Context

For foundational Flow Builder concepts (creating flows, element types, basic configuration), see Build Flows with Flow Builder (Trailhead). This page focuses on architect-level trade-offs: governor limit profiles, execution order implications, and when Flow breaks down at scale.

Flow Types

Flow TypeTriggerUse CaseContext
Record-Triggered FlowDML on a recordBefore/after save automationRuns in record transaction
Screen FlowUser interactionGuided UI experiencesInteractive, supports LWC
Schedule-Triggered FlowTime-basedBatch processing, remindersRuns as Automated Process user
Platform Event-TriggeredPlatform EventEvent-driven automationAsync, separate transaction
Autolaunched FlowInvoked by code/processReusable logic modulesNo UI, callable from Apex
OrchestrationMulti-step processesApproval-like workflowsLong-running, multi-stage

Record-Triggered Flow Execution Phases

Understanding the three phases is critical for avoiding recursion and governor limit issues:

Three-phase sequence showing before-save flow, Apex triggers, validation, database save, after-save flows, and scheduled paths in order.
Figure 1. Before-save flows run before the record hits the database and can modify the triggering record without a DML statement. After-save flows run post-commit and require DML to update related records, consuming shared governor limits, which makes the before/after choice a performance and limit-budget decision.

Before-Save vs After-Save

Before-save flows can modify the triggering record without a DML statement (no governor limit hit). After-save flows require DML to update related records. Use before-save when you only need to modify the triggering record - it is faster and cheaper on limits.

Flow Governor Limits

These limits are where Flow’s declarative simplicity becomes an architectural risk:

LimitValueWhy It Matters
Elements per interviewNo hard cap (removed in API v57.0+)Constrained by CPU time, not element count
SOQL queries per interview100 (shared with Apex transaction)Flow Get Records counts against this
DML statements per interview150 (shared with Apex transaction)Flow Create/Update/Delete counts here
CPU time10,000 ms sync / 60,000 ms async (shared)Formula-heavy flows consume CPU - this is the practical ceiling
Heap size6 MB (shared)Large collection variables can hit this
Screen Flow timeoutGoverned by session timeout settings (configurable per profile)Long-running screen flows expire based on org session policy

The One Automation Per Object Rule

Salesforce best practice: have one record-triggered flow per object per trigger event. This is architectural guidance, not a platform enforcement.

Why this matters:

  • Multiple flows on the same object create unpredictable execution order
  • Debugging grows exponentially harder with multiple entry points
  • Governor limits are shared across all automations in a transaction
  • Cross-flow dependencies create hidden coupling

How to implement:

  • Create one “master” record-triggered flow per object
  • Use subflows for logical separation within the master flow
  • Use Decision elements to route to the correct logic path
  • Document the routing logic so admins can follow it
A single master record-triggered flow on Account routes to four separate subflows, each handling one distinct logical concern.
Figure 2. The one-flow-per-object pattern routes all Account automation through a single entry point, preventing unpredictable execution order and making governor limit budgeting predictable. Each subflow handles one concern and can be modified independently without touching the master flow.

Apex: When Code Is the Right Choice

Apex is not a fallback. It is the right tool when declarative solutions introduce more complexity, risk, or maintenance burden than code.

When Apex Is Clearly Better

ScenarioWhy Apex Wins
Complex data transformationsLoops with conditional logic, maps, and sets are cleaner in code
High-volume processingBatch Apex handles millions of records; Flow struggles past 50K
Multi-object transactionsApex gives explicit transaction control and rollback
External service calloutsHttpRequest with retry logic, error handling, circuit breakers
Custom REST/SOAP endpointsApex web services for inbound integrations
Complex sharing calculationsApex managed sharing for dynamic sharing rules
Performance-critical logicApex is faster; compiled vs interpreted Flow
Bulkification requirementsApex triggers naturally bulkify; Flow requires careful design

Apex Invocable Actions: The Bridge

Invocable Actions (@InvocableMethod) are the key integration point between declarative and programmatic:

@InvocableMethod(label='Calculate Territory Assignment'
description='Assigns territory based on geo rules')
public static List<Result> assignTerritory(List<Request> requests) {
// Complex logic that would be painful in Flow
// But callable from Flow as an Action
}

Why this pattern matters architecturally:

  • Admins can invoke complex logic without understanding Apex
  • Business logic stays in code where it is testable and version-controlled
  • Flow handles the orchestration; Apex handles the computation
  • The implementation can be swapped without changing the Flow

Custom LWC in Screen Flows

Screen Flows support embedding Lightning Web Components for custom UI:

Use cases:

  • Complex data entry forms with real-time validation
  • Interactive data visualization within a flow
  • Custom lookup components with advanced filtering
  • File upload with preview and metadata extraction

Trade-offs:

  • Increases development complexity (LWC + Flow)
  • Requires developer for the LWC portion
  • Testing requires both Apex/LWC tests and Flow tests
  • LWC must implement FlowAttributeChangeEvent for data binding

Order of Execution

Understanding the full Salesforce order of execution is essential for debugging and predicting behavior. This is one of the most commonly tested CTA topics.

Complete 17-step sequence from initial validation through before-save flows, Apex triggers, workflow re-execution, database commit, and async post-commit logic.
Figure 3. Workflow field updates trigger one additional before-and-after trigger cycle, consuming governor limits a second time, without re-running validation rules or before-save flows. Roll-up summary recalculations cascade the entire execution chain onto the parent object, a common source of unexpected behavior in complex org configurations.

Color Legend

Green = Flow execution points. Orange/Red = Apex trigger execution points. Dark blue = Workflow Rules (deprecated — creation blocked since Winter ‘23; end-of-support Dec 31, 2025 means existing rules still execute but receive no bug fixes; migrate to Flow). Process Builder creation was blocked in Summer ‘23. Red = Re-execution cycle caused by workflow field updates. Gold = Database commit point. Understanding where each fires in the sequence prevents conflicts between declarative and programmatic automations.

The Workflow Re-execution Trap

When workflow field updates modify a record, Salesforce re-runs before and after triggers one additional time. This does NOT re-run validation rules or before-save flows. This re-execution loop is a common source of unexpected behavior and governor limit consumption. Always account for this in governor limit budgeting.

Recursion and Re-evaluation

  • Before-save flows do not cause re-evaluation (they modify the record in memory)
  • After-save flows that update the triggering record cause re-entry through the order of execution
  • Apex triggers can cause re-entry; use static variables to prevent infinite recursion
  • Cross-object updates from roll-up summaries trigger the parent object’s automation chain
  • Workflow field updates trigger one additional before + after trigger cycle (but NOT validation rules or before-save flows)

Flow vs Apex Capability Matrix

This matrix helps identify which tool supports a given capability quickly. Use it during CTA scenario analysis to justify technology choices.

CapabilityFlowApexVerdict
Simple field updatesYes - Before-Save FlowYes - but overkillFlow
Complex data transformsLimited - clunky loopsYes - maps, sets, sortingApex
Bulk processing (50K+)No - hits limitsYes - Batch ApexApex
External calloutsExternal Services onlyYes - full HTTP controlApex (or hybrid)
Transaction rollbackNo savepointsYes - Database.setSavepointApex
Automated testingLimited - manual + debugYes - @isTest, CI/CDApex
Dynamic SOQLNoYes - Database.queryApex
Custom REST endpointsNoYes - @RestResourceApex
Platform event publishYesYesEither
Scheduled executionYes - Scheduled FlowsYes - SchedulableEither (volume-dependent)
User-guided processesYes - Screen FlowsPossible but heavyweightFlow
Approval processesYes - integrates nativelyRequires custom implementationFlow
Error handlingBasic Fault pathsFull try-catch with custom logicApex
Version control diffsMetadata XML (hard to read)Source code (meaningful diffs)Apex

Reading This Matrix

Where the verdict says “Flow,” that is a strong signal to go declarative. Where it says “Apex,” that is a strong signal to go programmatic. Where it says “Either,” use the volume and maintainability context from the decision guides to break the tie.

Decision Matrix: Flow vs Apex

Routes automation requirements through data transformation complexity, volume, user interaction, and callout type to select the right declarative or programmatic tool.
Figure 4. The Invocable Action bridge is the key hybrid pattern: complex logic stays in testable, version-controlled Apex while Flow handles orchestration and remains admin-maintainable. External Services with OpenAPI spec eliminates the need for Apex callouts when the API is simple and the volume is low.

Color Legend for Decision Tree

Green = Declarative (admin-maintainable). Orange = Hybrid (admin + developer). Red = Programmatic (developer-required). Use this to communicate staffing and maintenance implications to stakeholders.

Automation Strategy Architecture

In enterprise scenarios, automation is rarely a single tool. The strongest architectures blend Flows, Apex, and Platform Events into a layered strategy. This diagram shows how the three work together in a typical CTA scenario.

Four-layer automation model with synchronous user transactions, async event-driven processing, scheduled batch operations, and a configuration layer driving all three.
Figure 5. Publishing a Platform Event from the synchronous user layer decouples heavy callouts and complex processing into an async context with its own governor limits. The configuration layer using Custom Metadata Types and Named Credentials makes all three execution layers environment-agnostic and deployment-safe.

CTA Presentation Strategy

Present your automation architecture in these four layers: synchronous user transactions, asynchronous event-driven processing, scheduled batch operations, and the configuration layer that makes everything environment-agnostic. This shows the review board you think about operational architecture, not just code.

Automation Strategy for CTA Scenarios

Assessment Checklist

When designing automation for a CTA scenario, evaluate each requirement against:

  1. Complexity: Can the logic be expressed in a Flow Decision element, or does it need nested loops with conditional maps?
  2. Volume: How many records will this process? Flow is fine for hundreds; Apex Batch for millions.
  3. Maintainability: Who will maintain this after go-live? If the customer has admins but not developers, Flow is operationally better.
  4. Performance: Is this in a synchronous user transaction? Apex is faster for complex operations.
  5. Testing: Flow testing is manual and limited. Apex testing is automated and CI/CD-friendly.
  6. Integration: Does this touch external systems? Apex gives you retry logic, circuit breakers, and error handling.
  7. Transaction control: Do you need explicit savepoints and rollbacks? Apex only.

Common CTA Scenario Patterns

Scenario PatternRecommended ApproachRationale
Lead assignment with territory rulesFlow + Invocable ApexAdmins manage routing rules; Apex handles geo-calculation
Order processing with inventory checkApex trigger + platform eventsTransaction integrity + async inventory notification
Customer onboarding wizardScreen Flow + custom LWCGuided experience with complex form inputs
Nightly data sync from ERPBatch Apex + SchedulableVolume, error handling, retry logic
Approval process with dynamic routingFlow + Approval ProcessDeclarative routing with standard approval framework
Real-time lead scoringBefore-save FlowSimple field calculation, no DML needed
Multi-object data validationApex triggerCross-object queries and validation in single transaction

Anti-Patterns to Avoid

Common Automation Anti-Patterns

  1. Multiple record-triggered flows on the same object: Creates unpredictable behavior and debugging nightmares
  2. Flow loops that perform DML inside the loop: Governor limit violations waiting to happen
  3. Using Apex for simple field updates: Over-engineering when a before-save Flow works fine
  4. Hardcoded IDs in Flows or Apex: Fails across environments; use Custom Metadata Types
  5. No error handling in Flows: Unhandled faults cause cryptic user errors
  6. Mixing Process Builder + Flow + Workflow Rules: Legacy mess; consolidate to Flow (Process Builder is deprecated)
  7. Apex triggers without bulkification: Works in dev, fails in production with data loader operations

Trade-Offs Summary

FactorFlow (Declarative)Apex (Programmatic)
Development speedFaster for simple logicFaster for complex logic
MaintenanceAdmin-friendlyRequires developer
TestingManual, limitedAutomated, CI/CD-ready
PerformanceGood for simple opsBetter for complex ops
Governor limitsShared, harder to optimizeShared, easier to optimize
Version controlMetadata API exportNative source tracking
DebuggingFlow Debug UI (limited)Debug logs, breakpoints, stack traces
ReusabilitySubflowsApex classes, interfaces, inheritance
Error handlingFault paths (basic)Try-catch with custom logic
Bulk operationsRequires careful designNatural with collections

Sources

Personal study notes for the Salesforce CTA exam. Content compiled from VJ's study notes, official Salesforce documentation, community sources, and online publicly available content, then organized and presented with AI assistance. Not affiliated with Salesforce. © 2025–2026 VJ Srivastava.