LearnFrenzy
Sign in Take a free test

Salesforce Apex interview · Set 4 of 7

Asynchronous Apex: Future, Queueable, Batch and Schedulable

  • 6 follow-up questions
  • 4 key points
  • Code examples
Test yourself

Pick the right async tool

Queueable for most jobs, Batch for big data, Schedulable for timing, and @future only for simple legacy cases. Explain limits, chaining and monitoring for each.

  • Tools@future, Queueable, Batch and Schedulable.
  • PatternsChaining, Stateful and callouts.
  • OperationsMonitoring and failure handling.

When work is too slow, too big or needs a callout after DML, you move it to asynchronous Apex. Interviewers expect you to choose the right tool and explain the limits of each — not just recite syntax.

1. When should you use asynchronous Apex?

For long-running work that would exceed synchronous limits, callouts after DML (not allowed in the same transaction before commit), processing millions of records, avoiding mixed DML errors, and work that does not need to finish before the user sees the result. Async transactions also get higher limits (200 SOQL, 60 s CPU, 12 MB heap).


2. What are @future methods and their limitations?

Static void methods annotated @future run later in their own transaction. Parameters must be primitives or collections of primitives (pass Ids, not records). Use @future(callout=true) for callouts. Limitations: no job Id to monitor, no chaining (a future cannot call another future), and at most 50 per transaction.

public class AddressVerifier {
    @future(callout=true)
    public static void verify(Set<Id> accountIds) {
        List<Account> accounts = [SELECT Id, BillingPostalCode FROM Account WHERE Id IN :accountIds];
        // ... call the address API, set Verified__c, update accounts
    }
}

3. Why is Queueable usually preferred over @future?

Queueable classes accept complex types (records, custom objects) through the constructor, return a job Id you can monitor, support chaining (enqueue the next job from execute) and can make callouts with Database.AllowsCallouts. They are the modern default for single-job async work.

public class SyncOrdersJob implements Queueable, Database.AllowsCallouts {
    private final List<Id> orderIds;
    public SyncOrdersJob(List<Id> orderIds) { this.orderIds = orderIds; }

    public void execute(QueueableContext ctx) {
        List<Id> batch = new List<Id>();
        for (Integer i = 0; i < Math.min(50, orderIds.size()); i++) batch.add(orderIds[i]);
        ErpClient.push(batch);                                   // callout
        if (orderIds.size() > batch.size()) {
            List<Id> rest = new List<Id>();
            for (Integer i = batch.size(); i < orderIds.size(); i++) rest.add(orderIds[i]);
            System.enqueueJob(new SyncOrdersJob(rest));          // chain the remainder
        }
    }
}
Id jobId = System.enqueueJob(new SyncOrdersJob(ids));

4. Explain Batch Apex and its three methods.

A class implementing Database.Batchable<SObject>: start returns a QueryLocator (up to 50 million records) or an Iterable; execute processes each chunk (default 200, max 2,000) with fresh limits; finish runs once at the end for notifications or chaining another job.

public class DeactivateStaleUsers implements Database.Batchable<SObject>, Database.Stateful {
    private Integer deactivated = 0;                        // kept across chunks thanks to Stateful

    public Database.QueryLocator start(Database.BatchableContext bc) {
        return Database.getQueryLocator(
            'SELECT Id FROM User WHERE IsActive = true AND LastLoginDate < LAST_N_DAYS:90');
    }
    public void execute(Database.BatchableContext bc, List<User> scope) {
        for (User u : scope) u.IsActive = false;
        update scope;
        deactivated += scope.size();
    }
    public void finish(Database.BatchableContext bc) {
        System.debug('Deactivated ' + deactivated + ' users');
    }
}
Database.executeBatch(new DeactivateStaleUsers(), 200);

5. What does Database.Stateful do?

Normally each execute runs with a fresh instance state, so member variables reset between chunks. Database.Stateful keeps instance variables across chunks — for running totals or error lists. It adds serialisation overhead, so keep the state small.


6. How do you schedule Apex?

Implement Schedulable and schedule it with a CRON expression via System.schedule or Setup. The scheduled job usually just starts a batch or queueable so the heavy work runs with async limits.

public class NightlyCleanup implements Schedulable {
    public void execute(SchedulableContext sc) {
        Database.executeBatch(new DeactivateStaleUsers(), 200);
    }
}
// Seconds Minutes Hours Day_of_month Month Day_of_week (Optional_year): every day at 2 AM
System.schedule('Nightly cleanup', '0 0 2 * * ?', new NightlyCleanup());

7. Future vs Queueable vs Batch vs Schedulable — summary?

  • @future — quick fire-and-forget with primitive parameters; legacy.
  • Queueable — default async job: complex parameters, job Id, chaining, callouts.
  • Batch — very large data volumes with chunked processing and fresh limits per chunk.
  • Schedulable — run something at a time or on a recurring schedule.

8. How do you monitor and handle failures in async jobs?

Query AsyncApexJob for status, errors and processed counts; check Apex Jobs in Setup; log failures to a custom log object; and in Batch Apex implement Database.RaisesPlatformEvents to publish BatchApexErrorEvent for failed chunks, which a trigger can record or retry.

AsyncApexJob job = [SELECT Status, NumberOfErrors, JobItemsProcessed, TotalJobItems, ExtendedStatus
                    FROM AsyncApexJob WHERE Id = :jobId];

Remember

Key points

  • Queueable is the default

    Job Id, chaining and complex params.

  • Batch = chunks + fresh limits

    Up to 50 million records.

  • Stateful keeps variables

    Across execute chunks.

  • Callout after DML → async

    Uncommitted work blocks callouts.

Interview drill

Follow-up questions

What the interviewer asks after your first answer. Turn on practice mode, answer each one aloud, then reveal.

  1. 1 Can you call a future method from a batch class? Intermediate

    No — future methods cannot be called from batch or other future methods. Use Queueable instead.

  2. 2 How many Queueable jobs can you enqueue from one transaction? Intermediate

    50 from a synchronous transaction; from inside a Queueable you can enqueue only one child job (chaining).

  3. 3 What is the maximum batch size? Basic

    2,000 records per execute when using a QueryLocator; the default is 200.

  4. 4 How many batch jobs can run at once? Intermediate

    Five active or queued at a time, with up to 100 more held in the Apex flex queue.

  5. 5 How do you avoid a mixed DML error? Advanced

    Mixed DML occurs when setup objects (User, Group) and non-setup objects are changed in one transaction. Move one of the operations to async Apex (Queueable or @future).

  6. 6 What is Transaction Finalizer? Advanced

    A class attached to a Queueable with System.attachFinalizer that runs after the job, even if it failed — ideal for logging and retry logic.

Preparing with friends?

Share this page with your study group or placement batch.

Search LearnFrenzy

Esc

Quick links