PracticeVideosBlogFlashcards

1.1 Declarative vs. Programmatic Architecture & Limits

Key Takeaways

  • Typical synchronous Apex limits include 100 SOQL queries and 150 DML statements per transaction; Batch and Queueable Apex have different allowances. Check the actual Flow or Apex execution context.

  • Declarative tools avoid the Apex code-coverage requirement, but still require testing and share transaction resources with other automation. Formula values are evaluated on read; roll-up summary values are stored.

  • Apex is appropriate when a requirement needs explicit row locking, granular savepoints, unsupported integration formats, or complex bulk processing. Flow supports HTTP Callout and REGEX; those features alone do not require Apex.

  • Before-save flows modify the triggering record in memory without an extra DML update. They run before before-Apex triggers and custom validation; immediate after-save flows also run before transaction commit.

Last updated: October 2026

Declarative vs. Programmatic Architecture & Limits

The Salesforce Lightning Platform is built on a metadata-driven, multitenant architecture. In this environment, multiple customer organizations (tenants) share the same underlying hardware, database clusters, and execution runtime. To guarantee that no single tenant can monopolize shared computing resources—such as CPU execution time, database connections, or memory heap—Salesforce enforces strict, deterministic runtime boundaries known as Governor Limits.

For a Salesforce Platform App Builder, understanding where declarative capabilities end and where programmatic solutions become necessary is one of the most heavily tested competencies on the certification exam. Selecting the wrong architectural tool can result in unmaintainable technical debt, brittle integrations, or catastrophic governor limit exceptions in production.


The Multitenant Platform Architecture & Metadata Engine

Unlike traditional on-premises enterprise software where infrastructure is dedicated to a single client, Salesforce abstracts all database tables, business logic, and user interfaces into metadata. When you create a custom field, build a validation rule, or configure a Record-Triggered Flow, Salesforce does not alter the physical database schema on disk. Instead, the platform records a metadata entry that dynamically configures the shared multitenant database engine at runtime.

Because all computing power is drawn from a shared pool, every transaction—whether initiated by a user editing a record in Lightning Experience, an automated background Flow, a bulk API data load, or an Apex trigger—is allocated a finite budget of platform resources. When a transaction reaches any governor limit threshold, the platform throws an uncatchable runtime exception, immediately terminates execution, and rolls back all database modifications executed during that transaction.

Note

Multitenant Architecture Foundation: Governor limits are not penalties; they are protective platform guardrails. Every automated transaction operates within an isolated governor limit container that resets once the transaction commits or aborts.


The Declarative Toolkit: Point-and-Click Architecture

Salesforce promotes a "clicks before code" architectural philosophy. Declarative tools offer faster development cycles, automatic compatibility with triannual platform releases (Spring, Summer, Winter), lower total cost of ownership (TCO), and zero requirement for writing formal unit test classes with 75% code coverage.

Key declarative automation and logic mechanisms include:

  1. Formula Fields & Roll-Up Summary Fields: Formula fields calculate on read; roll-up summary fields persist aggregates on the master and are recalculated during detail saves. Roll-up summary fields calculate aggregate values (SUM, COUNT, MIN, MAX) across master-detail relationships automatically.
  2. Validation Rules: Enforce data integrity by evaluating boolean formulas before record changes are committed to the database. If the formula evaluates to TRUE, the transaction halts and an error message is presented to the user or API client.
  3. Salesforce Flow: The cornerstone declarative engine for modern Salesforce implementations:
    • Before-Save Record-Triggered Flows (Fast Field Updates): Execute before the record is saved to the database disk. They update fields on the triggering record directly in memory, consuming zero DML statements and executing more efficiently than an equivalent extra after-save update.
    • After-Save Record-Triggered Flows: Execute after the initial save, before the transaction commits. Only scheduled/asynchronous paths run in a later transaction. Used to create or update related records, send email alerts, publish platform events, or execute asynchronous paths.
    • Screen Flows: Provide interactive, multi-step user interface wizards that capture and process data conditionally.
    • Schedule-Triggered Flows: Run automatically at specified times and frequencies for batches of records.
    • Autolaunched Flows: Execute behind the scenes when invoked by Apex, REST APIs, or Orchestrations.
  4. Quick Actions & Approval Processes: Automate multi-step record approval chains and contextual record creation directly from Lightning pages.

The Programmatic Toolkit: When Code is Necessary

Complex architectural scenarios can justify programmatic intervention using Apex and Lightning Web Components (LWC):

  • Apex Triggers & Classes: Provide full programmatic control over data operations, complex collection manipulations (List, Set, Map), and recursion control.
  • Asynchronous Apex: Bypasses synchronous execution boundaries to process large data volumes or long-running computations:
    • Batch Apex (Database.Batchable): Processes datasets of up to 50 million records by dividing them into manageable batches (typically 200 records per chunk). Each chunk receives a fresh set of governor limits.
    • Queueable Apex (Queueable): The modern evolution of @future methods, supporting complex data types (sObjects), job chaining, and job ID tracking via AsyncApexJob.
    • Future Methods (@future): Simple fire-and-forget asynchronous methods accepting primitive data types, ideal for isolated external web service callouts or resolving MIXED_DML_OPERATION exceptions (e.g., updating setup and non-setup objects in the same transaction).
    • Schedulable Apex (Schedulable): Schedules Apex classes to run at specific calendar times using cron expressions.
  • Lightning Web Components (LWC): Custom client-side user interfaces built on standard modern web components (HTML5, modern JavaScript ES6+, Shadow DOM) when standard Lightning pages, Dynamic Forms, or Screen Flows cannot deliver required third-party library integrations, canvas graphics, or complex responsive micro-interactions.

Governor Limits Reference: Synchronous vs. Asynchronous Contexts

Every App Builder must know the fundamental governor limits by heart. Synchronous transactions (e.g., a user clicking Save on a record) operate under stricter thresholds, while asynchronous contexts grant higher allowances to accommodate heavy processing.

Platform Resource / MetricSynchronous LimitAsynchronous Limit (Batch / Queueable)
Total SOQL Queries Issued100 queries200 queries
Total Records Retrieved by SOQL50,000 records50,000 records
Total DML Statements Issued150 statements150 statements
Total Records Processed via DML10,000 records10,000 records
Maximum Total CPU Time on Servers10,000 ms (10 seconds)60,000 ms (60 seconds)
Total Memory Heap Size6 MB12 MB
Maximum External Callouts per Transaction100 callouts (max 120s timeout)100 callouts (max 120s timeout)
Maximum Email Invocations (sendEmail)10 invocations10 invocations

Important

Bulkification in Flow Builder: Declarative automations run on the exact same engine as Apex. Placing a Get Records, Create Records, or Update Records element inside a Flow loop causes repeated SOQL queries or DML statements per iteration. A Get Records element repeated 101 times can exceed the 100-query limit; repeated DML has a separate 150-statement limit. Other automation shares those budgets. Always collect data into collection variables and perform single bulk DML operations outside loops.


Architectural Decision Matrix: Declarative vs. Programmatic

When evaluating a technical requirement, use the following scenario-based decision matrix to choose the correct architectural tier:

Business Requirement ScenarioRecommended Architectural SolutionCritical Architectural Justification
Update fields on the triggering recordBefore-Save Record-Triggered FlowExecutes in memory before database commit; consumes 0 DML statements and avoids trigger recursion
Create or update related child/parent recordsAfter-Save Record-Triggered FlowRequires the new record ID from the initial save; the transaction remains uncommitted
Interactive guided user data entryScreen FlowDeclarative, mobile-responsive UI wizard; supports conditional visibility and input validation
Custom pixel-perfect UI with third-party chartsLightning Web Component (LWC)Standard Flow screens cannot render arbitrary third-party JavaScript libraries or custom DOM structures
Nightly complex recalculation of millions of historical recordsBatch Apex (Database.Batchable)Check scheduled-flow interview allocations and per-transaction workload; Batch Apex offers explicit chunking for complex high-volume work
External REST API callout with dynamic payload parsingProgrammatic Apex Class / ServiceWhile Flow HTTP Callouts handle strict JSON schemas, dynamic XML/binary parsing demands Apex
Preventing race conditions on shared inventory recordsApex Trigger with FOR UPDATE SOQLDeclarative tools cannot lock database rows exclusively during transaction evaluation
Multi-object rollback with custom savepointsProgrammatic Apex (Database.setSavepoint())A handled Flow fault does not automatically roll back earlier changes; Custom Error and Roll Back Records support specific rollback cases, while Apex supports explicit savepoints

Common Exam Traps and Best Practices

  • Trap 1: Assuming Flow cannot make web service callouts. Modern Salesforce Flow supports HTTP Callout actions natively in Flow Builder. However, when an external API requires complex multipart form uploads, dynamic OAuth token signing, or custom binary stream manipulation, Apex remains required.
  • Trap 2: Creating an After-Save Flow to update the same record. If an after-save flow updates the record that triggered it, Salesforce executes an unnecessary DML update statement and initiates a recursive save cycle. Prefer a Before-Save Flow (Fast Field Updates) for same-record values available before the initial save. Values generated later in the transaction or actions requiring after-save capabilities can justify an after-save update; guard against recursion.
  • Trap 3: The 75% Test Coverage Gate. App Builders must remember that production Apex deployments must satisfy the selected test level: ordinarily at least 75% overall coverage and some coverage on every trigger; Run Specified Tests instead requires at least 75% coverage individually for every deployed class and trigger. All required tests must pass. Declarative automations (Flows, validation rules, formulas) do not require code coverage to deploy via change sets or DevOps Center, dramatically reducing deployment overhead.

Tip

The Fast Field Updates Advantage: Whenever a business requirement asks to validate, transform, or calculate field values on the same record being inserted or updated, choose Before-Save Record-Triggered Flow. It executes prior to database write, consumes zero DML statements, avoids recursion, and delivers near-instantaneous execution.

Loading diagram...
Architectural Decision Framework: Declarative vs. Programmatic
Test Your Knowledge

A team must recalculate 350,000 complex loyalty transactions nightly. Its scheduled-flow interview allocation is 250,000 per 24 hours and cannot accommodate the job. Which solution gives a developer explicit control over processing chunks?

A

Develop a Batch Apex class scheduled to execute nightly with a configurable batch size

B

Configure a Schedule-Triggered Flow scheduled to run nightly across all transaction records

C

Build an Autolaunched Flow triggered by a nightly workflow rule scheduled action

D

Design a Screen Flow that administrative personnel execute manually at the close of business

Test Your Knowledge

A high-volume ticket booking platform experiences frequent concurrency issues where two customer service representatives simultaneously submit reservations for the last available VIP seat, resulting in duplicate bookings and negative inventory balances. How should an app builder resolve this concurrency challenge?

A

Create a validation rule on the Reservation object checking available seat counts before save

B

Build a before-save Record-Triggered Flow to decrement seat availability immediately

C

Implement an Apex trigger utilizing a SOQL query with the FOR UPDATE locking keyword

D

Deploy a cross-object formula field on the Event object that calculates remaining capacity

Test Your Knowledge

An app builder needs to automatically calculate and populate a 'Priority Score' field on newly created and edited Case records based on Case Origin and Account Tier. The update must occur with maximum execution speed, avoid re-triggering workflow evaluation rules, and consume zero DML statements. What is the optimal solution?

A

An Apex trigger running on the after insert and after update events issuing a Database.update call

B

An after-save Record-Triggered Flow with an Update Records element targeting the triggering Case

C

A Workflow Rule with a field update action scheduled to execute immediately upon record creation

D

A before-save Record-Triggered Flow configured for Fast Field Updates on the Case object

Sections you finish are checked off in the contents.