LearnFrenzy
Sign in Take a free test

Salesforce Apex interview · Set 2 of 7

Governor Limits and Bulkification

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

Write for 200 records, always

Bulkification is the most tested Apex habit. Collect keys, query once into maps, do DML once, and choose async processing when work outgrows a single transaction.

  • LimitsSOQL, DML, rows, CPU and heap.
  • PatternsCollect → query once → map → DML once.
  • ScaleSOQL for loops, Limits class and Batch Apex.

Nothing marks a Salesforce developer faster than code that breaks with 200 records. Interviewers ask about governor limits to check that you write bulkified code by default — one query, one DML, collections and maps everywhere.

1. Which governor limits should you know by heart?

Per synchronous transaction: 100 SOQL queries (200 async), 50,000 rows retrieved by SOQL, 150 DML statements, 10,000 rows processed by DML, 10 seconds CPU time (60 async), 6 MB heap (12 MB async) and 100 callouts. Triggers receive records in chunks of up to 200.


2. Why is SOQL inside a loop a problem? Fix it.

Each loop iteration runs a query; with 200 records you hit “Too many SOQL queries: 101”. Collect the keys first, run one query, and use a map inside the loop.

// BAD: one query per contact
for (Contact c : Trigger.new) {
    Account a = [SELECT Id, Industry FROM Account WHERE Id = :c.AccountId];
    c.Industry__c = a.Industry;
}

// GOOD: one query for all contacts
Set<Id> accountIds = new Set<Id>();
for (Contact c : Trigger.new) if (c.AccountId != null) accountIds.add(c.AccountId);

Map<Id, Account> accounts = new Map<Id, Account>(
    [SELECT Id, Industry FROM Account WHERE Id IN :accountIds]);
for (Contact c : Trigger.new) {
    Account a = accounts.get(c.AccountId);
    if (a != null) c.Industry__c = a.Industry;
}

3. How do you avoid DML inside loops?

Add records to a list inside the loop and run one DML statement after it.

List<Task> followUps = new List<Task>();
for (Opportunity o : closedWon) {
    followUps.add(new Task(WhatId = o.Id, OwnerId = o.OwnerId,
                           Subject = 'Kick-off call', ActivityDate = Date.today().addDays(2)));
}
insert followUps;    // one DML for up to 10,000 rows

4. How do you process more than 50,000 records?

Use Batch Apex, which processes records in chunks (default 200, up to 2,000) with fresh limits per chunk and can query up to 50 million records with a QueryLocator. For simple updates, a SOQL for loop reduces heap usage by fetching rows in batches of 200.

for (List<Case> chunk : [SELECT Id, Status FROM Case WHERE Status = 'New' AND CreatedDate < LAST_N_DAYS:90]) {
    for (Case c : chunk) c.Status = 'Closed - Stale';
    update chunk;        // careful: still counts DML statements per chunk
}

5. How can you check limits at runtime?

The Limits class reports usage and maximums, for example Limits.getQueries() and Limits.getLimitQueries(). Use it to log consumption in heavy code paths or to stop early and hand work to async processing.

if (Limits.getQueries() > Limits.getLimitQueries() - 5) {
    System.enqueueJob(new ContinueProcessing(remainingIds));   // move the rest to async
    return;
}

6. What causes CPU time limit errors and how do you fix them?

Nested loops over large collections, repeated string building, heavy formula or flow logic on the same save, and recursion. Fix with maps instead of nested loops, less work per record, moving non-urgent work to async Apex, and avoiding unnecessary trigger re-entry.

// O(n × m) nested loops
for (Contact c : contacts) for (Account a : accounts) if (c.AccountId == a.Id) { /* ... */ }

// O(n + m) with a map
Map<Id, Account> byId = new Map<Id, Account>(accounts);
for (Contact c : contacts) { Account a = byId.get(c.AccountId); /* ... */ }

7. What does “bulkified” mean beyond triggers?

Any code path — invocable methods called by Flow, batch execute methods, REST endpoints, LWC Apex methods — may receive many records. Design every method to accept collections (List<Id>), query once and perform DML once.

public with sharing class OpportunityService {
    public static void closeAsLost(Set<Id> oppIds, String reason) {        // collection in
        List<Opportunity> opps = [SELECT Id FROM Opportunity WHERE Id IN :oppIds WITH USER_MODE];
        for (Opportunity o : opps) { o.StageName = 'Closed Lost'; o.Loss_Reason__c = reason; }
        update as user opps;                                                 // one DML
    }
}

8. How do you reduce heap size usage?

Query only the fields you need, use SOQL for loops for large result sets, clear collections you no longer need, avoid storing full records when Ids suffice, and move large data processing to Batch Apex (higher heap limit).


Remember

Key points

  • 100 SOQL, 150 DML

    Per synchronous transaction.

  • Never query or DML in loops

    Collections in, one call out.

  • Maps beat nested loops

    Saves CPU time.

  • Big data → Batch Apex

    Fresh limits per chunk.

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 Are limits per trigger or per transaction? Basic

    Per transaction — every trigger, flow and class running in that save shares the same limits.

  2. 2 What is the maximum number of records a trigger receives at once? Basic

    200 per chunk; a 1,000-record data load fires the trigger five times within limits that reset per chunk for API batches.

  3. 3 Do aggregate queries count against the 50,000-row limit? Intermediate

    Rows used to compute aggregates count towards the query-row limit, so COUNT() on huge tables can still fail; use reports or batch processing for very large counts.

  4. 4 What is the callout limit and timeout? Intermediate

    100 callouts per transaction, with a cumulative timeout of 120 seconds; set explicit timeouts per request.

  5. 5 Why can a Flow cause “Too many SOQL queries” in your trigger? Advanced

    Record-triggered flows on the same object run in the same transaction and share limits; a Get Records inside a loop in a flow consumes queries too.

  6. 6 How do you avoid hitting the 10,000 DML row limit in one transaction? Intermediate

    Split work across async jobs — Queueable chaining or Batch Apex — so each transaction stays within the limit.

Preparing with friends?

Share this page with your study group or placement batch.

Search LearnFrenzy

Esc

Quick links