← Back to Delivery Management
DEL-004 Delivery Management 22 min read For: Salesforce Architects · Delivery Managers

Technical Debt in Salesforce: How to Measure and Manage It

The delivery leader's tactical guide to quantifying customisation bloat, prioritising refactoring, and enforcing limits on technical debt.

VS

Vishal Sharma

Salesforce Delivery Specialist · Updated May 2026

What you will learn in this tutorial
  • The fundamental distinction between software code debt and declarative (point-and-click) customisation debt in Salesforce
  • Key quantifiable metrics for technical debt, including Custom Field Saturation, Trigger Multiplicity, and Test Execution Latency
  • An actionable prioritisation framework to categorise refactoring tasks by Business Risk and Refactoring Cost
  • Tactical governance mechanisms such as the Architecture Review Board (ARB) and static analysis pipeline integration
  • How to calculate and articulate the financial cost of technical debt and present a business case to the C-suite
  • Methods for enhancing your Agile definition of done (DoD) to prevent the re-accumulation of technical bloat

The Anatomy of Salesforce Technical Debt

In traditional software engineering, technical debt is generally understood as the implied cost of additional refactoring work caused by choosing an easy, fast solution now instead of a better approach that would take longer. This concept, coined by Ward Cunningham, translates directly to Salesforce development but with a unique, compounding complication: declarative debt.

Salesforce is marketed and sold on the power of low-code and no-code customisation. Point-and-click tools like Flow Builder, validation rules, sharing rules, and custom fields make it remarkably easy for business analysts and administrators to modify system behaviour instantly. However, this accessibility is a double-edged sword. While it accelerates initial delivery, it completely bypasses the traditional compiler checks, architectural reviews, and static analysis gates that safeguard custom-written code. As an organisation's Salesforce footprint grows, this lack of rigor leads to what we must categorise as declarative customisation bloat.

In an enterprise Salesforce org, technical debt manifests in three major categories:

  • Declarative Automation Bloat: Multiple active Flows, legacy workflow rules, process builders, and Apex triggers executing simultaneously on the same object. This multiplicity degrades transaction performance, leads to CPU timeout limits, and makes the system's execution order highly unpredictable.
  • Data Schema Pollution: An excessive accumulation of custom fields, redundant custom objects, and abandoned metadata. Over time, objects like Account, Contact, and Opportunity approach their hard custom field limits, creating severe "metadata friction" that slows down future development.
  • Apex Code Decay: Legacy custom code written without modern trigger frameworks, lacking automated unit test coverage, utilising hardcoded IDs, or ignoring modern programming practices like dependency injection or enterprise patterns.

This multi-faceted debt behaves exactly like financial debt. The short-term benefit is rapid feature delivery, but the long-term cost is the "interest" paid in the form of decreased development velocity, increased bug rates, high regression testing overhead, and ultimate platform instability. The major driver of this debt is almost always organizational. Squeezed delivery timelines, siloed business units demanding custom layouts, and a fundamental lack of architectural governance create a culture where speed is prioritised over sustainable design.

💡
Insight

Declarative technical debt is often far more dangerous than code debt. Code debt is visible to static analysis tools like PMD or SonarQube. Declarative debt—such as five redundant validation rules, three overlapping flows, and a series of sharing rules—lives silently in the database schema. It is rarely surfaced by standard source code scanners, yet it has an identical capacity to break production transactions and degrade user experience.

The Quantifiable Cost: Metrics That Matter

A critical failure of many Salesforce delivery programmes is the inability to quantify their technical debt. When advocating for refactoring resources, architects and delivery leaders often rely on subjective statements like "the code is messy" or "we need to clean up our flows." To a business sponsor or Chief Technology Officer (CTO), these statements are unpersuasive. To secure funding and sprint capacity for refactoring, you must translate architectural decay into concrete, measurable metrics.

To build an objective Salesforce Org Health Scorecard, delivery leaders should monitor the following five key performance indicators (KPIs):

1. Custom Field Saturation Rate

Every Salesforce edition has hard limits on the number of custom fields permitted per object (e.g., 500 for Enterprise Edition, 900 for Unlimited Edition). When core transactional objects like Account or Opportunity reach 80% saturation, the org enters a critical state. Furthermore, high saturation is often accompanied by low field fill rates. Using tools like Field Trip or standard metadata API queries, you should measure the percentage of custom fields containing data in less than 10% of records. Fields with extremely low fill rates represent "ghost metadata" that increases page layout loading times and confuses end users.

2. Trigger and Automation Multiplicity

For a given object (e.g., Case), calculate the total number of active automation engines running upon insert, update, or delete events. If an object has two Apex triggers, three active Record-Triggered Flows, and legacy Workflow Rules, it violates the foundational architectural best practice of having a single automation control point per object. High multiplicity leads to transaction recursion, exceeding the 10,000ms CPU limit, and makes debugging almost impossible because the order of execution is not guaranteed.

3. Test Class Execution Latency

Measure the total wall-clock time required to execute the entire suite of Apex test classes in a sandbox environment. In a healthy org utilising parallel testing and optimised mock data structures, this should take less than 15 minutes. In highly indebted orgs, test execution can stretch to several hours due to redundant DML operations, lack of test data factories, and unoptimised trigger execution. Long execution times act as a direct tax on your CI/CD pipeline, delaying deployments and discouraging developers from running tests frequently.

4. Static Code Analysis Violation Density

Run PMD or a similar static scanner against your repository and calculate the number of Priority 1 (Critical) and Priority 2 (Major) violations per 100 lines of Apex code. Common violations include DML operations inside loops, SOQL queries inside loops, hardcoded IDs, and empty catch blocks. A high violation density is a direct leading indicator of future production bugs and security vulnerabilities.

5. Unused Metadata and Dashboard Decay

Identify the percentage of reports, dashboards, email templates, and page layouts that have not been modified or accessed by any user in the last 365 days. A high percentage of dead metadata cluttering the user interface directly increases search index bloat and cognitive load for the system administrators.

To establish clear operational thresholds for these metrics, the following comparison table defines the boundaries of org health:

Metric Healthy Threshold Warning Threshold Critical Threshold Recommended Frequency
Field Saturation (Core Objects) < 60% of object limit 60% - 80% of limit > 80% of limit Monthly
Automation Control Points 1 Trigger Handler & 1 Flow per object 2 - 3 active automations > 3 active automations Bi-weekly
Test Suite Runtime < 20 minutes 20 - 60 minutes > 60 minutes Per deployment
PMD Critical Violations 0 violations 1 - 5 violations per 1k lines > 5 violations per 1k lines Continuous Integration
Metadata Fill Rate (Core Fields) > 85% fill rate 50% - 85% fill rate < 50% fill rate Quarterly

The Refactoring Framework: Prioritising the Backlog

Once you have quantified your technical debt, the immediate challenge is determining where to start. Attempting to clean up an entire enterprise org at once is a recipe for failure; it represents massive business risk, introduces high regression testing overhead, and will be aggressively rejected by business sponsors who demand new functional features. You must establish a structured refactoring framework that prioritises the debt backlog based on business impact and remediation effort.

The most effective approach is to categorise your technical debt backlog into a four-quadrant prioritisation matrix, plotting Business Risk / Operational Friction against Remediation Cost (Effort & Complexity).

  • Quadrant 1: High Risk, Low Effort (Quick Wins): These are items that actively cause transaction failures, CPU timeout warnings, or security vulnerabilities, but require minimal effort to resolve. Examples include deleting active validation rules that are entirely redundant, cleaning up empty catch blocks in Apex, or converting legacy workflow rules to Flow. These must be executed immediately.
  • Quadrant 2: High Risk, High Effort (Strategic Initiatives): These are the architectural bottlenecks that actively drag down your delivery velocity or cause major production outages, but require substantial refactoring. Examples include consolidating three triggers and five flows on the Account object into a single trigger framework, migrating a legacy managed package to standard features, or archiving millions of historic data records to resolve selective SOQL query issues. These require dedicated project resources and must be scheduled as separate architectural epics.
  • Quadrant 3: Low Risk, Low Effort (Sprint Fillers): Deprecated custom fields with 0% fill rate, unused email templates, and retired page layouts. While they clutter the org, they do not threaten operational stability. These can be assigned to junior developers or administrators during lighter periods or used as sprint fillers when delivery capacity permits.
  • Quadrant 4: Low Risk, High Effort (Deprioritised): Highly complex, bespoke legacy code that works perfectly and has not been modified in five years. Even if the code violates modern design patterns, if it is stable, low-risk, and requires massive effort to rewrite, it should be left alone. The cost of refactoring outweighs the business benefit.
Leader Perspective

Do not propose a dedicated "refactoring sprint" to your business steering committee. Business sponsors will almost always veto it because they see zero visible value in a sprint that delivers no new features. Instead, build a "20% Debt Tax" into your standard agile sprint capacity. In every single sprint, allocate exactly 20% of your story points to refactoring tasks from Quadrant 1 and Quadrant 2. This treats technical maintenance as a non-negotiable cost of doing business, maintaining your delivery velocity over the long term.

To illustrate how technical debt manifests in Apex and how it is refactored, consider the following standard anti-pattern where DML statements and queries are executed inside a loop. This code will fail in production when processing bulk records (e.g., during data loads or integrations) due to Salesforce's strict governor limits of 100 SOQL queries and 150 DML operations per transaction.

// ANTI-PATTERN: Heavy code debt due DML operations and SOQL queries executed inside a loop
public class AccountProcessorDebt {
    public static void updateContactsBillingAddress(List<Account> accounts) {
        for (Account acc : accounts) {
            // High Risk: SOQL query executed inside a loop. Will hit governor limit if list > 100
            List<Contact> relatedContacts = [SELECT Id, MailingStreet, MailingCity FROM Contact WHERE AccountId = :acc.Id];
            
            for (Contact con : relatedContacts) {
                con.MailingStreet = acc.BillingStreet;
                con.MailingCity = acc.BillingCity;
                
                // High Risk: DML operation executed inside a loop. Will hit governor limit if contacts > 150
                update con;
            }
        }
    }
}

By refactoring this code using bulkification best practices, we eliminate the governor limit risks and significantly reduce the transaction runtime:

// REFACTORED: Healthy, bulkified Apex code with zero code debt and optimised execution
public class AccountProcessorHealthy {
    public static void updateContactsBillingAddress(List<Account> accounts) {
        Map<Id, Account> accountMap = new Map<Id, Account>(accounts);
        List<Contact> contactsToUpdate = new List<Contact>();
        
        // Optimised: Single SOQL query outside the loop using bind variable
        List<Contact> relatedContacts = [SELECT Id, AccountId, MailingStreet, MailingCity 
                                         FROM Contact 
                                         WHERE AccountId IN :accountMap.keySet()];
                                         
        for (Contact con : relatedContacts) {
            Account acc = accountMap.get(con.AccountId);
            if (acc != null) {
                con.MailingStreet = acc.BillingStreet;
                con.MailingCity = acc.BillingCity;
                contactsToUpdate.add(con);
            }
        }
        
        // Optimised: Single DML operation outside the loop to update all records in bulk
        if (!contactsToUpdate.isEmpty()) {
            update contactsToUpdate;
        }
    }
}

Guardrails and Governance: Preventing Future Debt

Paying down technical debt is only half the battle. If your delivery organisation does not establish strict architectural guardrails and governance processes, the debt will accumulate faster than your team can refactor it. You must implement systemic controls that prevent the introduction of new technical debt in every deployment cycle.

The first control is the formal establishment of an Architecture Review Board (ARB). The ARB should consist of your Lead Solution Architect, Technical Architect, and Delivery Manager. Any request for a new custom object, integration endpoint, or complex Flow must pass through the ARB before entering the development backlog. Business units must prove that their requirements cannot be met by reusing existing custom metadata, standard objects, or out-of-the-box Salesforce configurations.

Secondly, you must automate your quality gates by integrating Static Code Analysis (SCA) directly into your CI/CD deployment pipeline. Tools like PMD, SonarQube, or Copado Robotic Testing should be configured with custom rulesets that enforce strict architectural standards. For example, your build pipeline should automatically reject any deployment if:

  • Apex unit test code coverage falls below 85% (significantly higher than Salesforce's default 75% limit).
  • Critical PMD violations (such as SOQL/DML in loops or hardcoded IDs) are detected.
  • New custom fields are added without description text and API field-level help text filled in.
  • A Flow is deployed without an active error-handling block (using standard Flow fault paths to log errors).
⚠️
Warning for Architects

Do not allow exception pathways in your CI/CD pipeline for "emergency hotfixes." The moment you permit developers to bypass static code analysis and test coverage gates to deploy an urgent patch to production, you establish a dangerous operational precedent. Emergency patches deployed without pipeline validation are the leading cause of catastrophic regressions and major org instability.

Finally, you must modify your team's Agile Definition of Done (DoD). A user story must not be marked as complete simply because the functional requirement works in a sandbox. The DoD must include strict technical debt criteria:

  1. Automation Registration: New Flow or trigger is formally documented in the org's central Automation Registry, verifying it complies with the single automation control point pattern.
  2. Static Analysis Compliance: PMD scan report confirms zero new critical or major violations are introduced.
  3. Data Dictionary Update: Any new custom fields or objects are registered in the enterprise data dictionary with complete descriptions of their business purpose, data owner, and compliance classification.
  4. Regression Testing Pass: Automated regression suite executes successfully with zero failures in the downstream staging environment.

Communicating Debt to the C-Suite

The ultimate responsibility of a Salesforce delivery leader is translating technical parameters into business language that the executive steering committee can comprehend. When pitching for budget or requesting timeline extensions to address platform health, presenting raw technical statistics like trigger count or test execution runtime will fail. Executives do not manage technical details; they manage financial cost, business risk, and strategic agility.

To successfully communicate the necessity of debt refactoring to the C-suite, structure your business case around three commercial pillars:

1. Delivery Agility and Feature Velocity

Explain that technical debt behaves as an ongoing "tax" on every single business request. If the org is clean, a new functional request might take five days to configure and deploy. If the org is heavily indebted—due to complex sharing rules, conflicting Flows, and massive Apex triggers—the same feature will take fifteen days because developers must spend ten days debugging and custom-coding workarounds. Frame this as a direct commercial penalty: carrying technical debt increases your ongoing Salesforce development costs by 200%.

2. Operational Risk and Business Continuity

Translate system limits into business-continuity risks. For example, explain that approaching the Salesforce governor CPU time limits on core objects means that during peak commercial volumes (such as quarter-end or high-traffic marketing campaigns), the system is highly likely to crash, preventing sales representatives from closing opportunities or customer service agents from logging critical support cases. Frame this in terms of financial loss per hour of system downtime.

3. Total Cost of Ownership (TCO) and Platform Value

Highlight the direct financial waste associated with carrying dead metadata. Accumulated technical bloat frequently leads organisations to purchase expensive Salesforce add-on storage, purchase supplementary software licences, or hire additional system administrators simply to manage the complexity of a chaotic environment. Explain that refactoring the org directly reduces maintenance overhead and maximises the return on their annual Salesforce licence investment.

By presenting technical debt as a commercial equation of feature velocity, business risk, and financial waste, you elevate platform health from a technical grievance to a core corporate strategy, securing the executive mandate and resources required to build a sustainable, high-performing Salesforce platform.

Key Takeaways

  • Technical debt in Salesforce consists of both code-level Apex decay and silent declarative customisation bloat, with the latter often being harder to detect and refactor.
  • Successful delivery teams monitor key quantitative metrics, including Field Saturation Rate, Trigger Multiplicity, and Test Latency, to assess platform health objectively.
  • Refactoring backlogs must be prioritised using a risk-effort matrix, ensuring that high-interest debt on core transactional objects is remediated first.
  • Establishing an Architecture Review Board and integrating automated static code analysis gates within your CI/CD pipeline are essential guardrails to prevent debt accumulation.
  • The Agile Definition of Done must incorporate non-functional technical health criteria to ensure new features are deployed without introducing regression risks.
  • To secure executive budget, delivery leaders must translate abstract technical parameters into business-critical metrics such as feature velocity, operational risk, and total cost of ownership.

Checkpoint: Test Your Understanding

1. Why is declarative (point-and-click) customisation in Salesforce uniquely prone to accumulating technical debt?

A. Because standard custom fields and flows do not count toward any Salesforce org-wide limits.
B. Because declarative tools bypass traditional compiler checks, allowing redundant or conflicting automations to be deployed without immediate technical failure, creating silent process bottlenecks.
C. Because declarative tools require extensive Apex coding knowledge to deploy correctly.
D. Because Salesforce deprecates declarative features every quarter, forcing mandatory rewrites.

2. When establishing a metric-driven refactoring programme, which metric is the most critical leading indicator of operational instability during peak business volumes?

A. The absolute count of custom fields across all standard objects in the org.
B. The percentage of test classes achieving exactly 75% code coverage.
C. Trigger and automation multiplicity on core transactional objects, indicating multiple flows, workflows, and triggers running concurrently.
D. The count of inactive user accounts that still own records.

3. What is the most effective tactical approach for a Delivery Manager to secure business funding for ongoing technical debt refactoring?

A. Requesting a dedicated three-month "refactoring sprint" where all feature development is completely paused.
B. Implementing a continuous "20% Tax" allocation within every active sprint, framing it as a maintenance premium that directly preserves feature delivery velocity.
C. Exclusively presenting raw PMD static analysis violation counts to the Chief Financial Officer.
D. Reverting all custom fields with less than 20% fill rate to standard fields without consulting business units.

Discussion & Feedback