Many of our customers have written custom cloud codes and encountered performance issues once they hit the production—especially their cloud code was throwing error code 1904 (Execution Time Threshold Exception). Code written inside any custom code must get executed within 10 seconds otherwise it will get killed and client will receive 1904 error code with execution time threshold exception. There are a few guidelines explained below that will help you in optimizing your custom cloud code so that you can avoid these time-out exceptions.
Avoid too many Server API calls
We have seen the instances where too many Cloud API calls were made within a single flow of custom code. More API calls will result in more latency and will cascade to Execution Time Threshold Exception. Ideally there should not be more than 3-4 API calls per custom cloud code.
Avoid too many conditions in Single Query for Storage
There are some instances where storage queries were written with 10-15 conditional operators in a single storage query. Putting too many conditions in a single query will result in latency and hence might result in Execution Time Threshold Exception (For example, finding docs where name=nick and age >30 and country=US and gender=Male and so on). Ideally there should not be more than 3-4 conditional operators in a single query.
Using Static Variable does not make any difference
Your deployed custom code runs in different clusters and using static variable will not improve the performance. Also, you should not use this variable as a global variable to calculate something because it will result in inconsistent results.
Keep an eye on Metering Data
You should keep an eye on metering data and look for execution time for your custom code—if it is continuously going above 5 seconds, it means you need to re-look and optimize it for better performance.