The independent daily for Salesforce admins, developers and architects

Curated by Abhinav (opens in a new tab)

Must-read

Bulkifying an Opportunity trigger to avoid the 101 SOQL limit error (opens in a new tab)

You will learn why a per-record SOQL query inside a trigger loop fails on bulk loads, and how to refactor it to one query and one DML statement using a map keyed by Account ID.

Why read this

You will also see the trade-offs between triggers, Flows and Queueable Apex.

Per-record (fails)

  • Query Account inside the loop
  • Update Account inside the loop
  • Fails on record 101

Bulk-safe (map)

  • Collect deltas in a map by AccountId
  • One SOQL query with IN
  • One DML update for the list
The failing per-record pattern set against the bulk-safe pattern

A trigger that passes a single-record test can fail a 200-row bulk import with a Too many SOQL queries error. This happens with Data Loader, Bulk API and scheduled integrations, and it usually shows up first in production, because sandbox test data rarely reaches 200 rows per batch. The article argues that the fix is to change how the trigger reads and writes data, not to retry or buy more licences.

The author uses an after update trigger on Opportunity that adds the Amount of newly closed-won deals to a Total_Won__c field on the parent Account. The original version queries and updates the Account once per record, which breaks on record 101 under the 100 SOQL limit and would also run into the 150 DML statement cap. The article uses this failing version to show the cause of the error.

The refactor has three steps. First, audit every query and DML statement that sits inside a loop over Trigger.new. Second, collect the qualifying deals into a map keyed by AccountId, filtering on the stage change so later edits do not double count, then run a single query with IN and a single update. The map also merges several deals for the same Account. Third, weigh the options: a handler class gives testability and bulk control, Record-Triggered Flow is quicker for simple logic but shares the same caps, and Queueable Apex allows more queries and CPU time at the cost of eventual consistency.

The article closes with a short FAQ. It notes that a LimitException cannot be caught with try-catch, that Limits.getQueries() can be used to check usage, and that Queueable suits follow-up work while Batch Apex suits large record sets. It recommends testing with 200 records in a single call so that the test matches the real chunk size.

Read the original at dev.to (opens in a new tab)

Worth reading?

Must-read

Catching AI-Generated Apex that breaks governor Limits with budget tests in CI (opens in a new tab)

You will learn how to measure governor limit consumption in Apex tests, set per-context budgets, and close the loop so AI agents fix limit-heavy code before it merges.

Why read this

The post includes a snapshot class pattern, a limits table and a retry-and-escalation design.

  1. Agent pushes code with bulk tests
  2. CI measures limit consumption
  3. Breach sends feedback to agent
  4. Up to two refactor attempts
  5. Human architect review if still failing
How the CI loop handles a governor limit breach in agent-written code

The article argues that AI-generated Apex can be functionally correct and fully unit-tested yet still exhaust shared transaction budgets, because agents build each feature in isolation and small additions compound until a governor limit is breached. Standard small-data tests rarely expose this, and since governor limits are platform capacity ceilings, the author recommends treating them as architectural contracts and enforcing them automatically before code merges. It illustrates the compounding with a sprint-by-sprint example where SOQL consumption climbs from 15% to 59% through individually harmless changes.

The proposed approach has several parts. Teams should supply a shared, immutable GovernorLimitSnapshot test utility, require agents to write bulk tests of 200 records that capture before and after snapshots, and have CI verify that these test conventions are present. A table compares synchronous and asynchronous limits, and a budget-allocation table recommends consumption thresholds by execution context: roughly 40 to 50% for trigger code, 60 to 70% for service classes, 80 to 85% for isolated asynchronous jobs, and 20 to 30% for Scheduled Apex. Snapshots should be taken just before Test.stopTest() so the synchronous footprint is measured separately from asynchronous work, which is tested in its own method.

The article then describes a closed feedback loop in CI. When a test breaches its budget, a structured prompt containing the metric, consumption, threshold and required optimization steps goes back to the agent, which gets up to three attempts, with the delta between attempts supplied on later tries. If the third attempt fails, the merge is blocked and a human architect is asked to review, possibly moving the logic to Queueable. Agents must not be allowed to weaken tests or thresholds, and the author notes that some limits, such as callouts and Platform Event publishing, need production monitoring as well. Thresholds should start generous, use warning and violation tiers, and be tightened over time, with a closing checklist for rolling the pattern out.

Read the original at Salesforce Architects (opens in a new tab)

Worth reading?

Ten Flow design mistakes that break Salesforce orgs as they scale (opens in a new tab)

You will learn how bulk record processing, database operations inside loops, repeated writes, hard-coded IDs and weak fault handling make Flow fail under load, and how to design around each one.

Why read this

The piece is practical guidance for anyone whose orgs run record-triggered automation at volume.

This Salesforce Ben article, written for architects, lists ten Flow design mistakes that cause failures as orgs grow, and suggests a fix for each. The first concerns treating Flow as a single-record tool: bulk operations from Data Loader or List Views share one transaction’s governor limits, so authors should use before-save flows for same-record updates, tighten entry conditions, and make invocable Apex bulk-safe. The second warns against database operations inside loops, recommending retrieving records before the loop, changing values in memory, and saving a collection once afterwards, with Collection Filters and Transform as alternatives. The third covers writing to the database too often, since each write can fire further automation and cause record-locking, so decisions should come first and writes should be batched near the end.

The next several points cover maintainability, testing and error handling. Hard-coded IDs break when flows move between environments, so the article recommends looking up records by DeveloperName, using Custom Metadata, Custom Labels or Custom Settings. Flows without deliberate fault handling leave failures to Salesforce’s default response, so authors should choose between blocking saves, guiding users, or logging failures, and should understand how rollback differs for unhandled errors, handled faults and explicit rollbacks. Testing with a single record gives little assurance, so the article urges bulk tests of at least 200 records, representative data, and separate logic, transaction-limit and load testing.

The final points address structure and design. Monolithic flows are hard to maintain, so the piece suggests subflows for repeated logic, self-contained processes and frequently changing rules, while warning against too many tiny subflows and recommending grouping flows by business purpose. Transaction boundaries matter because governor limits apply per transaction, and asynchronous paths, scheduled paths, screens, Wait elements and Platform Events can move work out of the original save, with the trade-off that committed changes cannot be rolled back. Screen Flows need care when users click Previous, which can cause duplicates, so the article advises saving at the end and making steps idempotent. Finally, it cautions that data model problems such as data skew, non-selective queries, recreated roll-up functionality and master-detail choices can limit what Flow design alone can fix. The conclusion advises reviewing the highest-volume objects first.

Read the original at Salesforce Ben (opens in a new tab)

Worth reading?

Seven Apex best practices for handling governor limits and bulk processing (opens in a new tab)

Readers will learn how to structure Apex transactions to avoid governor limit exceptions by applying bulkification patterns, optimizing data operations, and designing realistic test suites.

The article explains that Salesforce multitenancy requires strict resource management through governor limits that cap SOQL queries, DML statements, CPU time, and heap size. Developers are advised to treat these boundaries as foundational design constraints rather than post-development hurdles.

Core recommendations focus on eliminating database operations from iterative loops. The piece demonstrates collecting target identifiers into sets, executing single bulk queries, and populating maps for rapid lookups. It also shows how to accumulate records into lists for batch insertions while checking for empty collections beforehand.

Efficient use of Apex collections and comprehensive testing strategies receive equal emphasis. Writers are instructed to select appropriate collection types based on lookup needs and to validate logic against high record volumes. Testing must account for downstream automation overhead and varying data relationships to prevent unexpected limit exhaustion.

Finally, the guide outlines ongoing maintenance practices, including reviewing debug logs and refactoring inefficient code as data scales. It notes that persistent limit failures often stem from interconnected automation layers, requiring architects to evaluate broader system design alongside individual class performance.

Read the original at dev.to (opens in a new tab)

Worth reading?