36 Salesforce Apex and LWC Interview Questions and Answers

36 Salesforce Apex and LWC interview questions and answers banner from Coursack
Interview Questions Salesforce

36 Salesforce Apex and LWC Interview Questions and Answers

⏱ Updated November 202636 questions17 min read

Preparing for a Salesforce Developer interview? These 36 questions go beyond definitions. They cover architecture, design trade-offs, diagrams and real use cases for Apex and Lightning Web Components (LWC), the way senior interviewers actually ask them. Use the contents to jump to a topic, then build the skills with our Salesforce Developer Training.

Apex Design and Architecture

1. What happens, in order, when a user saves a record that has validation rules, flows and triggers?

Salesforce follows a fixed order of execution. Knowing it lets you explain why a field value changed unexpectedly or why a rule fired twice. In simplified form:

Save request
 1. System validation (required fields, field formats)
 2. Before-save record-triggered flows
 3. Before triggers
 4. Custom validation rules
 5. Duplicate rules
 6. Record saved to DB (not yet committed)
 7. After triggers
 8. Assignment, auto-response, workflow rules
 9. After-save record-triggered flows
10. Roll-up summaries, sharing, then COMMIT
11. Post-commit: emails, async jobs, platform events

Interview tip: say that field updates made in a before trigger or before-save flow do not need extra DML, while after-save logic needs DML and can re-fire triggers.

2. How would you design a trigger framework for a large org?

Use one trigger per object that does nothing except delegate to a handler class. The handler routes by context (before insert, after update and so on) to small service methods, so logic is testable and ordered. Add a bypass switch (a custom permission or custom metadata flag) for data loads, and a recursion guard.

AccountTrigger
   └─ AccountTriggerHandler (routes by context)
         ├─ AccountValidationService
         ├─ AccountTerritoryService
         └─ AccountSyncService (enqueues async work)

Keep triggers free of SOQL and DML inside loops, and put business logic in service classes that Flow, LWC and REST can reuse.

3. A trigger updates a record and fires itself again. How do you prevent recursion safely?

A plain static Boolean is a trap: in a batch of 200 records split into chunks, the flag blocks the second chunk. Track processed record Ids in a static Set instead, and only process Ids not yet seen. Better still, design logic so it only acts when a relevant field actually changed.

public class TriggerGuard {
  private static Set<Id> done = new Set<Id>();
  public static Boolean first(Id recordId) {
    return done.add(recordId); // false if already seen
  }
}
Want to answer these with confidence? Learn it live with an instructor.View Salesforce courses
4. How do you bulkify code, and how would you review code for bulk problems?

Assume every trigger receives up to 200 records. Collect Ids first, run one SOQL query outside the loop into a Map, then loop in memory and do one DML at the end. In review, look for SOQL or DML inside loops, hardcoded Ids, and queries that depend on Trigger.new[0].

// Bad: query per record
for (Contact c : Trigger.new) {
  Account a = [SELECT Name FROM Account WHERE Id = :c.AccountId];
}
// Good: one query, map lookup
Set<Id> ids = new Set<Id>();
for (Contact c : Trigger.new) ids.add(c.AccountId);
Map<Id, Account> accs = new Map<Id, Account>(
  [SELECT Name FROM Account WHERE Id IN :ids]);
5. Explain with sharing, without sharing and inherited sharing. How do you enforce object and field security?

with sharing applies the running user’s record access rules, without sharing ignores them, and inherited sharing takes the caller’s mode (a safe default for utility classes). Sharing does not enforce object permissions or field-level security by itself. Use WITH USER_MODE in SOQL and DML, or Security.stripInaccessible(), to enforce CRUD and FLS.

List<Account> rows = [
  SELECT Name, AnnualRevenue FROM Account
  WITH USER_MODE LIMIT 50];

Use without sharing only for narrow, documented cases, such as a service that must count records the user cannot see.

6. Your org hits “CPU time limit exceeded” in a trigger. How do you investigate and fix it?

Capture the transaction in a debug log and check the limits summary to see whether time is spent in Apex, flows or managed packages. Typical causes are nested loops over large collections, repeated string concatenation, heavy describe calls inside loops, and several automations stacking on one object. Fixes: replace nested loops with Maps, cache describes in static variables, move heavy work to Queueable or Batch, and consolidate automation so each object has one clear flow and trigger owner.

Asynchronous Apex and Integration

7. When do you choose Future, Queueable, Batch or Schedulable Apex?

Pick by volume and need:

Future      small, fire-and-forget, simple parameters
Queueable   chainable, object params, job Id, callouts
Batch       thousands to millions of records, chunked
Schedulable run something at a fixed time (often starts a Batch)

Prefer Queueable over Future for new code, because it accepts complex types, returns a job Id and can chain. Use Batch whenever data volume could exceed a single transaction’s limits.

8. Design a nightly process that updates 5 million records.

Use Batch Apex with a QueryLocator, which can iterate up to 50 million records. Choose a scope size that balances limits and speed (200 is a common start, smaller if each record triggers callouts or heavy logic). Implement Database.Stateful only when you need to carry counters across chunks, and send a summary email or platform event in finish().

Scheduler (cron)
   └─ Database.executeBatch(new NightlyUpdateBatch(), 200)
         ├─ start():  QueryLocator of records to process
         ├─ execute(): process one chunk, catch per-record errors
         └─ finish(): log results, chain next job if needed

Also mention error handling with Database.update(records, false) so one bad record does not roll back the chunk, and monitoring through the Apex Jobs page.

9. How do you make a callout when a record is saved, given that triggers cannot make callouts directly?

Callouts are not allowed in the same synchronous trigger context after DML, so hand the work to an asynchronous job. The trigger enqueues a Queueable (implementing Database.AllowsCallouts) and returns. Store the credentials in a Named Credential, never in code, and persist a status field so failures can be retried.

Record saved ─▶ after trigger ─▶ enqueue Queueable
                                      │
                                      ▼
                         callout via Named Credential
                           ├─ 2xx: mark Synced
                           └─ error: mark Failed + retry job
10. Platform Events, Change Data Capture, Outbound Messages and REST callouts: when do you use each?

Use Platform Events for custom, business-level messages you publish and subscribe to (Apex, Flow, LWC, external systems). Use Change Data Capture to broadcast record create, update, delete and undelete changes without writing publish code. Use a REST callout when you need a synchronous request and response. Outbound Messages are older, declarative and SOAP-based, so rarely a first choice now.

Need to react to data changes?     ─▶ Change Data Capture
Need custom business events?       ─▶ Platform Events
Need an immediate answer back?     ─▶ REST callout (Named Credential)
Need decoupling and replay?        ─▶ Platform Events / CDC (replay Id)
11. An external ERP must load 2 million orders into Salesforce every night. What is your architecture?

Do not push 2 million rows through standard REST one at a time. Have the ERP use Bulk API 2.0 to upsert into Salesforce on an External Id, so reruns are idempotent. Process in parallel where possible, then run a post-load Batch job for derived calculations. Monitor with job status and a failed-records file that is reprocessed.

ERP ─▶ Bulk API 2.0 upsert (External Id)
        ├─ success file ─▶ audit
        └─ failure file ─▶ fix and re-upsert
Salesforce ─▶ post-load Batch (roll-ups, flags) ─▶ done event

Mention disabling non-essential automation for the load user, and checking record-locking risks when child records point to the same parent.

12. How do you test callouts, and why can you not make real callouts in tests?

Tests run without real network calls, so you provide a mock. Implement HttpCalloutMock to return a canned response, then register it with Test.setMock. Test both success and error responses (500, timeout, bad JSON) because most production bugs live in error paths.

@isTest
global class ErpMock implements HttpCalloutMock {
  global HTTPResponse respond(HTTPRequest r) {
    HttpResponse res = new HttpResponse();
    res.setStatusCode(200);
    res.setBody('{"status":"ok"}');
    return res;
  }
}
// in test: Test.setMock(HttpCalloutMock.class, new ErpMock());

Data, SOQL and Large Volumes

13. A report-style query on an object with 10 million records keeps timing out. What do you check?

Check selectivity first: filters on indexed fields (Id, Name, lookups, External Id, custom indexed fields) that return a small share of rows. Negative operators (!=, NOT IN), leading wildcards (LIKE ‘%x’) and formulas defeat indexes. Options: ask Salesforce Support for a custom index, add a selective filter, use skinny tables, archive old data to Big Objects or an external store, or move heavy analytics to Data Cloud or CRM Analytics.

14. Write SOQL to list accounts with their open opportunities, and accounts that have no opportunities at all.

Use a parent-to-child subquery for the first, and an anti semi-join for the second.

// Accounts with open opportunities
SELECT Name,
  (SELECT Name, Amount FROM Opportunities WHERE IsClosed = false)
FROM Account

// Accounts with NO opportunities
SELECT Id, Name FROM Account
WHERE Id NOT IN (SELECT AccountId FROM Opportunity)

Remember that a subquery returns a nested list, and each query counts against limits.

15. The same code throws “Too many SOQL queries: 101” only when users import data. What is the likely cause?

Interactive saves send one record, but imports and integrations send up to 200 per transaction. Code that queries inside a loop, or several triggers and flows each running their own queries, passes with one record and fails at scale. Reproduce with a 200-record test, bulkify, and consolidate automation per object.

16. Custom Metadata, Custom Settings or Custom Labels: how do you decide?

Use Custom Metadata for configuration that ships with deployments (routing rules, thresholds, feature flags): it is deployable and queryable without counting heavily against limits. Use Custom Settings for values that differ per user or profile or that need to change at runtime without deploying. Use Custom Labels for translatable text. A config-driven design keeps business rules out of code.

17. How do you design a roll-up from child to parent on a Lookup relationship, where roll-up summary fields are not available?

Options in order of preference: a record-triggered Flow with an aggregate query for simple cases, a trigger plus an aggregate SOQL for custom logic, or a managed or open-source roll-up tool. Recalculate with GROUP BY for the affected parents only (not a delta), so the value self-heals.

child insert/update/delete/undelete
   └─ collect parent Ids
        └─ SELECT ParentId, SUM(Amount) FROM Child GROUP BY ParentId
             └─ update parents (one DML)

Testing, Debugging and DevOps

18. Why is 75% code coverage not the goal, and what does a good test class look like?

Coverage is a deployment gate, not a quality measure. A good test creates its own data (a test data factory, @TestSetup for shared records), runs the logic between Test.startTest() and Test.stopTest(), tests bulk (200 records), positive, negative and permission cases, and asserts outcomes with System.Assert. Never use SeeAllData=true unless unavoidable.

Build your skills in Salesforce

Join the next live batch with an instructor. Small batches, real projects and a free demo class before you decide.

19. How do you test Batch and Queueable Apex?

Wrap the call in Test.startTest() and Test.stopTest(): the job runs synchronously when stopTest() executes, so you can then query and assert results. A test may only execute one Batch execute() chunk, so keep the test data under the scope size, and test chained jobs separately.

Test.startTest();
Database.executeBatch(new NightlyUpdateBatch(), 200);
Test.stopTest();
System.assertEquals(200, [SELECT COUNT() FROM Account
                          WHERE Processed__c = true]);
20. Design a CI/CD pipeline for a Salesforce team of ten developers.

Use Git as the source of truth with feature branches and pull requests. Each PR triggers automated validation: a scratch org or validation deploy, local Apex tests, and static analysis (for example PMD or Salesforce Code Analyzer). Merging promotes through sandboxes to production with a delta or package-based deploy.

Feature branch ─▶ Pull request
      │                  │
      │            [validate: tests + code scan]
      ▼                  ▼
   Scratch org     Merge to main ─▶ Integration sandbox
                                      ─▶ UAT sandbox
                                      ─▶ Production (quick deploy)

Unlocked packages help modularise a large org, and a rollback plan should exist before every release.

21. Users report “UNABLE_TO_LOCK_ROW” intermittently. How do you diagnose and prevent it?

Two transactions are updating the same record or the same parent at once, often child records loaded in parallel under one parent Account, or a long-running trigger holding a lock. Find the pattern in debug logs and the Apex Jobs page, then reduce contention: sort and group data by parent, lower the batch concurrency or scope, use FOR UPDATE only where truly needed, and add retry logic for transient failures.

Lightning Web Components Architecture

22. Explain the LWC lifecycle and the order hooks run in a parent and child.

Hooks run in this order: constructor, connectedCallback, render, then renderedCallback. The parent constructs and connects first, then children, and renderedCallback runs child first, then parent.

Parent constructor
Parent connectedCallback
  Child constructor
  Child connectedCallback
  Child renderedCallback   ◀ child finishes first
Parent renderedCallback

Use connectedCallback for setup and data fetch, renderedCallback sparingly (it runs on every render, so guard against loops), and disconnectedCallback to clean up listeners and subscriptions.

23. Which communication pattern do you use between components, and how do you pick?

Parent to child: public @api properties and methods. Child to parent: a CustomEvent. Between unrelated components on the same page or across Aura, LWC and Visualforce: Lightning Message Service (LMS) with a message channel.

parent ──@api property──▶ child
parent ◀──CustomEvent──── child
cart-icon ◀──LMS channel──▶ product-list   (unrelated components)

Example: a product list that must update a cart badge elsewhere on the page. They are not parent and child, so publish an LMS message when an item is added, and let the badge subscribe.

24. When do you use @wire and when imperative Apex calls?

Use @wire for reading data that should load automatically and re-run when reactive parameters change; it supports caching and works with refreshApex. Use imperative calls for user-triggered actions, DML, non-cacheable methods, or when you need to control timing and error handling. Only methods annotated cacheable=true can be wired, and those cannot do DML.

@wire(getContacts, { accountId: '$recordId' }) contacts;
async handleSave() {
  await saveContact({ contact: this.draft }); // imperative
  await refreshApex(this.wiredResult);
}
25. Lightning Data Service or custom Apex: how do you decide?

Start with LDS (lightning-record-form, lightning-record-edit-form, getRecord and the uiRecordApi). It handles CRUD, FLS and sharing, caches records and keeps components on the page in sync with no Apex. Move to Apex when you need complex queries, aggregates, multi-object transactions or logic that LDS cannot express, and then enforce security yourself with WITH USER_MODE.

26. Design a reusable, configuration-driven data table component for multiple objects.

Make the component generic: parent supplies the object, field set or column config, filters and page size through @api properties. Server side, one Apex controller builds a dynamic SOQL query from validated field names, applies WITH USER_MODE, and returns a page of data with total count. Client side, handle sorting, infinite loading or pagination, and inline edit that saves through LDS or one bulk Apex call.

<c-smart-table object-api-name="Case"
   column-config={cols} page-size="50">
        │ @api config
        ▼
  Apex controller ─ validates fields ─ dynamic SOQL (USER_MODE)
        │
        ▼
  rows + totalCount ─▶ lightning-datatable

Key trade-off: flexibility versus injection and security risk, which is why field names must be validated against the schema.

27. A Lightning page with several LWCs is slow. How do you find and fix it?

Measure first with the browser performance tools and the Lightning Usage and Page Performance (EPT) data. Common fixes: reduce the number of components and wires per page, make Apex cacheable, load heavy sections lazily (render only when needed using lwc:if), paginate large lists, debounce search inputs, avoid re-creating large arrays in getters, and cache data with Platform Cache or client-side stores.

28. What changed in modern LWC templates, such as lwc:if and template expressions?

The old if:true and if:false directives have been replaced by lwc:if, lwc:elseif and lwc:else, which are clearer and cover branching. Recent releases, including Winter ’27, also bring complex template expressions so simple logic can sit in the template rather than in getter methods. Check the release notes for the API version needed and keep heavy logic in JavaScript.

<template lwc:if={isLoading}><lightning-spinner></lightning-spinner></template>
<template lwc:elseif={hasError}><c-error-panel></c-error-panel></template>
<template lwc:else><c-results items={items}></c-results></template>
29. How is security handled in LWC, and what is Lightning Web Security?

Lightning Web Security (LWS) is the modern client-side security architecture that isolates component namespaces and replaced Lightning Locker. It lets components use standard web APIs and third-party libraries more safely. You still own server-side security: enforce CRUD and FLS in Apex, avoid exposing sensitive fields to guest users in Experience Cloud, never build SOQL from raw user input (use bind variables), and avoid innerHTML with unsanitised data.

Scenario and Use-Case Questions

30. Users need a multi-step quote wizard on the Opportunity page. Flow, LWC or both?

Use a Screen Flow when the steps are mostly forms and logic that admins will maintain. Build an LWC when you need rich UI, heavy client-side behaviour or performance. A common hybrid is a Screen Flow that embeds a custom LWC for the hard screen and calls an invocable Apex action for the heavy logic.

Opportunity page
   └─ Screen Flow (steps, branching, admin-maintained)
         ├─ custom LWC screen component (product picker)
         └─ Invocable Apex (pricing engine)
              └─ creates Quote + line items
31. Build a live dashboard that updates the moment a Case is created, without page refresh. How?

Subscribe to a stream from the browser. Use Change Data Capture on Case, or a Platform Event your trigger publishes, and subscribe in the LWC with the lightning/empApi module. Update the tracked data on each event, unsubscribe in disconnectedCallback, and use replay Id handling for missed events.

Case created ─▶ CDC / Platform Event
                       │
              lightning/empApi subscribe
                       ▼
        LWC updates list and counters (no refresh)
32. Users upload a CSV of 50,000 rows through a custom LWC. How do you design it?

Parse the file in the browser, validate headers and basic types, then send the rows in chunks (a few hundred per call) to Apex, or upload the file and let a Queueable or Batch process it. Insert with Database.insert(rows, false), collect row-level errors, and report progress and an error file back through a Platform Event.

LWC: read CSV ─▶ validate ─▶ chunk
        │
        ▼
Apex/Queueable: upsert on External Id (allOrNone=false)
        │
        ├─ publish progress event ─▶ LWC progress bar
        └─ error rows ─▶ downloadable error file
33. The same business rule is needed in Apex triggers, Flow, an LWC and a REST API. How do you avoid duplicating it?

Put the rule in one service class (a service layer) and expose it through thin adapters. Triggers call the service directly, Flow uses an @InvocableMethod wrapper, LWC uses an @AuraEnabled wrapper, and the REST API uses an @RestResource wrapper. Changing the rule then happens in one place with one set of tests.

Trigger ──┐
Flow ─────┤
LWC ──────┼──▶ PricingService (rules + tests)
REST API ─┘
34. How do you decide between Flow and Apex for a new automation?

Default to Flow for straightforward, admin-maintainable logic on a single record or a small related set. Choose Apex for complex algorithms, large data volumes, advanced error handling, callouts needing retries, or logic that must be unit tested heavily. Avoid mixing many automations on one object: pick one owner per object and event, and document it.

Simple, admin-owned?              ─▶ Flow
Complex logic / big volume?       ─▶ Apex
Both on the same object + event?  ─▶ consolidate, one owner
35. An integration is creating duplicate Accounts. How do you stop it for good?

Make the load idempotent: give the external system a unique External Id field and use upsert on it, so retries update instead of insert. Add Duplicate and Matching Rules for user-entered data, and a unique constraint where possible. Clean existing duplicates with merge logic, and make the integration handle timeouts by retrying with the same External Id.

36. How do you expose Apex to an Agentforce agent as an action?

Write an @InvocableMethod with clear input and output classes and descriptive labels, because the agent’s reasoning relies on those descriptions to choose the action. Keep each action small and focused, enforce permissions inside it, and test with the agent’s Testing Center. See our 40 Agentforce interview questions for the agent side of this design.

Build your Salesforce Developer skills

Test yourself with the Salesforce Developer Apex practice test and the LWC practice test. Moving toward architecture? Read our 185 Salesforce Admin interview questions and the 40 Agentforce questions, or join the Salesforce Admin + Developer Training.

Related question sets

Prepare with a mentor. Try a class before you decide.WhatsAppBook a free demo
Share this set

Leave your thought here

Your email address will not be published. Required fields are marked *

Alert: You are not allowed to copy content or view source !!