The independent daily for Salesforce admins, developers and architects

Curated by Abhinav (opens in a new tab)

Must-read

Why a static Boolean Trigger guard silently skips records in bulk (opens in a new tab)

You will learn why a static Boolean recursion guard fails when a DML statement touches more than 200 records, how to reproduce the bug with a test, and how to replace it with an Id-based Set or a change-based check.

Static Boolean guard

  • One flag for the whole transaction
  • Chunk 2 onward is skipped
  • 800 of 1,000 records unprocessed
  • Insert still succeeds silently

Id-based Set guard

  • Tracks each record Id
  • New Ids in each chunk processed
  • Recursive Ids already in set skipped
  • Guards afterUpdate, not inserts
A static Boolean guard against an Id-based Set in a bulk trigger

Many Apex trigger tutorials recommend a static Boolean flag to stop a trigger from running again during recursion. The article argues this flag can silently skip records in production. Salesforce splits any DML statement touching more than 200 records into chunks of 200, running the trigger once per chunk within the same transaction. A static variable persists across those chunks, so the guard cannot distinguish a recursive call from the next batch of records, and records beyond the first chunk never get processed, though the insert still succeeds.

The problem is most likely in Batch Apex with a scope above 200, data migration scripts run from Anonymous Apex, service classes that insert or update large lists, and Flows that change many records in one element. It rarely appears in UI testing because records are saved one at a time. The article provides a test that inserts 201 Accounts and asserts that all 201 are processed. With the Boolean guard the test fails, reporting 200 processed, while a bulk-safe test catches the defect before release.

The recommended fix is to track record Ids in a Set rather than a single Boolean. Adding each Id to the set returns false when it was already present, so only genuinely new records are processed in later chunks, while a true recursive update is skipped. The article notes practical details: guard afterUpdate rather than inserts because records in before insert have no Ids yet, keep separate sets per event if both beforeUpdate and afterUpdate do work, and accept that a record updated twice on purpose is handled only once.

Often the better solution is to avoid needing a guard. Comparing field values against Trigger.oldMap and acting only on the change of interest stops recursion naturally, because the follow-up update does not change the field again. A before-insert handler that only sets fields on Trigger.new cannot cause recursion and needs no guard. The article closes with a checklist: search the org for static Boolean flags in trigger handlers, remove guards that are unnecessary, react to changes rather than every update, use Sets where a guard remains, and test every trigger with 201 or more records in one statement. The article also promotes a commercial starter kit, which is not part of the technical guidance.

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

Also told by dev.to (opens in a new tab), dev.to (opens in a new tab)

Worth reading?

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?

Using Apex savepoints to roll back a failed multi-step transaction (opens in a new tab)

You will learn how Database.setSavepoint() and Database.rollback() undo DML made after a savepoint, and where that protection stops, such as external callouts and emails.

Why read this

The article includes a short worked example.

  1. Call Database.setSavepoint()
  2. Insert the Account
  3. Insert the related Contact
  4. Contact insert fails: catch the exception
  5. Call Database.rollback(sp) to undo the Account
How a savepoint lets a failed Apex transaction undo its earlier database changes

The article describes a common problem: an Apex method performs several database operations, and a later one fails, leaving earlier changes saved. Savepoints address this by marking a point in the current transaction that can later be restored.

It presents two methods. Database.setSavepoint() creates the marker, and Database.rollback() reverses database changes made after it. The worked example creates an Account and a related Contact inside a try block, and on exception rolls back to the savepoint so the Account insert is undone.

The author notes that rollback does not undo every side effect. External API calls and emails already sent are outside the database transaction and are not reversed. The article also contrasts savepoints with partial-success DML using Database.insert(records, false), which is a different approach from a full rollback.

The limitations listed include that savepoints apply only within the current transaction, that Salesforce caps the number of savepoints, that certain transaction-control operations can invalidate them, and that DML and other transaction limits still apply. Best practices suggest creating savepoints only before operations that may need reversing, using clear exception handling, and testing both success and failure paths.

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

Worth reading?

How the merge() API handles Lead records and their MCAE Prospects (opens in a new tab)

You will learn which fields, history, related records and dates survive when Leads are merged, and how the linked MCAE Prospect behaves.

Why read this

You will also see how to find merged records afterwards with queryAll().

  1. Keep the chosen master Lead
  2. Reparent related records to it
  3. Copy the field values you supply
  4. Delete victims and set MasterRecordId
What the merge() call does to the victim Leads

The merge() SOAP API combines up to three records of the same type into one. The caller chooses the master record and the victims, and Salesforce keeps the master, reparents related records from the victims, deletes the victims and sets MasterRecordId on them. Field values are not copied automatically; any value the caller wants from a victim must be supplied on the master record in the MergeRequest.

For a merged Lead, the victims’ lead history is not carried over, but the surviving Lead gets a new “Lead Merged” history line showing the victim’s original name and company. Created By and Created Date are taken from the oldest victim. Related records such as Tasks, Campaign Members and Messaging Sessions move to the surviving Lead.

When both Leads are linked to MCAE Prospects, the Prospects are merged too and attached to the surviving Lead. The surviving Prospect keeps its original created date, but its conversion date and Recent Interaction date come from the oldest victim, and its audit log includes the victims’ activity. The article also notes an audit line reading “Started matching Marketing Data Sharing criteria”. Use queryAll() with MasterRecordId to find the records a merge deleted.

Read the original at SimplySfdc (opens in a new tab)

Worth reading?

Must-read

How a local Apex runtime speeds up testing without replacing your org (opens in a new tab)

You will learn how a local runtime executes Apex and Flow metadata against an embedded database while enforcing governor limits and order of execution.

Why read this

The article explains how this approach accelerates the edit-test cycle and fits into your standard deployment workflow.

Local Apex runtime

  • Apex interpreter
  • Local database for SOQL and DML
  • Rule engine for limits and execution
The local Apex runtime is built from three core components

The article, written by the maker of renmy runtime (formerly Nimbus, renamed in October 2026), introduces a local Apex runtime: a program that executes Apex, SOQL and DML on a developer’s own machine without a Salesforce org. It argues that Salesforce developers work in a slow loop, where every edit is deployed to an org and tested there, while developers in Java, JavaScript and Go run tests locally in about a second. The author attributes this gap to Apex being multi-tenant and tied to the platform’s data model and order of execution. Cited costs include round trips to the org, CI that needs org credentials, outages that halt testing, and AI coding agents that cannot iterate quickly. A local runtime has three parts: an Apex interpreter, an embedded PostgreSQL database for real queries and DML, and the platform’s rules, including enforced governor limits, triggers and Flows in order of execution, and per-test rollback. A sample test runs in tens of milliseconds, and the article says the runtime is not a mock, not a Scratch Org and not a transpiler.

The article is clear that a local runtime does not replace the org. Lightning pages, user-facing Screen Flows, permission checks, real integrations and the deploy itself with Salesforce’s metadata validation still happen in the org. The author compares this to a Java team’s staging environment, which stays for integration and final checks but is not the only place code runs. The renmy deploy is described as running local test and coverage gates first, then a check-only validation in the target org, then the deploy. The tool also offers coverage reporting, mutation testing, a debugger in VS Code and JetBrains, an MCP server for AI coding tools, and an IDE plugin. A published benchmark reports that 837 tests from four open-source suites ran in about 2.4 seconds locally versus about 1 minute 46 seconds in an org, with all tests passing in both.

Installation is a single binary for macOS, Linux and Windows, with no JVM, Docker or org required, and the commands are renmy test “” from the project root, plus options for single classes, coverage and a browser dev UI. The free tier covers individual developers, while Pro and Team tiers are free during the public beta and listed at $19 per month and $49 per developer per month. The article links to a parity record, which it describes as not a claim of 100 percent accuracy, and to GitHub for issues and releases.

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

Worth reading?

Recommended

Securing Salesforce to LLM integrations with Apex and scoped permissions (opens in a new tab)

Readers will learn how to enforce least-privilege access when calling external language models from Apex, including proper use of WITH USER_MODE, Named Credentials, and response validation.

The article argues that connecting Salesforce to a large language model takes more than an API key. The integration should control which records and fields the model can reach, protect credentials, minimize the data sent, and stop AI output from triggering unauthorized actions. It proposes an architecture with five parts: Salesforce enforcing permissions, Apex or middleware handling authorization and request building, Named Credentials managing the endpoint and authentication, the LLM API generating output, and a validation layer checking results before they are shown or used. A support assistant summarizing Cases, for example, needs only subject, description and status, not full contact or financial history. Authorization should happen before data is sent to the model and again before any business action follows its response.

The piece distinguishes several permission mechanisms that must be combined rather than relying on OAuth scopes alone: integration identity, object permissions, field-level security, record sharing and application-level restrictions. In Apex, declaring a class with sharing does not enforce object and field permissions, so the article recommends WITH USER_MODE on supported SOQL queries, with Security.stripInaccessible() as an alternative for removing inaccessible fields. For credentials, it recommends never hardcoding API keys and instead using External and Named Credentials, granting access through Permission Sets, and keeping separate configurations for each environment. A sample Apex class summarizes a Case through the OpenAI Responses API, querying only needed fields, sending a minimal payload, and checking the HTTP status and response structure before returning text.

The article also covers defending against prompt injection, since record text from emails or tickets may contain malicious instructions. Its safeguards include treating retrieved text as untrusted, limiting fields and records, avoiding unrestricted query or tool access for the model, checking proposed operations against a server-side allowlist, requiring human approval for consequential changes, and filtering documents by user access before they reach the model in retrieval-based designs. For scale, it suggests asynchronous processing with Queueable Apex or middleware for longer tasks, bounded retries with backoff only for suitable errors, request identifiers to prevent duplicate actions, token and latency monitoring, and cache designs that respect permission changes. The conclusion urges starting with a read-only use case and adding write capabilities only after authorization and failure handling are tested.

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

Worth reading?

Master six overlooked Developer Console features to speed up debugging and querying (opens in a new tab)

You will learn how to configure saved workspace layouts, set persistent debug log levels, and use checkpoints and tree views to trace execution faster.

Why read this

The guide also explains how to export raw logs for side-by-side comparison when troubleshooting production issues.

The article positions the Developer Console as a lightweight scratchpad for quick queries and debugging, highlighting six underused capabilities that improve daily workflows. It begins by explaining how saved perspectives organize interface panels for specific tasks like data investigation versus breakpoint tracing.

It details how checkpoints capture heap and variable state at exact execution lines without cluttering code with debug statements. The author also recommends defining custom log levels for Execute Anonymous runs to filter out noise and speed up analysis.

Further tips cover the Query Editor, which now supports multi-line SOQL and maintains session history for rapid iteration. Debug logs can be navigated using a tree view to isolate specific classes, and the raw log export function allows developers to download and diff outputs across environments to pinpoint failures.

The piece concludes by reinforcing that while the console handles ad-hoc tasks efficiently, Visual Studio Code with the Salesforce extensions remains the superior choice for source tracking, testing, and deployment workflows.

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

Worth reading?

Must-read

Custom sharing reasons now roll out for standard objects alongside a setting to preserve manual shares (opens in a new tab)

You will learn how to use the new custom sharing reason feature on standard objects and configure the org-wide setting that keeps manual shares intact during record transfers.

Why read this

The article provides exact metadata and Apex examples so you can implement these changes immediately.

Keep Manual Shares

  • Available immediately in Sharing Settings
  • Keeps user manual shares after ownership changes
  • Best for teams relying on manual distribution

Custom Row Causes

  • Rolls out via Metadata API through October
  • Defines programmatic sharing reasons in code
  • Best for developers using Apex or Flow
Two new Salesforce sharing features help records keep access after owner changes

Salesforce is introducing two enhancements to the sharing model that eliminate long-standing workarounds for standard object access control. The first is an org-wide toggle called Keep Manual Shares when Transferring Records, which is available immediately in Sharing Settings. Enabling it ensures that manual shares survive ownership changes without requiring custom code or triggers.

The second enhancement rolls out through October and allows developers to define custom row causes on standard objects using the Metadata API. Previously, Apex managed sharing was restricted to Custom Objects. The update lets you declare a sharing reason like On Call Expert directly in the CustomObject metadata, then reference it in Apex share records or Flow actions. This separation keeps programmatic shares distinct from user manual shares and prevents automatic deletion when owners change.

The guidance recommends evaluating existing code that creates CaseShare, AccountShare, or similar records. Teams building shares via Apex or Flow should migrate to custom row causes to maintain auditability and stability. Those relying purely on manual distribution can simply enable the preservation setting. Both features arrive ahead of November updates that will bring management capabilities to Agentforce and Setup.

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

Worth reading?

A VS Code extension runs anonymous Apex and SOQL with a single keyboard shortcut (opens in a new tab)

Readers will learn how to install and configure Virga to execute throwaway Apex and SOQL scripts without leaving the editor.

Why read this

The piece also explains how the extension resolves common language server completion issues and disables telemetry during local runs.

Virga is a free VS Code extension designed to streamline the execution of throwaway Apex and SOQL scripts directly within the editor. Setup requires VS Code version 1.90 or newer, the Salesforce CLI on the system path, and an active Salesforce DX project. Users create dedicated scratch tabs for either language, trigger execution with a keyboard shortcut, and receive formatted output showing compilation status, debug logs, governor limits, or flattened query results.

The tool handles execution through a temporary file copy rather than direct command line arguments, which prevents partial edits from affecting the run. It achieves a seamless experience by applying a brief auto-save delay that clears tab dirtiness markers, allowing instant closure without save prompts. Scratch files persist in a version control ignored folder and survive editor restarts, while conflicting keymaps are handled to preserve the shortcut exclusively for scratch contexts.

Beyond basic execution, the extension patches gaps in the standard Salesforce Extension Pack. It adds completion support for inner types declared in the same file, identifies and offers quick fixes for parameter shapes that crash the language server, and supplies missing snippets for annotations and user mode operations. Privacy is maintained by automatically disabling Salesforce CLI telemetry for each run, though administrators can enforce global telemetry suppression through standard configuration commands.

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

Worth reading?

How elastic limits extend Async Apex capacity and throttle processing in Winter '27 (opens in a new tab)

You will learn how the Winter '27 extension of elastic limits increases Async Apex capacity while throttling throughput, and how to monitor usage with the OrgLimits class.

The Winter ’27 release extends the beta capability of elastic limits to Batch jobs, following its initial introduction for Queueable and Future methods in Summer ’26. When standard asynchronous governor limits are reached, the system allows additional enqueues up to a secondary cap calculated as the minimum of two million or the standard limit. Enqueued jobs beyond the baseline trigger throttling, which slows active processing and restricts Batch jobs to a single concurrent instance.

Developers can track consumption using the OrgLimits class, specifically querying the DailyAsyncApexElasticExecutions metric alongside the standard daily limit. The feature remains exclusive to production environments, meaning sandbox and trial orgs do not receive the extra capacity. Salesforce intentionally omits exact throttling metrics to prevent teams from treating the slowdown behavior as a guaranteed service level.

Scheduled Apex does not support elastic limits because the feature trades execution speed for additional volume, which conflicts with the time-sensitive nature of scheduled runs. The author advises using the extra capacity strictly as a resilience buffer rather than a primary scaling strategy, recommending that organizations investigate root causes when they regularly approach baseline limits.

Read the original at Bob Buzzard Blog (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?

Recommended

Block unwanted outbound emails in Email-to-Case using Custom Metadata and Apex (opens in a new tab)

The reader will learn how to prevent accidental outbound replies in Email-to-Case by storing blocked addresses in a Custom Metadata Type and enforcing them with an Apex trigger on EmailMessage.

Agents frequently reply to internal distribution lists or automated mailboxes during Email-to-Case interactions, causing infinite loops or unintended data exposure. Standard workarounds rely on hardcoded Validation Rules or Apex classes, which demand repeated testing and deployments whenever the blocklist changes.

The proposed solution moves the restriction list into a Custom Metadata Type. Administrators gain direct access to manage blocked addresses through Setup, removing the need for developer intervention or version control cycles for simple address updates.

Enforcement occurs via a before insert trigger on the EmailMessage object paired with a dedicated handler class. The code isolates outbound communications, verifies the fifty hundred parent identifier to limit scope to cases, and compares recipient addresses against the metadata records using case insensitive matching.

When a restricted address appears in the to or cc fields, the trigger applies an error that prevents the message from sending. This architecture keeps the logic modular, avoids interfering with inbound case creation or unrelated email automation, and provides a reusable template for other metadata driven routing rules.

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

Worth reading?

How to write effective Apex tests that pass deployment gates and avoid common pitfalls (opens in a new tab)

You will learn the exact platform requirements for Apex test coverage and how to structure tests that actually validate business logic instead of just inflating percentages.

Why read this

The piece also outlines practical patterns for bulk-safe test data and deployment troubleshooting.

The article explains that Salesforce enforces mandatory Apex test runs to protect multi-tenant reliability and prevent regression. Production deployments require at least seventy-five percent org-wide code coverage, complete trigger coverage, and zero failing methods, though test classes themselves are excluded from the calculation.

It emphasizes that coverage metrics alone do not guarantee quality, urging developers to replace empty test methods with explicit System.assert calls that verify business outcomes rather than implementation details. Writers are advised to cover both happy and unhappy paths, including validation failures and governor limit boundaries.

Practical guidance follows for building robust test suites, recommending the use of @TestSetup for shared fixtures, centralized test data factories, and inserting two hundred records to simulate bulk trigger behavior. The piece also clarifies how Test.startTest and Test.stopTest reset governor limits and synchronize asynchronous executions.

Finally, it lists common deployment hurdles such as coverage resetting after metadata edits, mixed DML errors when creating users alongside other objects, and the recommendation to target ninety percent coverage for safety margins. Individual class debugging is suggested to isolate failures quickly.

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

Worth reading?

Recommended

Understanding the new Apex heap limits and transition settings in Winter '27 (opens in a new tab)

Readers will learn the exact new synchronous and asynchronous Apex heap limits in Winter Twenty Seven and how to configure non-production orgs during the transition.

Why read this

The piece also explains how larger memory allocations impact transaction scaling, user experience, and downstream system stability.

The Winter Twenty Seven release increases the synchronous Apex heap limit from six megabytes to ten megabytes and raises the asynchronous limit from twelve megabytes to twenty-five megabytes. To manage the transition safely, administrators can use Apex Settings to force non-production orgs to retain the previous Summer Twenty Six limits until code is verified against the new thresholds.

Testing with large compressed files shows that the additional memory allows significantly larger payloads to be processed in a single transaction, though compression algorithms and file structure still dictate actual heap consumption. The author notes that higher memory availability does not automatically improve throughput, as CPU limits and governor constraints remain unchanged.

Larger heaps introduce risks such as overwhelming end users with unfiltered data tables, overloading downstream APIs, or masking existing logic flaws that previously failed at smaller record counts. The article concludes that developers should continue writing code that conserves resources and batches workloads, treating the increased limits as capacity for legitimate growth rather than a target to hit routinely.

Read the original at Bob Buzzard Blog (opens in a new tab)

Worth reading?

Using Apex frameworks to enforce code quality and platform limits in the AI era (opens in a new tab)

Readers will learn how to structure Apex libraries with strict interfaces and runtime validations to prevent both human and AI errors.

Why read this

The piece also explains how these patterns automatically optimize SOQL and DML usage to stay within Salesforce governor limits.

The article, written by Piotr Gajek, a Senior Salesforce Developer and Technical Architect, introduces Framework-Driven Development (FDD), an approach developed over a couple of years in his Apex Fluently libraries. Its core idea is to move responsibility for code quality and Salesforce governor limits out of individual developers and AI agents and into shared frameworks and the development process. He argues that LLM output is statistically average and often disconnected from the wider architecture, and that shared limits on an org mean one team’s careless generated code can break another’s solution. He describes the phenomena of “meat proxies” and “slop grenades” as reasons why ownership of code becomes unclear.

The approach rests on three rules: frameworks should be idiot-proof and AI-proof, generated code should be optimized for platform limits, and quality should be built in by design. Idiot-proofing uses limited interfaces that expose only permitted methods, such as the SOQL Lib cache module that blocks toList() because of misleading cached results, and the Trigger Lib contexts that allow only relevant actions per trigger phase. Internal validation throws explanatory exceptions with suggested overrides, and documentation and AI-readable skills act as a final safeguard.

For limits, the author highlights Async Lib, which manages queueable, schedulable and batch jobs to avoid the “Too many queueable jobs” error; DML Lib, which builds a dependency graph and commits records in optimized order through a shared Unit of Work; SOQL Lib, which caches queries in static, org or session scope; and Trigger Lib, which batches parent queries from many handlers. Quality by design is reinforced by phase-specific rules and small, single-responsibility classes. He also suggests administrators could benefit when Apex-based logic replaces Record-Triggered Flows. The conclusion recommends combining libraries, context documents and layered testing, with TDD where useful.

Read the original at Beyond the Cloud (opens in a new tab)

Worth reading?

Must-read

Custom Metadata Types as one deployable home for values across Salesforce and Agentforce (opens in a new tab)

You will see how one Custom Metadata Type can feed formulas, Validation Rules, Flow, Apex and Agentforce actions, and where those references stop working.

Typed into each tool

  • Thresholds in formulas
  • Defaults in Flows
  • Feature switches in Apex classes
  • Each change means finding every use

Custom Metadata Types

  • One deployable home for values
  • Travels through source control
  • One record per region plus Default
  • Read via $CustomMetadata reference
One deployable home replaces values typed into each formula, Flow or Apex class

The article argues that developers often hard-code business values such as thresholds, defaults, feature switches and mappings into formulas, Flows and Apex without noticing, which makes later changes hard to trace. Custom Metadata Types offer a central, deployable home for these values. Unlike Custom Settings or Custom Objects, which hold data, Custom Metadata holds configuration that ships with application code through source control and CI/CD. The author illustrates this with a Deal_Policy__mdt type holding a shared maximum discount and regional records for large-deal amount, default discount and approval threshold, selected by region name.

The piece then maps where references work. Formula Fields, Validation Rules and field defaults can use a three-part reference (type, record name, field), but the formula must name a fixed record, so it cannot pick a region from opportunity data. Long text area fields cannot be referenced, and the formula editor does not list Custom Metadata fields for defaults, though typing the reference still works. Flow can query the type with Get Records, match a region, and fall back to the Default record, and it can also use the literal reference. Apex uses getInstance with a similar fallback. Custom Permissions are kept separate, since they govern what a user may do while Custom Metadata governs the values.

Agentforce cannot read $CustomMetadata references directly, so the workaround is an invocable Apex action that loads the policy and returns the values, which the Agent Script maps into variables before answering. Lightning App Builder component visibility does not accept Custom Metadata references. On record pages a Formula Field can bridge the value, though that adds a field, and App and Home pages must read the data in Apex, through @wire, or via Dynamic Interactions.

To assess impact, the article recommends Setup’s Where is this used? option or a Tooling API query of MetadataComponentDependency, which lists the Apex classes and Validation Rules that depend on a field. It also notes that an attempt to build an LWC editor that showed these dependencies from Apex was complicated by the authentication setup REST calls require. Finally, it outlines platform limits: 200 types per org (350 with certified managed packages), 100 fields per type, and a 10 million character budget where each text area reserves 255 characters regardless of use. Process Builder allows 15 Custom Metadata formula references per process. The author concludes that teams should treat business values as configuration, centralize them, and keep track of where each reference works and where it does not.

Read the original at Andy in the Cloud (opens in a new tab)

Worth reading?