[SalesForce] Connection was cancelled here, Interrupting long running request

Sometimes an Apex request gets interrupted/terminated by Force.com. The underlying Apex request contains numerous DML statments (insert into around 13 custom objects) all of which marked at a savepoint. There are no triggers/workflows/formula fields. Also these objects don't have too many fields. There are only few hundreds of records.

  1. What could be possible reasons for DML operation to run long and be interrupted by Force.com?
  2. As these are runtime exception, what is the best possible way to handle/react to these exceptions?
  3. What troubleshooting will help?

Appreciate any suggestion.

Best Answer

In no particular order...

  1. Are you sure the most time-consuming part is the DMLs? If it's initiated from visualforce and you have a complex page it might take long time to deserialize viewstate, run basic validations (like required fields being filled in) and setters before even your actual action method is called. Use debug logs to compare the request's initial timestamp and the timestamp on first DML operation.
  2. Any SELECT ... FOR UPDATE that might cause the request to wait for a resource?
  3. Any callouts being made before actual DML?
  4. Do you really need the savepoint in this transaction? Can you move some parts (like less important inserts) to @future?
  5. Are there any other signs of problems - are you getting close to queries limit maybe? returned rows? script statements? Multiple inserts in a loop?
  6. Field history tracking, email sending and sharing rules recalculation happen outside the transaction so I don't think it will matter. Formulas have no impact either (they're calculated when you view data). But are there any unique fields or validation rules that SF needs to verify that might take some time (like VLOOKUP() in validation rule?
  7. Maybe it's not your code's fault - use debug logs to check if any of the managed packages you might have is also invoked (they'll have their own triggers, in theory separate set of governor limits, I'm not too sure about the request time though)
  8. Any particular time of day it happens (rush hours?) or for specific user maybe?