We’re thrilled to introduce ApexGuru, a revolutionary generative AI-based feature now generally available in Scale Center. ApexGuru empowers Salesforce Developers by offering a transformative approach to addressing critical anti-patterns and hotspots in their Apex code.

This innovative solution leverages runtime profiles, providing actionable insights and prescriptive code recommendations. It’s powered by cutting-edge generative AI models developed in collaboration with Salesforce AI Research, redefining the way developers tackle critical scale issues in their Apex code. ApexGuru is available at no extra charge to all Scale Center customers, including UE production and full-copy sandbox orgs, signature orgs, and all Scale Test customers.

In this blog post, we’ll explore how this game-changing innovation helps you proactively assess and resolve performance issues in your Apex code with actionable AI-driven insights, allowing you to scale applications confidently on the Salesforce Platform.

The importance of building for scale

Scaling efficiently is a critical aspect of designing and implementing applications on the Salesforce Platform. Many customers only become aware of scalability issues once end users begin to report degraded performance and usability — at this point, these issues have already impacted the business. Designing for the future, and predicting and simulating future business traffic, can be very challenging. While some errors can be caught during the design phase, most errors occur only at runtime in production, and sometimes, they manifest during peak loads.

Last year, we announced the general availability of Salesforce Scale Center to address these problems in scale and performance. With Scale Center, you can now address application scalability proactively instead of reactively, ensuring more available, responsive, and performant solutions for your end user. With Scale Center, we are continuously identifying major areas in performance and scale where our customers need help, and leveraging state-of-the-art technology innovations in AI to help you resolve these issues.

Mastering scalable and efficient Apex code has always been a quest for developers. Often, developers unintentionally adopt suboptimal coding practices, injecting anti-patterns that can trigger Salesforce’s governor limits. These limits are pivotal in preventing misuse, ensuring fair resource distribution, and maintaining the overall health of the Salesforce environment.

Now, let’s explore some of the specific governor limits that ApexGuru addresses, equipping you with a potent solution to refine your coding practices and confidently navigate the Salesforce Platform.

  • CPU Time: Apex code is allocated a certain amount of CPU time for execution. If the code exceeds this limit, a “CPU time limit exceeded” error is thrown.
  • SOQL Queries: Salesforce enforces limits on the number of SOQL query issues per transaction. This includes both the number of queries issued and the total number of rows retrieved.
  • Limit on SOQL Statement Length: A maximum of 4,000 characters is allowed for each string within a WHERE clause.
  • DML Statements: There are limits on the number of records that can be processed in a single transaction. This includes both inserts and updates.
  • Apex Character Limit: This is the aggregate character count in custom Apex codes within the customer’s organization, excluding those from managed packages.

With ApexGuru, we utilize breakthrough innovations in AI and ML to detect these anti-patterns in Apex code, and we also provide actionable recommendations on how to fix these issues. All of this is based on your org’s run time profiles, ensuring that ApexGuru recommendations are highly customized per org and very impactful. ApexGuru’s AI capabilities are powered by CodeGen models that have been developed and pre-trained by Salesforce AI Research. CodeGen is a family of transformer decoder models trained on code and adapted and fine-tuned for ApexGuru’s code recommendation capabilities.

Detecting and fixing critical anti-patterns in Apex code

ApexGuru automates the detection of critical anti-patterns and performance hotspots in your Apex code and provides AI-driven insights and very prescriptive code recommendations. In this section, we’ll describe some of these critical anti-patterns.

In Salesforce Apex, Schema.getGlobalDescribe is a method that allows developers to dynamically fetch metadata information about all objects in the Salesforce schema. While this offers flexibility, it can be resource-intensive, especially in orgs with numerous custom objects and fields, consuming CPU time and memory, and contributing to governor limits like CPU time limits.

Consider the code snippet below that aims to retrieve metadata information for a specific object, but ends up getting metadata for all objects. This can lead to increased resource consumption, high latency, and potential governor limits.

Original code

Proposed amendment

The proposed amendment offers a more efficient way of retrieving metadata for sObjects. Additionally, you can check if an sObject exists in an org with the expression. At this point, the AI does not generate a null check, but it is better to add a null check if your application needs it.

The graph below depicts the average app CPU time for two entry points spanning seven weeks. Notably, on the week of 12/4, the implementation of ApexGuru recommendations was carried out and deployed in the production environment.

Initially, both entry points exhibited high app CPU time consumption. However, following the deployment, there was a noticeable reduction, with entry point 1 decreasing by 60% and entry point 2 by 45%. This significant improvement indicates the positive impact of utilizing ApexGuru in optimizing and enhancing the efficiency of the Apex code.

Graph depicting the noticeable reduction of app CPU time after deploying the code recommendations in production

SOQL/DML Anti-pattern analysis

SOQL/DML anti-patterns significantly impact Apex performance. In another scenario, let’s explore a common issue where a customer aims to create a Task list for all contacts.

A common practice is utilizing a list of sObjects for IN-bind filtering on the ID field of a SOQL query, providing a convenient coding approach. In this case, Apex converts the list of sObjects to a String representation, potentially causing a performance bottleneck. This stringification process can be resource-intensive, especially for sObjects with numerous fields. Additionally, there’s a risk of exceeding the maximum 4000 characters limit for the converted string in the WHERE clause.

To address this, the recommended approach is to obtain the list of IDs for the IN-bind, preventing unnecessary CPU time consumption, and minimizing the risk of hitting governor limits.

The graphical representation illustrates the average DB CPU time for three distinct entry points across a seven-week timeframe. Significantly, during the week commencing 12/4, the implementation of ApexGuru recommendations was executed and deployed within the production environment. Initially, each of the three entry points demonstrated elevated DB CPU time consumption. Subsequent to the deployment, a discernible reduction occurred, with entry point 1 decreasing by 30%, entry point 2 by 55%, and entry point 3 by 70%.

Chart illustrating the impact of ApexGuru recommendations on DB CPU time.

To help you make the changes faster, ApexGuru pinpoints the exact class and line of code where the anti-pattern was detected, and also provides the recommended code fix. Furthermore, to help you prioritize these issues, it organizes recommendations into critical, major, and minor, based on the expected impact.

ApexGuru report showing critical anti-patterns and prescriptive LLM-powered code recommendations

Additional insights on code in Scale Center

ApexGuru also surfaces additional performance insights on your Apex code. Customers get an overview of methods that use the most CPU time. They see methods using over 5% of CPU, flagged as critically expensive, as well as methods using 2-5% of CPU, flagged as expensive.

You can analyze these methods and optimize their performance to further improve org scalability. These insights are generated from your most recent 15 days of usage, so you can make informed decisions based on the latest runtime telemetry. You can also see deployed Apex classes and methods that will never be executed.

Having a lot of unused code can add to cognitive overload, impacting developer productivity. Reducing unused code can additionally improve application performance and also help reduce your chances of hitting governor limits for exceeding Apex characters.

Get started with ApexGuru in Scale Center

ApexGuru is available to all Scale Center customers at no additional cost. Customers can access ApexGuru using the Scale Insights feature of Scale Center.

Product considerations:

  • ApexGuru has no impact on org performance or storage limits
  • Customer code is not used for training the ML models for ApexGuru
  • The artificial intelligence models that power ApexGuru look at your Apex code to provide high-impact recommendations
  • Please note that like Scale Center, ApexGuru isn’t supported in Government Cloud Plus
  • If you would like ApexGuru to be enabled and don’t fall into the above categories, please reach out to your account representative

How to access ApexGuru:

  1. Navigate to Setup.
  2. Enter Scale Center in the Quick Find box, and click on the ApexGuru tab under the Scale Insights leaf.
  3. Enable ApexGuru for your org by accepting the ApexGuru Agreement.

Screenshot showing the Accept the ApexGuru Agreement notification

Note: It may take up to 24 hours for ApexGuru reports to appear after enabling ApexGuru in Scale Center. Insights are generated within a day of enabling and then weekly afterward.

Conclusion

You may be familiar with another Salesforce feature called Code Analyzer that also gives you Apex insights. Know that Code Analyzer is a Salesforce CLI plugin and VS Code extension that statically analyses your Apex code to give you recommendations on improving it. This tool integrates various open-source, static application security testing (SAST) tools, providing developers with the means to produce secure and well-maintained code.

In contrast, ApexGuru analyzes Java Virtual Machine (JVM) traces from your production org with an LLM that can find issues with your Apex code when it’s being executed in runtime, such as performance issues. Both features are complimentary and can help you improve your Apex code at different stages of the development lifecycle.

AI-powered code analysis tools are changing the way we analyze and improve code. And these are only the first steps for Apex. Scale Center is working on additional and more complex, AI-powered, anti-pattern detention and resolution, providing impact measurement for recommendations, and also providing targeted search to help with further prioritization.

Check out our ApexGuru help page to learn more. Try it out today and be mesmerized by this game-changing feature in Scale Center.

Resources

About the authors

Ravi Raina is Director Product Management at Salesforce working on the Scalability Products portfolio. He can be reached at LinkedIn and X (Twitter).

Gokulakrishnan Gopalakrishnan is Principal Member of Technical Staff at Salesforce working on ApexGuru. He can be reached at LinkedIn and X (Twitter).

Get the latest Salesforce Developer blog posts and podcast episodes via Slack or RSS.

Add to Slack Subscribe to RSS