[SalesForce] Are batch jobs guaranteed to run sequentially

I encounter an UNABLE_TO_LOCK_ROW error in a batch job where I do an upsert on a custom object. The problem is that I am not able to guarantee that a particular record is only upserted in one single batch, i.e. a record may (and will) be upserted multiple times during the execution of the batch job.

If the execution of batch jobs is strictly sequential, i have to look elsewhere for the cause of the lock error. If execute() methods of the same batch job can run in parallel, however, this may be the cause of the lock error and may even lead to serious logical errors (e.g. getting two records from two upserts instead of just one if they were run sequentially).

So my question is: Am i guaranteed that batches from one instance of a batch job are always processed strictly sequentially?

Best Answer

Yes, currently 'execute' methods run sequentially, though the documentation does not make it perfectly clear on this. In the future Salesforce may enable parallel running, though I'd expect this to be enabled via a annotation or interface marker on the class. So hopefully we would get the chance to opt into it or not.

So it maybe possible your users are running your job again and thus in parallel over the same data, or indeed other activities as you suspect.

Note: Also this comment from the Batch Apex docs, which might be important to you.

Batches of records are not guaranteed to execute in the order they are received from the start method.