Apex Governor Limits – What Exactly is the Execution Time Limit of 10 Minutes?

Execution Governors and Limits documentation says that

Maximum execution time for each Apex transaction is 10 minutes for
both Synchronous and Asynchronous

To understand this I executed the below code in anonymous apex window :

Long startTime = System.now().getTime();
Long maxLimit = 9*60*1000; //I am taking max limit as 9 mins.
while(System.now().getTime() - startTime <= maxLimit ){  
}

I get this error :

enter image description here

What is one use case where we don't run into CPU time limit(or other limits) but reach execution time limit?

Best Answer

The ten minute limit is pretty hard to reach in normal conditions, but you need to remember that executing Apex Code is only one part of a transaction, while the ten minute limit applies to everything in the transaction, literally in wall-clock time. For example, it's possible to roll back transactions partway using the DML retry mechanism; while the CPU time can be harvested back because of retries, the limit towards the ten minutes would still apply.

One "easy" way to see this is to write a complicated query with sub-queries and expensive formulas against an object with millions of records in a Batchable's start method. If there's a lot of database time used, this could theoretically cause the Batchable class to fail. That's why it's preferable to query only the fields you need, and then query the remainder of the fields and any sub-queries in the execute method.

Realistically, you'll probably never see this error, but you should know that it can occur. In those cases, all you can do is try again; this would usually resolve the issue. One theoretical point where you could hit this limit is if you consistently use row locks in a way that causes maximum lock timeout (~10 seconds), which would theoretically allow you to construct a transaction that runs for an hour or longer if not for this limit. To avoid that situation, remember to always lock parents before children, and do so in record Id order, when possible.

Related Topic