Interview Questions on Batch Apex

1. Why do we use Batches?

    If we have a use case to process millions of records, it would be difficult to do this manually as well as in a synchronous context (the time limit is 10 seconds) so we use batches to process bulk data or records together, with a new set of Governer limits per transaction.

2. What did you mean by "a new set of Governer limits per transaction"?

    Batch Jobs can be operated on any size of records, with a maximum of 200 records per batch. Each batch is a transaction. The Apex governor limits are reset for each transaction.

3. Can you write a batch class blueprint?

4. What is Database.QueryLocator & Iterable<sObject>?

    In Database.QueryLocator, we use a simple query (SELECT) to generate the scope of objects. The governor limit for the total number of records retrieved by SOQL queries is bypassed, i.e. it can return up to 50 million records.

In Iterable<sObject>, we can create a custom scope for processing, which would be not possible to create using SOQL where clauses. the governor limit for the total number of records retrieved by SOQL queries is still enforced. For example,

So we can return our custom scope by simply calling as below.

Also, If the code accesses external objects and is used in batch Apex, use Iterable<sObject> else Database.QueryLocator.

5. If We use Itereable<sObject>, will We be able to process Batches in a specific order?

    Batches of records tend to execute in the order in which they’re received from the start method. However, the order in which batches of records execute depends on various factors. The order of execution isn’t guaranteed. So even if you do ORDER BY, there is no guarantee of processing in the same order.

6. In a batch context, can I process Data in a specific order?

    Yes, You can order the scope of that batch, however, you want and process it.

7. Can I query related records using Database.QueryLocator?

    Yes, You can do subquery for related records, but with a relationship subquery, the batch job processing becomes slower. A better strategy is to perform the subquery separately, from within the execute method, which allows the batch job to run using faster.

8. Can I Use FOR UPDATE in SOQL using Database.QueryLocator?

    No, We can’t. It will through an exception stating that “Locking is implied for each batch execution and therefore FOR UPDATE should not be specified”

The reason is, If we query the entire database of an org using SELECT … FOR UPDATE, we would lock the entire database as long as the batch was active.

9. Let’s say Record A has to be processed before Record B, but Record B came in the first Batch and Record A came in the second batch. The batch picks records that are unprocessed every time it runs. How will you control the processing Order?

    The Processing order can’t be controlled, but we can bypass the record B processing before Record A. We can implement Database.STATEFUL and use one class variable to track whether Record A has been processed or not. If not processed and Record B has come, don’t process Record B. After all the execution completes, Record A has already been processed so Run the batch again, to process Record B.

10. What is Database.STATEFUL?

    Database.STATEFUL is a Marker interface that helps in maintaining state across transactions. When using Database.STATEFUL, only instance member variables retain their values between transactions. Static member variables don’t retain their values and are reset between transactions.

11. Is there any other interface that can be implemented by a Batch apex?

    Database.AllowsCallouts is another Marker Interface, which is implemented to make HTTP callouts through Batch.

12. What is the Limit of Size of scope in a batch?

    If the start method of the batch class returns a QueryLocator, the optional scope parameter of Database.executeBatch can have a maximum value of 2,000. If set to a higher value, Salesforce chunks the records returned by the QueryLocator into smaller batches of up to 2,000 records. If the start method of the batch class returns an iterable, the scope parameter value has no upper limit.

13. Let’s say, we have run an apex batch to process 1000 records, and It is running with batch size 200. Now, while doing DML on the 398th record, an error occurred, What will happen in that case?

    In batches, If the first transaction succeeds but the second fails, the database updates made in the first transaction are not rolled back.

    Since the batch size is 200, so the first batch will be processed completely and all data will be committed to DB. In seconds batch, if we are committing records using normal DML statements like insert, update then the whole batch will be rollbacked. So records 201 to 400 will not be processed.

    If we use the Database DML operations like Database.insert with AllOrNone as false, then partial commit can happen and only 398th record will not be processed in that batch and total of 199 records will be processed. Also, the other batch execution will not gonna be hampered.

14. Can I call any method from Batch Apex?

    Methods declared as future can’t be called from a batch Apex class.

15. How can you track the progress of a Batch job?

    The Database.executeBatch method returns the ID of the AsyncApexJob object.

16. How can you stop a Batch job?

    The Database.executeBatch and System.scheduleBatch method returns an ID that can be used in System.abortJob method.

17. Let’s say, I have 150 Batch jobs to execute, Will I be able to queue them in one go?

    Once you run Database.executeBatch, the Batch jobs will be placed in the Apex flex queue and its status becomes Holding. The Apex flex queue has the maximum number of 100 jobs, Database.executeBatch throws a LimitException and doesn’t add the job to the queue. So almost 100 jobs can be added in one go.

Also, if Apex flex queue is not enabled, the Job status becomes Queued, Since the concurrent limit of the queued or active batch is 5, so almost 5 batch jobs can be added in one go.

18. Can I change the order of already queued Batch Jobs?

    Only jobs having status as Holding can be moved. It can be done through UI of Apex Flex queue or we can use Apex Flex Queue Methods.

19. How Can I schedule a Batch Apex?

    Through System.scheduleBatch Method, we can schedule batch for once at a future time. This method returns the scheduled job ID also called CronTrigger ID.

20.  How Can I Test a Batch Apex?

    We can test it by calling the Batch job between Test.startTest() and Test.stopTest(). Using the Test methods startTest and stopTest around the executeBatch method to ensure that it finishes before continuing your test. All asynchronous calls made after the startTest method are collected by the system. When stopTest is executed, all asynchronous processes are run synchronously.

Also, we can test only one execution of the execute method. So we need to set the scope as per the governor limits.