Back to interview questions

100+ Salesforce Developer Interview Questions and Answers

100+ Salesforce Developer Interview Questions and Answers

Explore 120 Salesforce Developer interview questions and answers on Apex, SOQL, triggers, security, LWC, integrations, testing, and deployment.

Explore 120 Salesforce Developer interview questions and answers on Apex, SOQL, triggers, security, LWC, integrations, testing, and deployment.

By

Team Sherlock.sh

Add Sherlock as a preferred source on Google

Salesforce Developer interviews should reveal whether a candidate can turn a business process into secure, maintainable platform behavior. Writing Apex syntax is only one part of that work. Recruiters need to assess data modeling, bulk-safe automation, query design, permissions, Lightning Web Components, integrations, and the judgment required when a transaction or asynchronous job fails.

This guide to 100+ Salesforce Developer Interview Questions and Answers contains 120 questions across beginner, intermediate, and experienced levels. It starts with platform and language fundamentals, then develops transaction design, explicit security, client data handling, and production operations. Use the scenarios to distinguish a feature that works for one administrator from a dependable implementation for real users and realistic data volumes.

How can recruiters assess genuine Salesforce development skills when interview assistance can conceal gaps in bulk processing or permission-aware design?

Ask the candidate to repair a query-in-loop trigger, explain a restricted user’s failed request, or recover an integration after an uncertain write. Change the execution context and ask what evidence they would inspect before proposing a fix.

Sherlock AI helps hiring teams assess signals of potential AI cheating, deepfakes, impersonation, and unauthorized assistance during interviews.

Consider those signals alongside practical work and the candidate’s explanation, rather than treating them as conclusive proof of misconduct. Clear scenarios and explicit platform assumptions help candidates demonstrate reasoning instead of memorizing isolated limit values.

Salesforce Developer Interview Questions

The complete question bank appears first so interviewers can choose prompts without revealing the answers. State the relevant Salesforce products, API versions, user permissions, and synchronous or asynchronous entry point before discussing detailed behavior.

Salesforce Developer Interview Questions for Beginners

Start with the platform data model, Apex collections and queries, native automation, security layers, and LWC foundations. Ask what each feature guarantees and what remains the developer’s responsibility.

  1. What does a Salesforce developer build on the platform?

  2. When should you choose declarative automation rather than Apex?

  3. How do standard objects and custom objects differ?

  4. What is the difference between a field label and an API name?

  5. How do lookup and master-detail relationships differ?

  6. What is a junction object used for?

  7. When should you use a formula field instead of stored data?

  8. What does a roll-up summary field provide?

  9. How do record types differ from profiles and permission sets?

  10. What is Apex, and where does it execute?

  11. What is an sObject in Apex?

  12. How do List, Set, and Map serve different purposes in Apex?

  13. Why are maps commonly keyed by record ID?

  14. How should null values be handled in Apex?

  15. What does SOQL do?

  16. How is SOSL different from SOQL?

  17. How do relationship queries work in SOQL?

  18. Why should Apex queries use bind variables?

  19. What is DML in Apex?

  20. How does upsert differ from insert and update?

  21. What is an Apex transaction?

  22. Why does Salesforce impose governor limits?

  23. What does bulkification mean?

  24. What is an Apex trigger?

  25. How do before and after triggers differ?

  26. What do Trigger.new and Trigger.old represent?

  27. Why should queries and DML usually be kept out of per-record loops?

  28. How can addError be used in record automation?

  29. What are the main layers of Salesforce data access?

  30. Does with sharing enforce CRUD and field-level security?

  31. How do permission sets help manage application access?

  32. What is Lightning Web Components?

  33. When should an LWC use Lightning Data Service instead of Apex?

  34. What does the LWC wire service provide?

  35. When should Apex be called imperatively from an LWC?

  36. What does @AuraEnabled(cacheable=true) require?

  37. How should data flow between parent and child LWCs?

  38. What is asynchronous Apex used for?

  39. What should an Apex unit test demonstrate?

  40. How would you prepare a small Salesforce feature for review?

Salesforce Developer Interview Questions for Intermediate

Explore transaction handling, query selectivity, versioned security, asynchronous work, client data refresh, and testing. These prompts test whether a candidate can connect a local code choice to the full execution path.

  1. How would you organize trigger logic for maintainability?

  2. How do you detect a meaningful field transition in an update trigger?

  3. Why is a single static Boolean a fragile recursion guard?

  4. How should a developer reason about Salesforce order of execution?

  5. What is the difference between all-or-none DML and partial-success DML?

  6. When should you use a savepoint and rollback?

  7. What is mixed DML, and how should it influence design?

  8. How do synchronous and asynchronous limits differ?

  9. How would you investigate an Apex CPU-limit failure?

  10. How does a SOQL for loop help with large result processing?

  11. What makes a SOQL filter selective?

  12. How do aggregate queries differ from retrieving every record?

  13. How can dynamic SOQL be built safely?

  14. Why should pagination use a deterministic ordering?

  15. How have Apex security defaults changed across API versions?

  16. What does WITH USER_MODE do in an Apex query?

  17. When is stripInaccessible useful?

  18. How do with sharing, without sharing, and inherited sharing express intent?

  19. How would you test that Apex respects restricted users?

  20. How should an @AuraEnabled method validate its inputs?

  21. How does Queueable Apex differ from a future method?

  22. When is Batch Apex appropriate?

  23. What does Database.Stateful preserve in Batch Apex?

  24. What should Scheduled Apex be responsible for?

  25. How should callouts be coordinated with database changes?

  26. What do Named Credentials and External Credentials separate?

  27. How do named-principal and per-user integration identities differ?

  28. How should an LWC refresh data after an Apex mutation?

  29. How do reactive wire parameters handle undefined and null differently?

  30. Why should an LWC avoid mutating wired or parent-owned objects?

  31. How should an LWC handle pending requests and errors?

  32. When should Lightning Message Service be considered?

  33. How does Lightning Web Security affect component design?

  34. What should Test.startTest and Test.stopTest be used for?

  35. How do @TestSetup and test-data factories help?

  36. How should Apex HTTP callouts be tested?

  37. Why is code coverage not enough for deployment confidence?

  38. How do custom metadata and custom settings fit configuration needs?

  39. What should a Salesforce deployment include besides code?

  40. How would you diagnose a test that passes in one org but fails in another?

Salesforce Developer Interview Questions for Experienced

Use these scenarios to assess architecture, diagnosis, recovery, permission boundaries, and deployment judgment. Strong answers identify assumptions and failure cases before expanding privileges or adding more infrastructure.

  1. How would you design automation for an object with many existing flows and triggers?

  2. How would you prevent repeated side effects across separate transactions?

  3. How would you recover from a partial-success data-processing job?

  4. How would you investigate record-locking failures?

  5. What risks arise from data skew in Salesforce?

  6. How would you optimize a query that slows as an org grows?

  7. How would you design a large-volume synchronization integration?

  8. When would you choose events instead of a synchronous integration call?

  9. How do Platform Events and Change Data Capture serve different purposes?

  10. What does publish-after-commit behavior change for events?

  11. How would you handle an API timeout after Salesforce may have committed a write?

  12. How would you choose an authentication pattern for a Salesforce integration?

  13. How would you secure a custom Apex REST endpoint?

  14. How would you evaluate a proposed system-mode exception?

  15. How would you migrate Apex classes to a newer API version safely?

  16. How would you prevent data leakage through a read-only Apex response?

  17. How would you design permission-sensitive caching?

  18. How would you handle a large editable grid in an LWC?

  19. How can stale responses corrupt an LWC search experience?

  20. What should an LWC accessibility review include?

  21. How would you choose between LDS, GraphQL, and custom Apex for a screen?

  22. How would you design an asynchronous retry policy?

  23. What are the risks of unbounded Queueable chaining?

  24. How would you monitor asynchronous processing operationally?

  25. How would you select a Batch Apex scope size?

  26. How would you test a multi-stage asynchronous workflow?

  27. How would you make test data realistic without relying on production records?

  28. What should a bulk trigger test assert beyond record count?

  29. How would you plan a deployment that changes data and metadata together?

  30. How would you manage environment-specific configuration?

  31. How would you diagnose a failure that occurs only for one permission persona?

  32. How would you instrument Apex without leaking sensitive data?

  33. How would you review a Salesforce integration's field ownership rules?

  34. How would you prevent schema changes from silently breaking consumers?

  35. What should a technical review of a metadata-driven Apex framework examine?

  36. How would you decide whether logic belongs inside Salesforce or externally?

  37. How would you handle a production automation incident safely?

  38. How would you assess an Apex performance improvement claim?

  39. How would you design a senior Salesforce Developer interview exercise?

  40. What does a dependable Salesforce development operating model include?

Salesforce Developer Interview Questions and Answers

The answers follow the question bank’s exact wording and numbering. Apex examples target APIs supporting explicit user-mode operations; class fixture metadata uses API 67.0. Current security guidance distinguishes API 67.0 and later defaults from API 66.0 and earlier behavior, so declarations and operation modes are explicit where relevant. Salesforce features, limits, licenses, and supported objects depend on the execution context and product. All Apex, SOQL, and LWC examples received static review only; no Salesforce org was accessed and no platform code was compiled or executed. A separate plain JavaScript helper has a local fixture, which does not establish Salesforce runtime behavior.

Salesforce Developer Interview Questions and Answers for Beginners

These answers connect platform terminology to practical implementation choices. Small examples emphasize intent and state their execution assumptions.

1. What does a Salesforce developer build on the platform?

A Salesforce developer implements business capabilities using the platform's data model, automation, Apex, user-interface technologies, and integration APIs. The job is broader than writing triggers: a good solution respects permissions, transaction boundaries, operational limits, and maintainability. I would first understand the process and available native features, then choose code where it adds clear value. For example, a record-entry experience may use standard components while a complex transactional operation needs Apex. The design should explain why each layer exists and how failures are handled.

2. When should you choose declarative automation rather than Apex?

Use declarative features when they express the requirement clearly and can be maintained and tested within the organization's operating model. Apex is appropriate when complexity, transaction control, scale, or reusable logic requires it. The decision is not a contest between administrators and developers. I would assess the entire automation path, including existing flows and triggers, and avoid implementing the same rule twice. Prototype difficult cases, establish ownership, and compare the debugging and deployment costs before choosing the simplest suitable mechanism.

3. How do standard objects and custom objects differ?

Standard objects model platform-provided concepts such as Account and Contact, while custom objects model organization-specific data. Both participate in Salesforce's metadata, permissions, and relationship model, but their capabilities and constraints are not necessarily identical. I would use an existing object when its meaning genuinely matches the requirement rather than force unrelated data into it to avoid configuration. Custom object API names commonly include a suffix, and managed-package namespaces can affect names. Integrations should use documented API identifiers rather than user-visible labels.

4. What is the difference between a field label and an API name?

A label is the user-facing name presented in the interface, while an API name identifies metadata in code, queries, and integrations. Labels can be translated or changed without necessarily changing the API identifier. I would reference stable API names and use schema-aware tools when discovering fields rather than infer identifiers from visible text. Namespace prefixes and relationship names also matter. A successful label rename does not prove every integration is unaffected, because external systems may have incorrectly depended on display names or exported headings.

5. How do lookup and master-detail relationships differ?

A lookup connects records with looser ownership and lifecycle coupling, while master-detail makes the detail depend more strongly on the master, including sharing and deletion behavior. Master-detail also enables native roll-up summaries in supported circumstances. I would choose based on the business lifecycle, required independence, and reporting needs rather than merely wanting a related list. Conversion and optionality have constraints, so inspect the actual metadata and existing data before changing relationship type. A relationship decision affects security and operations as well as navigation.

6. What is a junction object used for?

A junction object represents an association between records, often enabling a many-to-many relationship. For example, an enrollment can connect a learner and a course while storing association-specific information such as enrollment status. Salesforce commonly models this using two master-detail relationships where the lifecycle fits, but other relationship designs may be appropriate. I would define uniqueness, ownership, deletion behavior, and access explicitly. The junction should represent a real business relationship, not merely compensate for an unclear data model or duplicate lists of identifiers.

7. When should you use a formula field instead of stored data?

A formula field derives a value from a supported expression and is useful when the value should reflect current source data without custom synchronization logic. A stored field is appropriate when a historical snapshot, external value, or independently managed state is required. I would consider reporting, performance, relationship dependencies, and formula limitations before choosing. A formula showing today's calculated result is not automatically evidence of what the value was when an earlier decision occurred, so audit and historical requirements need separate design.

8. What does a roll-up summary field provide?

A roll-up summary calculates a supported aggregate over related detail records in an appropriate master-detail relationship. It can avoid custom code for requirements such as a count or sum, subject to the field and filter capabilities. I would verify the relationship and desired aggregation before assuming any lookup relationship supports the same native feature. Roll-ups can also participate in additional automation and locking behavior. Their convenience does not remove the need to test the full save path and understand how parent updates affect other logic.

9. How do record types differ from profiles and permission sets?

Record types support variations such as business processes, available picklist values, and page-layout assignments. Profiles and permission sets concern user capabilities and access configuration. They interact in the user experience but are not interchangeable security mechanisms. I would not treat hiding a layout field or assigning a record type as proof that an API user cannot access data. Define object, field, and record permissions separately, then test the appropriate users and interfaces. Record-type choices should also avoid unnecessary complexity in shared automation.

10. What is Apex, and where does it execute?

Apex is Salesforce's server-side language for implementing platform logic, including triggers, services, and asynchronous jobs. It executes within Salesforce-managed contexts and resource limits rather than a developer-controlled application server. Its syntax resembles familiar object-oriented languages, but transactions, security, database operations, and deployment are platform-specific. I would identify the entry point and API version before predicting behavior. A code fragment that looks like Java is not evidence that Java libraries, threading assumptions, or local filesystem access apply to Apex.

11. What is an sObject in Apex?

An sObject represents a Salesforce record, with fields corresponding to an object type. Code can use a specific type such as Account for stronger compile-time checking or a generic sObject when building metadata-driven behavior. An instance in memory is not automatically a committed database record. I would distinguish constructing or changing an sObject from performing DML. Also, a queried instance contains the selected fields, so attempting to use an unqueried field can fail rather than transparently fetch missing data on demand.

12. How do List, Set, and Map serve different purposes in Apex?

A List is an ordered collection that can contain duplicates, a Set represents unique values, and a Map associates keys with values. They are fundamental to bulk-safe processing: collect identifiers into a set, query related records once, and build a map for efficient matching. I would choose keys whose equality matches the business relationship and avoid relying on unordered iteration for business ordering. Collection choice improves clarity, but it does not remove limits on heap size, query results, or total processing work.

Code language: Apex. Apex anonymous-block illustration; no database operations.

List<String> names = new List<String>{'Ada', 'Bo', 'Ada'};
Set<String> uniqueNames = new Set<String>(names);
Map<String, Integer> counts = new Map<String, Integer>();
for (String name : names) {
    Integer previous = counts.containsKey(name) ? counts.get(name) : 0;
    counts.put(name, previous + 1);
}
System.assertEquals(3, names.size());
System.assertEquals(2, uniqueNames.size());
System.assertEquals(2, counts.get('Ada'));
List<String> names = new List<String>{'Ada', 'Bo', 'Ada'};
Set<String> uniqueNames = new Set<String>(names);
Map<String, Integer> counts = new Map<String, Integer>();
for (String name : names) {
    Integer previous = counts.containsKey(name) ? counts.get(name) : 0;
    counts.put(name, previous + 1);
}
System.assertEquals(3, names.size());
System.assertEquals(2, uniqueNames.size());
System.assertEquals(2, counts.get('Ada'));
List<String> names = new List<String>{'Ada', 'Bo', 'Ada'};
Set<String> uniqueNames = new Set<String>(names);
Map<String, Integer> counts = new Map<String, Integer>();
for (String name : names) {
    Integer previous = counts.containsKey(name) ? counts.get(name) : 0;
    counts.put(name, previous + 1);
}
System.assertEquals(3, names.size());
System.assertEquals(2, uniqueNames.size());
System.assertEquals(2, counts.get('Ada'));

Expected behavior: The list retains three entries, the set has two distinct names, and Ada has a count of two.

13. Why are maps commonly keyed by record ID?

A record ID provides a convenient way to associate a queried record with another record that references it. A Map<Id, Account>, for example, avoids repeatedly scanning a list of accounts for each contact. I would still handle missing keys because the referenced record may be inaccessible, deleted, or outside the query's scope. New records do not always have IDs before insertion. A map also cannot represent multiple values for the same key unless its value is itself a collection or another suitable structure.

14. How should null values be handled in Apex?

Treat null as an explicit possible state and decide whether it means missing input, unavailable data, or an invalid condition. Check a value before dereferencing it and distinguish an empty collection from a null collection reference. I would avoid broad exception handling as a substitute for a clear contract. For example, a missing map lookup should lead to an intentional fallback or validation error. Tests should cover absent optional values and unexpected missing relationships, not only fully populated administrator-created records.

15. What does SOQL do?

SOQL retrieves Salesforce records using the platform's object and relationship model. It supports selection, filtering, ordering, relationship queries, and supported aggregation, but it is not general SQL with arbitrary joins and updates. I would select only needed fields and restrict the population according to the business requirement and security context. A syntactically valid query can still be inefficient or expose the wrong data. Explain where it runs, which access mode applies, and how the result size is bounded before treating it as production-ready.

Code language: SOQL. SOQL query illustration. The limit is an application example, not a platform limit. In Apex, set an explicit access mode for permission-sensitive use.

SELECT Id, Name
FROM Account
WHERE Name LIKE 'Acme%'
ORDER BY Name, Id
LIMIT 50
SELECT Id, Name
FROM Account
WHERE Name LIKE 'Acme%'
ORDER BY Name, Id
LIMIT 50
SELECT Id, Name
FROM Account
WHERE Name LIKE 'Acme%'
ORDER BY Name, Id
LIMIT 50

Expected behavior: At most 50 matching accounts are returned in a defined order, subject to the execution context.

16. How is SOSL different from SOQL?

SOSL is designed for text search across supported fields and potentially multiple object types, while SOQL queries records with a structured object-specific condition. The right choice depends on whether the requirement is search or precise retrieval. I would explain the returned structure, supported search scope, and freshness expectations rather than claim that either language always finds the same records. Search indexing and query execution have different characteristics. After finding candidates, additional retrieval and authorization checks may be needed for the application's actual workflow.

17. How do relationship queries work in SOQL?

Child-to-parent traversal selects fields through a relationship, while a parent-to-child subquery retrieves related child records using the relationship's API name. These names are not always the visible object labels. I would inspect schema metadata and select only necessary child data, because a relationship query can still produce a large result and consume resources. Supported traversal depth and behavior depend on the API and context. Do not assume SOQL permits every join expression or recursive traversal available in a general relational query language.

Code language: SOQL. SOQL child-to-parent example; record visibility and field access depend on the execution path. The broad nonnull filter is educational, not a selectivity guarantee.

SELECT Id, LastName, Account.Name
FROM Contact
WHERE AccountId != null
ORDER BY LastName, Id
LIMIT 50
SELECT Id, LastName, Account.Name
FROM Contact
WHERE AccountId != null
ORDER BY LastName, Id
LIMIT 50
SELECT Id, LastName, Account.Name
FROM Contact
WHERE AccountId != null
ORDER BY LastName, Id
LIMIT 50

Expected behavior: The query projects contact fields and the related account name.

18. Why should Apex queries use bind variables?

Bind variables separate supported query values from the query text and make code easier to read and less vulnerable to injection through those values. For example, an ID set can be bound to an IN condition instead of concatenating a comma-separated string. I would still validate dynamically selected object names, fields, and sort directions, because binding values does not authorize arbitrary query structure. Query security also includes the selected population and execution mode, not merely protecting quote characters in a search term.

Code language: Apex. Apex class. Callers must bound the ID collection; user-mode field or object permission failures must be handled by the calling workflow.

public with sharing class AccountSelector {
    public static List<Account> findByIds(Set<Id> accountIds) {
        if (accountIds == null || accountIds.isEmpty()) {
            return new List<Account>();
        }
        return [
            SELECT Id, Name
            FROM Account
            WHERE Id IN :accountIds
            WITH USER_MODE
            ORDER BY Name, Id
        ];
    }
}
public with sharing class AccountSelector {
    public static List<Account> findByIds(Set<Id> accountIds) {
        if (accountIds == null || accountIds.isEmpty()) {
            return new List<Account>();
        }
        return [
            SELECT Id, Name
            FROM Account
            WHERE Id IN :accountIds
            WITH USER_MODE
            ORDER BY Name, Id
        ];
    }
}
public with sharing class AccountSelector {
    public static List<Account> findByIds(Set<Id> accountIds) {
        if (accountIds == null || accountIds.isEmpty()) {
            return new List<Account>();
        }
        return [
            SELECT Id, Name
            FROM Account
            WHERE Id IN :accountIds
            WITH USER_MODE
            ORDER BY Name, Id
        ];
    }
}

Expected behavior: Only requested visible accounts are selected; absent input returns an empty list.

19. What is DML in Apex?

DML performs record operations such as insert, update, delete, undelete, and upsert. Changing an sObject in memory does not persist it until an appropriate database operation occurs, except for supported before-trigger changes to the records being saved. DML can invoke validation and other automation, so its effect is broader than one line of code. I would process collections where appropriate, make the access mode deliberate, and handle errors according to the transaction's business contract rather than assume every attempted record change succeeds.

20. How does upsert differ from insert and update?

Insert creates records, update modifies identified existing records, and upsert chooses between creation and update using a supported matching key, such as an ID or a specified external ID field. I would define the external key's uniqueness and ownership rather than assume upsert alone prevents every duplicate. Ambiguous matches or concurrent requests can still require careful handling. Integrations should retain stable correlation identifiers and inspect per-record outcomes so retries do not silently create inconsistent records or overwrite fields owned by another system.

21. What is an Apex transaction?

A transaction is a unit of platform work with a shared execution context and commit or rollback behavior. It can include Apex, validation, flows, triggers, and other operations participating in the same save path. An unhandled failure can roll back database changes in that transaction. I would not equate a method call with a separate transaction: calling another class usually continues within the existing context. Asynchronous execution introduces additional transaction boundaries, so the original operation and later work need an explicit consistency and failure model.

22. Why does Salesforce impose governor limits?

Salesforce shares infrastructure among tenants, so governor limits constrain resource consumption and help protect overall service behavior. Limits cover different dimensions, including queries, DML, CPU, heap, and asynchronous activity, with values and scopes depending on context and features. I would design for bounded work instead of memorizing one universal number. Use the applicable current documentation and Limits APIs for diagnosis. Moving inefficient code to another class does not create a fresh allowance when it still runs in the same transaction.

23. What does bulkification mean?

Bulkification means designing logic to handle all records in a transaction efficiently and correctly, rather than assuming one record arrives at a time. Typical patterns collect keys, query related data once, use maps for matching, and perform collection-based DML outside per-record loops. I would test both multiple records and realistic automation interactions. Bulk-safe code must also control result volume, CPU, and heap; removing a query from a loop is necessary in many cases but not sufficient proof that the complete design scales.

24. What is an Apex trigger?

A trigger runs in response to supported record events such as insert, update, delete, or undelete. It can inspect context records and enforce or coordinate platform logic around the save operation. I would keep the trigger entry point concise and place substantial reusable behavior in appropriately designed classes. A trigger is not isolated from flows, validation, and other automation. Its correctness depends on understanding event timing, bulk execution, security expectations, and the consequences of additional DML that may invoke the save process again.

25. How do before and after triggers differ?

Before triggers are useful for validating or changing field values on the records being saved before persistence. After triggers run after the relevant record values and IDs are available, and commonly coordinate related-record work; their context records are not directly editable. I would avoid performing DML on the same records merely to persist a before-trigger field change. The choice depends on the data required and operation performed, and both paths need bulk handling. An after trigger does not mean the entire transaction has already committed.

Code language: Apex. Apex trigger illustration. Apply only if this default is an approved business rule; org automation and security context must be tested before deployment.

trigger AccountDefaultDescription on Account (before insert) {
    for (Account record : Trigger.new) {
        if (String.isBlank(record.Description)) {
            record.Description = 'New account awaiting review';
        }
    }
}
trigger AccountDefaultDescription on Account (before insert) {
    for (Account record : Trigger.new) {
        if (String.isBlank(record.Description)) {
            record.Description = 'New account awaiting review';
        }
    }
}
trigger AccountDefaultDescription on Account (before insert) {
    for (Account record : Trigger.new) {
        if (String.isBlank(record.Description)) {
            record.Description = 'New account awaiting review';
        }
    }
}

Expected behavior: The before-insert trigger supplies a description only when the incoming description is blank, without separate DML.

26. What do Trigger.new and Trigger.old represent?

Trigger.new contains new versions of records for supported events, while Trigger.old contains previous versions for supported update or delete contexts. Their availability and mutability depend on the trigger event. Maps such as Trigger.oldMap make it practical to compare a record with its previous state by ID. I would consult the context contract instead of accessing every variable unconditionally. A change comparison should also handle nulls and distinguish a meaningful business transition from a save that leaves the relevant value unchanged.

27. Why should queries and DML usually be kept out of per-record loops?

A query or DML operation executed for each record can consume transaction limits rapidly as batch size grows. Collecting identifiers and processing collections reduces repeated database calls and often makes relationships clearer. I would not replace the loop with one unbounded query that retrieves an entire object, however. The query should target the required population and return only needed fields. Review helper methods too, because a loop can hide repeated database operations behind a method name that looks harmless at the call site.

28. How can addError be used in record automation?

AddError attaches a validation error to an appropriate record or field in a supported context, preventing the affected save according to the operation's error-handling semantics. It is useful when a business rule requires a clear actionable message. I would test both ordinary UI saves and collection operations with their chosen all-or-none behavior. Avoid using a vague error to conceal an unrelated programming failure. The message should explain what the user can correct without exposing sensitive internal details or data they are not authorized to see.

29. What are the main layers of Salesforce data access?

Object permissions determine allowed operations, field-level security controls field access, and record-level sharing determines which records a user can access within those capabilities. Organization and authentication controls provide additional boundaries. I would assess these layers separately rather than assume a visible record proves every field is readable or writable. Page layouts are presentation, not a complete security control. Apex execution mode and sharing declarations can affect enforcement, with API-version differences, so the application's server-side path must be reviewed explicitly.

30. Does with sharing enforce CRUD and field-level security?

No. A sharing declaration addresses record-level sharing, while object and field permissions require the applicable database access mode or other explicit enforcement. Current defaults vary by API version, making unqualified statements about Apex security misleading. I would declare sharing intent and use explicit user-mode operations where the operation should respect the user's data permissions. Tests should cover a real restricted permission model rather than only an administrator. A class-level keyword alone is not a complete authorization design for every action the class exposes.

31. How do permission sets help manage application access?

Permission sets grant additional capabilities to users, and permission set groups can organize related grants. They help separate application needs from a large collection of profile variations, but effective access still depends on the full permission model and licensing constraints. I would define a minimal supported user persona and test it end to end. Adding broad permissions merely to resolve one Apex failure can hide an incorrect execution-mode assumption. Access to an Apex class is also distinct from permission to read or modify every object it touches.

32. What is Lightning Web Components?

Lightning Web Components is Salesforce's component programming model built around web standards, with platform-specific modules, templates, data services, and deployment metadata. A component commonly combines JavaScript, an HTML template, optional CSS, and configuration. I would distinguish standard browser concepts from Salesforce framework behavior, especially around data access and component boundaries. Building an attractive template is only part of the work: loading, error handling, accessibility, security, and refreshing data after changes all affect whether the component is reliable in a real application.

33. When should an LWC use Lightning Data Service instead of Apex?

Start with suitable base components or Lightning Data Service APIs when they can satisfy the data requirement, because they provide platform-aware caching and security behavior. Use Apex when supported data services do not meet the required operation, particularly for custom transactional logic. I would compare the exact objects and capabilities rather than assume every object is supported. Apex-returned data is not automatically managed by the same cache as LDS records, so choosing Apex also creates responsibilities for access enforcement, error handling, and refresh behavior.

34. What does the LWC wire service provide?

The wire service provisions a reactive stream of values based on a supported adapter and configuration. It is not simply an imperative function call that runs once when the component is constructed. Reactive parameters can cause new provisioning, and consumers should handle data and errors without assuming a fixed timing. I would treat provided objects as read-only and derive local presentation state safely. For wired Apex, the method must meet the cacheable requirements; writes belong in an appropriate imperative or other supported mutation path.

35. When should Apex be called imperatively from an LWC?

Use an imperative call when the component needs explicit control over invocation or when calling a method that changes data and cannot be cacheable. The JavaScript receives a promise and must handle success and failure. I would prevent confusing duplicate interactions, display useful pending feedback, and refresh relevant data through the correct mechanism after completion. An imperative call does not automatically synchronize all LDS consumers. The Apex method must also validate inputs and authorization rather than trust the browser to expose only permitted actions.

36. What does @AuraEnabled(cacheable=true) require?

It exposes an appropriate Apex method for supported client use while declaring that the operation can be cached. The method must retrieve data without changing it, and wired Apex requires this cacheable annotation. I would not place logging DML or hidden side effects inside a supposedly read-only method. Cache lifetime is managed by the platform and should not be treated as a fixed application guarantee. The caller needs a deliberate refresh strategy, and the server still needs correct sharing, object, and field access behavior.

37. How should data flow between parent and child LWCs?

Parents pass data down through public properties, and children notify parents about events rather than mutating parent-owned objects directly. This keeps ownership clear and avoids surprising updates across component boundaries. I would make a suitable local copy before changing received data and choose event detail that exposes only the intended contract. A shallow copy does not isolate every nested object. Event bubbling and composition should be intentional, because exposing an event beyond a component boundary makes it part of the component's public behavior.

38. What is asynchronous Apex used for?

Asynchronous Apex moves suitable work into later platform execution contexts, allowing the initiating user interaction to finish without waiting for that work. Queueable, Batch, Scheduled, and older future patterns serve different needs. It is not unlimited capacity or a guarantee of immediate execution, and failures occur outside the original transaction's simple success path. I would define monitoring, retry behavior, and user-visible status before choosing it. Some limits differ from synchronous contexts, but the exact mechanism and context still determine which rules apply.

39. What should an Apex unit test demonstrate?

It should demonstrate meaningful behavior with controlled data and assertions, including normal, boundary, bulk, and failure cases where relevant. Coverage is a deployment signal, not proof that the business rule is correct. I would create necessary test records and avoid depending on arbitrary production data. Security, automation interactions, and asynchronous behavior need their own focused scenarios. A test that merely invokes a method and reaches enough lines can pass even when the method returns the wrong records or silently ignores failed updates.

Code language: Apex. Apex class used by the following test; it performs no database work.

public with sharing class NameNormalizer {
    public static String normalize(String value) {
        return value == null ? null : value.trim();
    }
}
public with sharing class NameNormalizer {
    public static String normalize(String value) {
        return value == null ? null : value.trim();
    }
}
public with sharing class NameNormalizer {
    public static String normalize(String value) {
        return value == null ? null : value.trim();
    }
}

Expected behavior: The pure helper trims surrounding whitespace and preserves null.

Code language: Apex. Apex test class. These are expected results from static review, not an executed Apex test run.

@IsTest
private with sharing class NameNormalizerTest {
    @IsTest
    static void trimsAndPreservesNull() {
        System.assertEquals('Ada', NameNormalizer.normalize('  Ada  '));
        System.assertEquals('', NameNormalizer.normalize('   '));
        System.assertEquals(null, NameNormalizer.normalize(null));
    }
}
@IsTest
private with sharing class NameNormalizerTest {
    @IsTest
    static void trimsAndPreservesNull() {
        System.assertEquals('Ada', NameNormalizer.normalize('  Ada  '));
        System.assertEquals('', NameNormalizer.normalize('   '));
        System.assertEquals(null, NameNormalizer.normalize(null));
    }
}
@IsTest
private with sharing class NameNormalizerTest {
    @IsTest
    static void trimsAndPreservesNull() {
        System.assertEquals('Ada', NameNormalizer.normalize('  Ada  '));
        System.assertEquals('', NameNormalizer.normalize('   '));
        System.assertEquals(null, NameNormalizer.normalize(null));
    }
}

Expected behavior: All three assertions should pass for the helper as written.

40. How would you prepare a small Salesforce feature for review?

I would document the requirement, data and security assumptions, chosen automation path, and expected failure behavior. Then provide readable metadata and code changes with meaningful tests and a deployment plan for dependencies such as permissions. Demonstrate the feature as an intended ordinary user, not only an administrator. I would also identify what was not tested, such as external service behavior or production-scale data. A useful review package explains the operational consequences of the change rather than presenting code coverage as its only evidence.

Salesforce Developer Interview Questions and Answers for Intermediate

These answers examine how automation, permissions, limits, and client state interact. Verify the actual context before applying a familiar pattern.

41. How would you organize trigger logic for maintainability?

I would keep a clear trigger entry point and delegate cohesive operations to a handler or service layer, with explicit inputs and responsibilities. The goal is predictable orchestration, not a framework so elaborate that simple rules become hard to trace. Review existing automation on the object and define the order within code you control. Multiple separate triggers do not provide a reliable business sequencing strategy. Tests should cover the handler's behavior and the actual save path, since isolated helper tests can miss interactions with other automation.

42. How do you detect a meaningful field transition in an update trigger?

Compare the new value with the corresponding old value and apply the business condition explicitly. For example, react when a status changes into a target state rather than whenever a record already has that state. I would handle nulls, bulk records, and relevant insert behavior separately. This reduces unnecessary work and helps prevent repeated side effects, but it is not a complete idempotency design. Additional automation can update the record again, and external retries may produce another transaction with similar business intent.

Code language: Apex. Apex helper for an update context; callers provide nonnull collections. If case-only name changes matter, define and test the required case-sensitive comparison separately.

public with sharing class AccountChangeDetector {
    public static Set<Id> renamedIds(
        List<Account> currentRecords,
        Map<Id, Account> previousById
    ) {
        Set<Id> changed = new Set<Id>();
        for (Account current : currentRecords) {
            Account previous = previousById.get(current.Id);
            if (previous != null && current.Name != previous.Name) {
                changed.add(current.Id);
            }
        }
        return changed;
    }
}
public with sharing class AccountChangeDetector {
    public static Set<Id> renamedIds(
        List<Account> currentRecords,
        Map<Id, Account> previousById
    ) {
        Set<Id> changed = new Set<Id>();
        for (Account current : currentRecords) {
            Account previous = previousById.get(current.Id);
            if (previous != null && current.Name != previous.Name) {
                changed.add(current.Id);
            }
        }
        return changed;
    }
}
public with sharing class AccountChangeDetector {
    public static Set<Id> renamedIds(
        List<Account> currentRecords,
        Map<Id, Account> previousById
    ) {
        Set<Id> changed = new Set<Id>();
        for (Account current : currentRecords) {
            Account previous = previousById.get(current.Id);
            if (previous != null && current.Name != previous.Name) {
                changed.add(current.Id);
            }
        }
        return changed;
    }
}

Expected behavior: The result contains IDs whose names compare as changed under Apex string comparison semantics.

43. Why is a single static Boolean a fragile recursion guard?

A static flag can suppress legitimate later work in the same transaction, including additional records or distinct operations. It also does not persist across separate transactions or solve external retries. I would first design logic that acts only on meaningful state changes and converges on the intended result. Where a transaction-scoped guard is still needed, scope it to the operation and records, and consider exception paths. Tests should include bulk saves and repeated valid updates rather than prove only that one recursive loop stopped.

44. How should a developer reason about Salesforce order of execution?

Treat the save path as an interaction among validation, triggers, flows, and other platform operations, with details governed by current documentation and enabled features. I would trace the actual automation on the object instead of memorizing a simplified sequence and assuming it covers every case. Before-save and after-save work have different purposes, and some updates can cause further processing. Document which layer owns each rule, then test representative paths to prevent duplicate work, conflicting updates, and assumptions that a late-stage action means the transaction already committed.

45. What is the difference between all-or-none DML and partial-success DML?

All-or-none behavior treats the operation's records as one success requirement, while supported Database methods can return per-record outcomes when partial success is requested. I would inspect every result and associate failures with the correct input record. Partial success does not mean successful records are immune to a later transaction rollback. The business process must decide whether a partially completed batch is acceptable and how retries target only unresolved work. Silently ignoring SaveResult errors can create a false success report even when the method itself returns normally.

Code language: Apex. Apex DML illustration, not executed. It requires suitable permissions and org configuration; the missing Account name should fail, while the first record can also fail for other legitimate org rules. Logs intentionally omit record payloads.

List<Account> candidates = new List<Account>{
    new Account(Name = 'Example account'),
    new Account()
};
Database.SaveResult[] results = Database.insert(
    candidates, false, AccessLevel.USER_MODE
);
for (Integer index = 0; index < results.size(); index++) {
    if (results[index].isSuccess()) {
        System.debug('Succeeded at input index ' + index);
    } else {
        for (Database.Error problem : results[index].getErrors()) {
            System.debug('Failed at input index ' + index + ': ' +
                problem.getStatusCode());
        }
    }
}
List<Account> candidates = new List<Account>{
    new Account(Name = 'Example account'),
    new Account()
};
Database.SaveResult[] results = Database.insert(
    candidates, false, AccessLevel.USER_MODE
);
for (Integer index = 0; index < results.size(); index++) {
    if (results[index].isSuccess()) {
        System.debug('Succeeded at input index ' + index);
    } else {
        for (Database.Error problem : results[index].getErrors()) {
            System.debug('Failed at input index ' + index + ': ' +
                problem.getStatusCode());
        }
    }
}
List<Account> candidates = new List<Account>{
    new Account(Name = 'Example account'),
    new Account()
};
Database.SaveResult[] results = Database.insert(
    candidates, false, AccessLevel.USER_MODE
);
for (Integer index = 0; index < results.size(); index++) {
    if (results[index].isSuccess()) {
        System.debug('Succeeded at input index ' + index);
    } else {
        for (Database.Error problem : results[index].getErrors()) {
            System.debug('Failed at input index ' + index + ': ' +
                problem.getStatusCode());
        }
    }
}

Expected behavior: Each result is inspected and associated with its original input position.

46. When should you use a savepoint and rollback?

Use a savepoint when part of a transaction may need to be rolled back while the code handles a failure deliberately. It affects database state within that transaction, not arbitrary external side effects or every in-memory variable. I would define what work remains valid after rollback and avoid assuming resource limits are restored. Callout and savepoint interactions have version-specific rules that need verification. A broad try-catch with rollback is not automatically a recovery plan if the application cannot explain which operations succeeded and which must be retried.

47. What is mixed DML, and how should it influence design?

Mixed DML restrictions apply when certain setup-object changes and ordinary business-record changes are attempted within the same transaction. The exact objects and exceptions matter, so I would verify the relevant operation rather than label every User-related update prohibited. A common design separates the responsibilities across appropriate transaction boundaries, with an explicit consistency and failure model. Test-only techniques do not necessarily describe production behavior. Moving code into another method is insufficient if both operations still run in the same transaction.

48. How do synchronous and asynchronous limits differ?

Some asynchronous contexts have different per-transaction allowances, but the values and applicable limits depend on the mechanism. Scheduled Apex, Batch execution, Queueable work, and other paths should not be treated as one uniform 'async' budget. There are also organization-level and daily limits beyond a single transaction. I would identify the entry point, consult its current limits, and measure the constrained resource. Asynchronous processing can introduce queue delays and operational complexity, so it should not be used merely to conceal an inefficient synchronous design.

49. How would you investigate an Apex CPU-limit failure?

I would trace the complete transaction, including flows, triggers, repeated calculations, nested loops, and serialization work. Query-count improvements alone do not prove CPU efficiency. Compare realistic bulk input and data distributions, identify repeated operations, and use the relevant debug or profiling evidence without logging sensitive payloads. A governor-limit failure generally cannot be handled like an ordinary recoverable business exception. The fix should reduce or deliberately partition work, followed by tests of the actual entry path rather than only an isolated utility method.

50. How does a SOQL for loop help with large result processing?

A SOQL for loop retrieves records in an iteration-friendly manner that can reduce the need to retain an entire query result list in memory. It does not remove the transaction's query-row, CPU, or other limits, and accumulating every processed record in another collection can defeat the memory benefit. I would choose it when the operation can process a bounded query incrementally. Truly large workloads may need an appropriate asynchronous or API approach, with explicit batching, recovery, and access semantics.

51. What makes a SOQL filter selective?

A selective filter narrows the candidate population enough for the optimizer to consider an efficient access path, often involving a useful index. The result depends on data distribution, operators, indexes, and the complete query, not simply the presence of a WHERE clause. I would inspect current query-plan information and representative volumes instead of applying one fixed percentage universally. A filter that performs well in a small sandbox may become poor as data grows or values become concentrated, so monitoring and realistic testing matter.

52. How do aggregate queries differ from retrieving every record?

An aggregate query asks the platform to compute a supported summary, such as counts or totals grouped by a field, rather than sending every detail record to Apex for reduction. This can reduce application-side work, but aggregation still has limits and query-performance implications. I would select the exact grouping and null behavior needed and use clear aliases when reading AggregateResult values. A summary count does not prove that the correct records were included, so validate the filter population as well as the final number.

Code language: SOQL. SOQL aggregate illustration; query limits, access context, and population selectivity still apply. It is not an unbounded production reporting recipe.

SELECT AccountId, COUNT(Id) contactCount
FROM Contact
WHERE AccountId != null
GROUP BY

SELECT AccountId, COUNT(Id) contactCount
FROM Contact
WHERE AccountId != null
GROUP BY

SELECT AccountId, COUNT(Id) contactCount
FROM Contact
WHERE AccountId != null
GROUP BY

Expected behavior: The result summarizes contact counts by associated account instead of returning every contact.

53. How can dynamic SOQL be built safely?

Bind data values using supported facilities, and allowlist any structural choices such as object names, field names, and sort directions. Database.queryWithBinds can resolve named values from a map and accepts an explicit access level, which makes intent visible. I would not treat quote escaping as complete protection or allow a caller to supply arbitrary WHERE fragments. Authorization and result-size limits remain separate requirements. Tests should include unusual input, unsupported fields, and restricted users, not only a normal search string.

Code language: Apex. Apex dynamic-SOQL example. The cap is an illustrative product choice, not a guarantee that all matching records are returned.

public with sharing class DynamicAccountSelector {
    public static List<SObject> findByName(String accountName) {
        Map<String, Object> binds = new Map<String, Object>{
            'requestedName' => accountName
        };
        return Database.queryWithBinds(
            'SELECT Id, Name FROM Account ' +
            'WHERE Name = :requestedName ORDER BY Id LIMIT 50',
            binds,
            AccessLevel.USER_MODE
        );
    }
}
public with sharing class DynamicAccountSelector {
    public static List<SObject> findByName(String accountName) {
        Map<String, Object> binds = new Map<String, Object>{
            'requestedName' => accountName
        };
        return Database.queryWithBinds(
            'SELECT Id, Name FROM Account ' +
            'WHERE Name = :requestedName ORDER BY Id LIMIT 50',
            binds,
            AccessLevel.USER_MODE
        );
    }
}
public with sharing class DynamicAccountSelector {
    public static List<SObject> findByName(String accountName) {
        Map<String, Object> binds = new Map<String, Object>{
            'requestedName' => accountName
        };
        return Database.queryWithBinds(
            'SELECT Id, Name FROM Account ' +
            'WHERE Name = :requestedName ORDER BY Id LIMIT 50',
            binds,
            AccessLevel.USER_MODE
        );
    }
}

Expected behavior: The value is bound from the map; query structure is fixed and access mode explicit.

54. Why should pagination use a deterministic ordering?

Without a sufficient ORDER BY, result order is not a stable paging contract. A nonunique primary sort also needs an appropriate tie-breaker, commonly an ID, to make boundaries predictable. I would consider keyset-style paging for suitable larger traversals rather than assume large OFFSET requests are supported or efficient indefinitely. Concurrent changes still require an explicit consistency policy. Tests should cover equal sort values, deleted records, and retries so a plausible page count does not hide skipped or repeated records.

55. How have Apex security defaults changed across API versions?

Current Salesforce guidance states that API version 67.0 and later uses user-mode database operations and record-sharing defaults, while API version 66.0 and earlier has older system-mode defaults. I would not assume upgrading class metadata is behavior-neutral. Explicit sharing declarations and explicit operation access modes make the intended contract clearer across versions. Review the actual entry point and operation, then test restricted personas. Any deliberate system-mode work needs a justified authorization boundary rather than a blanket workaround for newly surfaced permission failures.

56. What does WITH USER_MODE do in an Apex query?

It explicitly requests user-mode data access for the query, enforcing relevant user permissions such as object access, field security, and sharing. This makes the operation's intent clearer even when the current API version has a user-mode default. I would expect a permission problem to be handled deliberately rather than switch to system mode merely to make the query succeed. The query must still limit its population and validate inputs. User mode enforces data access; it does not decide every business rule about which action the application should offer.

57. When is stripInaccessible useful?

Security.stripInaccessible can remove fields the user is not permitted to access for a specified operation, supporting deliberate graceful degradation or sanitization of incoming sObjects. Code must use the returned records, inspect removed-field information when relevant, and handle object-permission failures appropriately. I would not silently discard a field that is essential to the business operation and then report complete success. The method does not replace record-level authorization or a clear access mode. Choose between failing and degrading according to the actual product contract.

Code language: Apex. Apex illustration with no DML. Root object access can still fail, and the application must decide whether removed fields are optional or require an error.

List<Account> proposed = new List<Account>{
    new Account(Name = 'Example', Description = 'Optional note')
};
SObjectAccessDecision decision = Security.stripInaccessible(
    AccessType.CREATABLE, proposed
);
List<SObject> sanitized = decision.getRecords();
Boolean removedAnyFields = !decision.getRemovedFields().isEmpty();
System.debug('Fields removed: ' + removedAnyFields);
List<Account> proposed = new List<Account>{
    new Account(Name = 'Example', Description = 'Optional note')
};
SObjectAccessDecision decision = Security.stripInaccessible(
    AccessType.CREATABLE, proposed
);
List<SObject> sanitized = decision.getRecords();
Boolean removedAnyFields = !decision.getRemovedFields().isEmpty();
System.debug('Fields removed: ' + removedAnyFields);
List<Account> proposed = new List<Account>{
    new Account(Name = 'Example', Description = 'Optional note')
};
SObjectAccessDecision decision = Security.stripInaccessible(
    AccessType.CREATABLE, proposed
);
List<SObject> sanitized = decision.getRecords();
Boolean removedAnyFields = !decision.getRemovedFields().isEmpty();
System.debug('Fields removed: ' + removedAnyFields);

Expected behavior: The returned collection is the sanitized input; the flag indicates whether any fields were removed.

58. How do with sharing, without sharing, and inherited sharing express intent?

These declarations describe record-sharing behavior for classes, while inherited sharing follows the applicable calling context rather than hardcoding one sharing choice. Without sharing is a deliberate bypass that requires careful justification. User-mode database operations enforce their own access rules, so a class declaration is not the only factor. I would use explicit declarations and operation modes, especially across API-version changes, then test the supported entry paths. Object and field permissions remain distinct from the record-sharing declaration itself.

59. How would you test that Apex respects restricted users?

Create or configure representative test personas with the intended permission model, run the relevant operations in their supported user context, and assert both allowed results and denied access. System.runAs can help establish a test user context, but it is not a universal switch that makes every operation enforce CRUD and FLS regardless of access mode. I would test the explicit query and DML modes and the actual entry point. Administrator-only tests can conceal overbroad selectors and missing field restrictions.

60. How should an @AuraEnabled method validate its inputs?

Treat browser-supplied parameters as untrusted data. Validate required values, allowed transitions, record ownership or access, maximum collection sizes, and any structural choices before performing work. An ID arriving from the page is not proof that the user may act on that record. I would return a controlled error without leaking internal details and keep authorization on the server. UI visibility and disabled buttons improve usability, but a caller can invoke a permitted endpoint outside the intended component flow.

61. How does Queueable Apex differ from a future method?

Queueable Apex provides a job-based model with a returned job ID, support for richer serializable state, and supported chaining. Future methods have more restrictive signatures and older asynchronous semantics. I would generally evaluate Queueable for new work that fits its model rather than assume future methods are interchangeable. Both have limits and execution constraints, and neither guarantees immediate execution. The choice should include monitoring, retries, transaction boundaries, and whether the work can be safely repeated after an uncertain outcome.

Code language: Apex. Apex Queueable class depending on AccountSelector from question 18. This minimal example demonstrates the interface, not durable audit storage or a retry policy. Enqueueing is deliberately not performed here.

public with sharing class AccountAuditJob implements Queueable {
    private Set<Id> accountIds;

    public AccountAuditJob(Set<Id> requestedIds) {
        accountIds = new Set<Id>();
        if (requestedIds != null) accountIds.addAll(requestedIds);
    }

    public void execute(QueueableContext context) {
        List<Account> visible = AccountSelector.findByIds(accountIds);
        System.debug('Visible account count: ' + visible.size());
    }
}
public with sharing class AccountAuditJob implements Queueable {
    private Set<Id> accountIds;

    public AccountAuditJob(Set<Id> requestedIds) {
        accountIds = new Set<Id>();
        if (requestedIds != null) accountIds.addAll(requestedIds);
    }

    public void execute(QueueableContext context) {
        List<Account> visible = AccountSelector.findByIds(accountIds);
        System.debug('Visible account count: ' + visible.size());
    }
}
public with sharing class AccountAuditJob implements Queueable {
    private Set<Id> accountIds;

    public AccountAuditJob(Set<Id> requestedIds) {
        accountIds = new Set<Id>();
        if (requestedIds != null) accountIds.addAll(requestedIds);
    }

    public void execute(QueueableContext context) {
        List<Account> visible = AccountSelector.findByIds(accountIds);
        System.debug('Visible account count: ' + visible.size());
    }
}

Expected behavior: A queued execution uses the bounded supplied ID set and records a count without changing records.

62. When is Batch Apex appropriate?

Batch Apex is suitable for workloads that need to process a large population in separate scopes, using start, execute, and finish responsibilities. Each execute scope has its own transaction, so one successful scope does not mean the entire job succeeded or can be rolled back as one unit. I would design a selective source, appropriate scope size, and per-record or per-scope outcomes. Batch processing adds operational complexity; for a small bounded task, a simpler Queueable or synchronous operation may be easier to maintain.

63. What does Database.Stateful preserve in Batch Apex?

It allows supported instance member state to persist between batch transactions, which can help accumulate a summary across scopes. Static variables are not the same persistence mechanism, and retaining large state can increase serialization overhead. I would keep state small and purposeful, such as counters needed by finish, rather than store every processed record. Persistent reporting or restartable workflows may need durable records instead. The design should distinguish in-job aggregation from a recovery strategy that survives failure, cancellation, or a completely new job run.

64. What should Scheduled Apex be responsible for?

Scheduled Apex starts work according to a schedule, but the scheduled entry point should remain bounded and delegate suitable larger work through an appropriate mechanism. Its limits and timing behavior should be checked specifically rather than assumed to match every asynchronous context. I would prevent overlapping runs where they cause conflicts, define the scheduling timezone, and monitor failures. A schedule existing in Setup does not prove the underlying business job completed successfully, so operational status needs to track execution and outcomes separately.

65. How should callouts be coordinated with database changes?

A remote callout and Salesforce DML do not form a single distributed transaction automatically. I would choose an allowed execution sequence and define what happens if one side succeeds while the other fails. Transaction restrictions, including uncommitted work and particular asynchronous callout requirements, must be checked for the chosen context. Stable correlation IDs, idempotency, and reconciliation are more reliable than blind retries. Avoid holding a user's interaction open unnecessarily when an asynchronous integration with clear status can satisfy the requirement.

66. What do Named Credentials and External Credentials separate?

Named Credentials describe endpoint-related configuration, while External Credentials define authentication and principals used to access the external system. Permission mappings determine which users can use a principal. This keeps secrets and authentication concerns out of ordinary Apex code, but it does not automatically authorize every possible business operation at the destination. I would configure least privilege, environment-specific endpoints, rotation, and ownership. Packaging metadata alone may not populate all credentials or tokens, so deployment and operational setup need explicit verification.

Code language: Apex. Apex callout example, not executed. Catalog_Service, its authentication/principal permissions, and the remote endpoint must be configured. The timeout is illustrative; callers must handle status codes, exceptions, and uncertain remote outcomes.

public with sharing class CatalogClient {
    public static HttpResponse fetchStatus() {
        HttpRequest request = new HttpRequest();
        request.setEndpoint('callout:Catalog_Service/status');
        request.setMethod('GET');
        request.setTimeout(10000);
        return new Http().send(request);
    }
}
public with sharing class CatalogClient {
    public static HttpResponse fetchStatus() {
        HttpRequest request = new HttpRequest();
        request.setEndpoint('callout:Catalog_Service/status');
        request.setMethod('GET');
        request.setTimeout(10000);
        return new Http().send(request);
    }
}
public with sharing class CatalogClient {
    public static HttpResponse fetchStatus() {
        HttpRequest request = new HttpRequest();
        request.setEndpoint('callout:Catalog_Service/status');
        request.setMethod('GET');
        request.setTimeout(10000);
        return new Http().send(request);
    }
}

Expected behavior: The callout uses a configured Named Credential rather than embedding credentials in the source.

67. How do named-principal and per-user integration identities differ?

A named principal uses a shared configured external identity, while a per-user model authenticates according to the individual user's external identity where supported. The choice affects auditability, authorization, provisioning, and what happens when a user leaves. I would match it to the external system's access model rather than choose only for setup convenience. Salesforce permission to use a credential is one boundary; the remote identity's permissions are another. Tests should cover missing authorization and expired credentials without logging tokens or sensitive responses.

68. How should an LWC refresh data after an Apex mutation?

Refresh according to the data source. A retained wired Apex result can be passed to refreshApex, while relevant LDS records can be marked stale with notifyRecordUpdateAvailable using supported identifiers. An imperative Apex read can be invoked again when needed. I would not assume these caches synchronize automatically or use one refresh API indiscriminately for every adapter. Await the appropriate work and handle failures so the component does not show an old value as confirmation that the update failed or succeeded.

69. How do reactive wire parameters handle undefined and null differently?

For wired Apex parameters, undefined prevents the method from being called, while null is a supplied value and permits invocation. This distinction is useful when a record ID or filter is not ready yet. I would make the initialization contract explicit and handle changing parameters without relying on one timing sequence. The method must still validate null if it is not meaningful. Avoid overloaded @AuraEnabled methods, because selection is not a reliable way to dispatch different wire parameter shapes.

Code language: JavaScript. LWC JavaScript module. The @wire decorator requires the Salesforce LWC compiler; ordinary Node syntax checking does not validate it. Pair with the next HTML block and Apex controller.

import { LightningElement, wire } from 'lwc';
import findAccounts from '@salesforce/apex/AccountSearchController.findAccounts';

export default class AccountSearch extends LightningElement {
    namePrefix; // undefined: the wired Apex method is not invoked yet
    accounts = [];
    error;

    @wire(findAccounts, { namePrefix: '$namePrefix' })
    receiveAccounts({ data, error }) {
        if (data) {
            this.accounts = data;
            this.error = undefined;
        } else if (error) {
            this.accounts = [];
            this.error = 'Accounts could not be loaded.';
        }
    }

    handleSearch(event) {
        this.namePrefix = event.target.value;
    }
}
import { LightningElement, wire } from 'lwc';
import findAccounts from '@salesforce/apex/AccountSearchController.findAccounts';

export default class AccountSearch extends LightningElement {
    namePrefix; // undefined: the wired Apex method is not invoked yet
    accounts = [];
    error;

    @wire(findAccounts, { namePrefix: '$namePrefix' })
    receiveAccounts({ data, error }) {
        if (data) {
            this.accounts = data;
            this.error = undefined;
        } else if (error) {
            this.accounts = [];
            this.error = 'Accounts could not be loaded.';
        }
    }

    handleSearch(event) {
        this.namePrefix = event.target.value;
    }
}
import { LightningElement, wire } from 'lwc';
import findAccounts from '@salesforce/apex/AccountSearchController.findAccounts';

export default class AccountSearch extends LightningElement {
    namePrefix; // undefined: the wired Apex method is not invoked yet
    accounts = [];
    error;

    @wire(findAccounts, { namePrefix: '$namePrefix' })
    receiveAccounts({ data, error }) {
        if (data) {
            this.accounts = data;
            this.error = undefined;
        } else if (error) {
            this.accounts = [];
            this.error = 'Accounts could not be loaded.';
        }
    }

    handleSearch(event) {
        this.namePrefix = event.target.value;
    }
}

Expected behavior: Undefined suppresses the initial call; changing the search value supplies a reactive parameter.

Code language: LWC HTML. LWC HTML template, not a standalone browser document. A deployable component also requires its configuration metadata; the local fixture includes an unexposed example configuration.

<template>
    <lightning-input type="search" label="Account name prefix"
        onchange={handleSearch}></lightning-input>
    <p lwc:if={error} role="status">{error}</p>
    <ul>
        <template for:each={accounts} for:item="account">
            <li key={account.Id}>{account.Name}</li>
        </template>
    </ul>
</template>
<template>
    <lightning-input type="search" label="Account name prefix"
        onchange={handleSearch}></lightning-input>
    <p lwc:if={error} role="status">{error}</p>
    <ul>
        <template for:each={accounts} for:item="account">
            <li key={account.Id}>{account.Name}</li>
        </template>
    </ul>
</template>
<template>
    <lightning-input type="search" label="Account name prefix"
        onchange={handleSearch}></lightning-input>
    <p lwc:if={error} role="status">{error}</p>
    <ul>
        <template for:each={accounts} for:item="account">
            <li key={account.Id}>{account.Name}</li>
        </template>
    </ul>
</template>

Expected behavior: The input is visibly labeled, errors are displayed, and records use stable IDs as template keys.

Code language: Apex. Apex controller for the preceding LWC. LIKE wildcard characters supplied in the prefix retain their pattern meaning; binding prevents value injection but is not a selectivity or literal-prefix guarantee.

public with sharing class AccountSearchController {
    @AuraEnabled(cacheable=true)
    public static List<Account> findAccounts(String namePrefix) {
        if (String.isBlank(namePrefix)) return new List<Account>();
        String pattern = namePrefix.trim() + '%';
        return [
            SELECT Id, Name
            FROM Account
            WHERE Name LIKE :pattern
            WITH USER_MODE
            ORDER BY Name, Id
            LIMIT 50
        ];
    }
}
public with sharing class AccountSearchController {
    @AuraEnabled(cacheable=true)
    public static List<Account> findAccounts(String namePrefix) {
        if (String.isBlank(namePrefix)) return new List<Account>();
        String pattern = namePrefix.trim() + '%';
        return [
            SELECT Id, Name
            FROM Account
            WHERE Name LIKE :pattern
            WITH USER_MODE
            ORDER BY Name, Id
            LIMIT 50
        ];
    }
}
public with sharing class AccountSearchController {
    @AuraEnabled(cacheable=true)
    public static List<Account> findAccounts(String namePrefix) {
        if (String.isBlank(namePrefix)) return new List<Account>();
        String pattern = namePrefix.trim() + '%';
        return [
            SELECT Id, Name
            FROM Account
            WHERE Name LIKE :pattern
            WITH USER_MODE
            ORDER BY Name, Id
            LIMIT 50
        ];
    }
}

Expected behavior: The controller performs a read-only user-mode query and returns a bounded result.

70. Why should an LWC avoid mutating wired or parent-owned objects?

Those values are provided through a data-flow contract rather than owned freely by the receiving component. Mutating them can violate read-only protections or produce inconsistent state across consumers. I would derive a new local object or collection for editing and send a deliberate mutation through the appropriate API or parent event. A shallow copy shares nested objects, so copy the level actually being changed. Then refresh authoritative data after save instead of assuming a local edit proves the server accepted the same value.

71. How should an LWC handle pending requests and errors?

It should expose a clear loading state, prevent inappropriate repeated actions, and show an understandable error while allowing recovery. I would ensure the pending state is cleared on both success and failure, and avoid letting an older response overwrite a newer search or selection. Server errors may have different shapes, so normalize them carefully without exposing sensitive implementation details. Accessibility matters too: status announcements and focus behavior should help users understand the result rather than merely display a spinner that disappears silently.

72. When should Lightning Message Service be considered?

Lightning Message Service can support communication between components across supported DOM or technology boundaries where ordinary parent-child events are insufficient. I would first choose the narrowest communication pattern that fits the component relationship. Define a stable message channel contract, avoid sending unnecessary sensitive data, and manage subscriptions according to component lifetime. A global messaging mechanism is not a substitute for clear data ownership or a shared transactional state model. Test the actual supported container because availability and behavior can depend on where the components run.

73. How does Lightning Web Security affect component design?

Lightning Web Security provides platform isolation and compatibility behavior for component JavaScript, but developers still need secure data handling and supported DOM access patterns. I would avoid assumptions about unrestricted global objects, cross-namespace access, or arbitrary third-party libraries. Test dependencies in the actual Salesforce environment rather than infer compatibility from a standalone web page. Security isolation does not validate business permissions in Apex or sanitize every application-defined data flow, so client-side protections and server-side authorization must be reviewed together.

74. What should Test.startTest and Test.stopTest be used for?

They bracket the operation under test, separating its governor-limit context from setup work and allowing supported asynchronous work queued in that test phase to be observed at stopTest. I would place assertions around meaningful outcomes, not merely use the pair as a ritual. Do not assume every downstream chained job executes recursively in the same test; test units and orchestration deliberately. The production code still runs under real limits, and a test-only reset is not evidence that a long production transaction has additional capacity.

75. How do @TestSetup and test-data factories help?

@TestSetup can provide shared baseline records for test methods in a class, while a factory centralizes intentional construction of varied test data. They reduce duplication without requiring dependence on existing organization records. I would keep defaults visible and let tests override fields relevant to their scenario, avoiding a factory that silently creates a huge unrelated graph. Tests still need realistic validation and automation assumptions. Shared helpers should make the scenario easier to understand, not hide why a record qualifies or which permissions the test expects.

76. How should Apex HTTP callouts be tested?

Use supported callout mocks, such as HttpCalloutMock, to return controlled responses and inspect relevant request details. Tests should cover successful payloads, error statuses, malformed content, and timeout-like exception handling where appropriate. No real external request is needed to prove local parsing and decision logic. I would also maintain a separate authorized integration test strategy for authentication and the actual service contract. A mock that returns whatever the code expects can pass while the production endpoint, headers, or schema are wrong.

Code language: Apex. Apex test class depending on CatalogClient from question 66. It has not been compiled or executed here and does not verify real authentication or the remote service.

@IsTest
private with sharing class CatalogClientTest {
    private class StatusMock implements HttpCalloutMock {
        public HttpResponse respond(HttpRequest request) {
            System.assertEquals('GET', request.getMethod());
            System.assertEquals(
                'callout:Catalog_Service/status', request.getEndpoint()
            );
            HttpResponse response = new HttpResponse();
            response.setStatusCode(200);
            response.setBody('{"status":"ready"}');
            return response;
        }
    }

    @IsTest
    static void readsMockResponse() {
        Test.setMock(HttpCalloutMock.class, new StatusMock());
        Test.startTest();
        HttpResponse response = CatalogClient.fetchStatus();
        Test.stopTest();
        System.assertEquals(200, response.getStatusCode());
        System.assertEquals('{"status":"ready"}', response.getBody());
    }
}
@IsTest
private with sharing class CatalogClientTest {
    private class StatusMock implements HttpCalloutMock {
        public HttpResponse respond(HttpRequest request) {
            System.assertEquals('GET', request.getMethod());
            System.assertEquals(
                'callout:Catalog_Service/status', request.getEndpoint()
            );
            HttpResponse response = new HttpResponse();
            response.setStatusCode(200);
            response.setBody('{"status":"ready"}');
            return response;
        }
    }

    @IsTest
    static void readsMockResponse() {
        Test.setMock(HttpCalloutMock.class, new StatusMock());
        Test.startTest();
        HttpResponse response = CatalogClient.fetchStatus();
        Test.stopTest();
        System.assertEquals(200, response.getStatusCode());
        System.assertEquals('{"status":"ready"}', response.getBody());
    }
}
@IsTest
private with sharing class CatalogClientTest {
    private class StatusMock implements HttpCalloutMock {
        public HttpResponse respond(HttpRequest request) {
            System.assertEquals('GET', request.getMethod());
            System.assertEquals(
                'callout:Catalog_Service/status', request.getEndpoint()
            );
            HttpResponse response = new HttpResponse();
            response.setStatusCode(200);
            response.setBody('{"status":"ready"}');
            return response;
        }
    }

    @IsTest
    static void readsMockResponse() {
        Test.setMock(HttpCalloutMock.class, new StatusMock());
        Test.startTest();
        HttpResponse response = CatalogClient.fetchStatus();
        Test.stopTest();
        System.assertEquals(200, response.getStatusCode());
        System.assertEquals('{"status":"ready"}', response.getBody());
    }
}

Expected behavior: The test checks the intended request and controlled response without a real remote call.

77. Why is code coverage not enough for deployment confidence?

Coverage measures which lines were exercised, not whether correct outcomes were asserted. A test can cover error handling while swallowing every failure or query the wrong population successfully. Deployment coverage rules also depend on the chosen test level and operation, so one headline percentage is not a universal description. I would run required checks, assert business and security behavior, and inspect deployment dependencies. Confidence comes from appropriate evidence about the change, not from manipulating tests solely to reach a numerical threshold.

78. How do custom metadata and custom settings fit configuration needs?

Both can externalize configuration, but their deployment, access, hierarchy, and packaging behavior differ. Custom metadata is often useful for deployable application configuration, while supported custom-setting patterns can fit particular runtime or hierarchy needs. I would choose according to who manages the values and how environments differ, not treat either as a general secret store. Configuration also needs validation and safe defaults. A metadata-driven rule engine can become harder to maintain than explicit code if the configuration language grows without clear constraints.

79. What should a Salesforce deployment include besides code?

It may need object and field metadata, permissions, component configuration, automation dependencies, and environment-specific setup. I would build a version-controlled deployment package and identify post-deployment actions such as credential population or assignments that are not automatically satisfied by deploying Apex. Validate against an appropriate target and inspect results rather than infer success from a local build. Rollback planning must include data and automation effects, because redeploying an older class does not reverse records already changed by the new behavior.

80. How would you diagnose a test that passes in one org but fails in another?

Compare metadata, API versions, permissions, validation rules, active automation, configuration, and any accidental dependence on existing data. Then reproduce the smallest meaningful scenario in an appropriate test environment. I would avoid disabling validations or adding SeeAllData merely to suppress the difference. The failure can reveal an undeclared dependency or an unrealistic fixture. Record the required configuration and make tests intentional, while recognizing that some environment-specific integration behavior belongs in a separate test layer rather than a supposedly isolated unit test.

Salesforce Developer Interview Questions and Answers for Experienced

These answers focus on evidence, ownership, and recovery. Adapt them to the organization’s data, products, API versions, and operating model rather than treating them as universal guarantees.

81. How would you design automation for an object with many existing flows and triggers?

I would inventory every entry point, owner, condition, and side effect before adding another rule. Identify overlapping responsibilities, transaction interactions, and pathways that update the same records repeatedly. Then choose a clear orchestration approach and migrate incrementally with behavior tests. A new handler framework does not automatically simplify existing declarative automation. I would measure the actual save path with representative bulk data and restricted users, preserving business behavior while reducing duplicated work and making error ownership understandable to administrators and developers.

82. How would you prevent repeated side effects across separate transactions?

Use a durable business identity or operation key and a state model that can recognize completed work, rather than a static variable that lasts only for one transaction. I would define what counts as the same request, enforce uniqueness where appropriate, and handle concurrent attempts. For external effects, include an idempotency contract with the recipient or a reconciliation process. A record status alone may be insufficient if a failure happens between the effect and the status update, so examine that gap explicitly.

83. How would you recover from a partial-success data-processing job?

I would retain per-record identities and outcomes, distinguish retryable failures from invalid data, and retry only work whose state is understood. Successful scopes may already have committed, so rerunning the entire job blindly can repeat side effects. Capture enough error context for diagnosis without storing sensitive payloads unnecessarily. Reconcile expected records and important fields after recovery, not only job counts. The recovery design should be part of the original job contract, including who investigates exhausted retries and how business users see incomplete processing.

84. How would you investigate record-locking failures?

I would identify the records and related parents being updated, overlapping transactions, relationship skew, and the order in which locks are acquired. Apparently unrelated child updates can contend on shared parents or other platform-managed relationships. Reducing scope size, grouping work appropriately, or consistent processing order may help, but the remedy depends on evidence. I would avoid immediate uncontrolled retries that increase contention. Test realistic concurrency in an authorized environment and define a bounded retry or rescheduling policy for failures that remain transient.

85. What risks arise from data skew in Salesforce?

Large concentrations of ownership or relationship links can affect sharing calculations, locking, and query behavior. The relevant skew depends on the object model and operations, so I would inspect actual distributions rather than apply one universal threshold. A design that is fine with evenly distributed sandbox data may fail when many records share one parent or owner. I would consider alternative ownership, relationship, or processing strategies and measure the impact, while preserving the real business relationship and access requirements rather than reshaping data solely for a benchmark.

86. How would you optimize a query that slows as an org grows?

I would examine the exact filter values, indexes, result size, query-plan information, and data distribution at realistic scale. A once-selective status can become common, changing the optimizer's choices. Reduce unnecessary fields and relationship data, but do not confuse a small selected column set with a selective filter. I would verify security and pagination semantics after changes. If the requirement inherently scans a large population, choose a suitable processing architecture rather than force it through an interactive request with a larger timeout expectation.

87. How would you design a large-volume synchronization integration?

I would define source ownership, stable external keys, change capture or polling strategy, pagination, deletion handling, and reconciliation before choosing an API. Bulk-oriented APIs can suit large data movement, while request-response APIs serve different latency needs. Limits, licenses, and supported objects must be checked for the actual product. I would store checkpoints durably and design retries around idempotent operations. A completed transfer job is insufficient evidence: reconcile identities, fields, and errors to detect silent omissions or transformations that produced plausible but incorrect totals.

88. When would you choose events instead of a synchronous integration call?

Events fit decoupled workflows where the initiating transaction can complete without an immediate business response and consumers can process asynchronously. A synchronous call is appropriate when the user truly needs the remote answer before proceeding, subject to latency and failure constraints. I would compare delivery semantics, ordering, retention, replay, and monitoring for the chosen event technology. Events do not eliminate failures or guarantee exactly-once business processing. Consumers need idempotency and recovery, and the user interface needs an honest representation of pending versus completed work.

89. How do Platform Events and Change Data Capture serve different purposes?

Platform Events communicate application-defined business events, while Change Data Capture reports supported record changes through the platform's change-event model. The choice depends on whether consumers need a semantic business signal or a feed of data changes. I would inspect availability, payload, permissions, retention, and delivery behavior for the selected feature. Neither should be treated as a permanent complete audit archive without a retention strategy. Consumers also need to handle duplicate deliveries, gaps, and schema evolution according to the documented contract.

90. What does publish-after-commit behavior change for events?

It aligns publication with a successful transaction commit where the selected event configuration supports that behavior, reducing the risk of notifying consumers about data that later rolls back. It is not a distributed transaction that guarantees every subscriber completes its work. I would distinguish acceptance of a publish request from downstream processing and monitor relevant outcomes. The selected event's publishing behavior matters, so inspect its configuration. Consumers should still reconcile data and tolerate retries rather than assume an event implies every related system is already consistent.

91. How would you handle an API timeout after Salesforce may have committed a write?

Treat the outcome as uncertain and reconcile using a stable request or external identifier before retrying. A client timeout does not prove that Salesforce rolled back or never received the operation. I would use idempotent upsert patterns where appropriate, inspect per-record results when available, and avoid matching solely on mutable display names. The recovery path should be bounded and observable. For multi-step workflows, track which business effect is confirmed rather than repeat every step because one response was lost.

92. How would you choose an authentication pattern for a Salesforce integration?

I would identify whether the actor is a user or a service, the deployment environment, required scopes, and the current supported OAuth and application configuration options. Choose a flow appropriate to that trust model and manage credentials through approved storage and rotation. Avoid embedding a shared user's password in code. Authentication establishes identity, while permissions and business authorization determine allowed actions. I would test expiry, revocation, and least-privilege access, and document ownership so the integration does not depend on an employee's unmanaged account.

93. How would you secure a custom Apex REST endpoint?

I would validate inputs, authorize the exact operation and records, apply explicit data-access modes, and return a bounded response with controlled errors. Authentication and Apex class access are necessary but do not replace those checks. Design request size limits, idempotency, and versioned contracts where appropriate. I would also inspect what happens when a caller supplies fields the UI never exposes. Tests should include restricted users, malformed payloads, and repeated requests, while logs should retain correlation and diagnosis without exposing secrets or unnecessary personal data.

94. How would you evaluate a proposed system-mode exception?

I would ask which business capability requires elevation, who may invoke it, and which records and fields it must touch. Constrain that capability through an explicit authorization check and a narrow operation rather than making a whole service broadly privileged. Record the reasoning and test both authorized and unauthorized callers. API-version changes can expose reliance on older defaults, but restoring broad system mode is not automatically the right migration fix. Elevation should be a deliberate reviewed exception with observable outcomes and minimal scope.

95. How would you migrate Apex classes to a newer API version safely?

Inventory version-sensitive behavior and dependencies, especially security defaults, then test representative entry points and permission personas before changing versions broadly. I would make sharing and database access modes explicit, review compilation and runtime differences, and stage the rollout. A version change can affect semantics without a large code diff. Preserve a recovery plan and investigate new permission failures instead of granting broad access reflexively. The migration is complete when intended behavior and denied-access cases are verified, not merely when metadata deploys successfully.

96. How would you prevent data leakage through a read-only Apex response?

Read-only does not mean harmless: a response can expose fields or records the user should not see. I would minimize the selected data, enforce appropriate access, and project a deliberate response contract rather than serialize an entire object graph. Review error messages, logs, and cached client data as additional disclosure paths. Tests should inspect the complete returned payload under restricted permissions. Removing a sensitive field from the visible template is insufficient if the browser has already received it in the server response.

97. How would you design permission-sensitive caching?

I would identify which user, tenant, permission, and record context determines the result and ensure the cache cannot reuse a privileged answer for a less privileged request. Define invalidation and freshness requirements, and avoid caching sensitive data more broadly than necessary. Platform-managed caches and custom caches have different contracts, so do not transfer assumptions between them. I would test permission changes and stale records explicitly. A faster read is not acceptable if it bypasses current authorization or exposes data through an incorrectly shared cache key.

98. How would you handle a large editable grid in an LWC?

I would limit the loaded population, request only necessary fields, preserve stable row identities, and define a bounded save contract. Use supported components where they fit, but inspect accessibility and performance with realistic row counts. Saving rows one at a time can create excessive requests and confusing partial outcomes; one server transaction has different limits and all-or-none choices. I would show per-row errors clearly and refresh authoritative results, avoiding a success toast that hides failed rows or overwrites concurrent changes silently.

99. How can stale responses corrupt an LWC search experience?

If several requests are in flight, an older request can finish later and replace newer results. I would associate responses with the current request or search state and ignore obsolete results, while using appropriate debouncing or reactive data patterns. This is distinct from server-side query selectivity and cache freshness. Test rapid input changes and failures, not just sequential clicks. The component should preserve a clear loading and error state for the active request instead of allowing every promise completion to update the screen unconditionally.

Code language: JavaScript. Plain JavaScript helper illustrating stale-response protection; an LWC must connect it to its actual promise and state handling. This helper has a local Node fixture, which does not validate Salesforce component execution.

export function createLatestRequestGate() {
    let latest = 0;
    return {
        begin() {
            latest += 1;
            return latest;
        },
        isCurrent(requestId) {
            return requestId === latest;
        }
    };
}
export function createLatestRequestGate() {
    let latest = 0;
    return {
        begin() {
            latest += 1;
            return latest;
        },
        isCurrent(requestId) {
            return requestId === latest;
        }
    };
}
export function createLatestRequestGate() {
    let latest = 0;
    return {
        begin() {
            latest += 1;
            return latest;
        },
        isCurrent(requestId) {
            return requestId === latest;
        }
    };
}

Expected behavior: A response can be ignored when its request ID is no longer current.

100. What should an LWC accessibility review include?

Review visible and programmatic labels, keyboard interaction, focus movement, error announcements, and responsive behavior across complete tasks. Base components provide useful foundations but do not make an assembled workflow automatically accessible. I would test loading, empty, error, and success states and use supported component APIs rather than manipulating internal markup. Custom interactions need appropriate semantics and behavior. Automated checks can catch some defects, but real keyboard and representative assistive-technology testing are needed to assess whether users can understand and complete the task.

101. How would you choose between LDS, GraphQL, and custom Apex for a screen?

I would start with the data shape, supported objects, mutation needs, and transaction requirements. LDS-based components and adapters provide managed data access, while the supported GraphQL adapter can retrieve a precise graph or reduce multiple requests where its capabilities fit. Apex supports custom server logic and transactional operations beyond those services. Check current module and feature support rather than assume all GraphQL adapters are identical. I would measure payload and refresh behavior and avoid introducing Apex solely because it is familiar.

102. How would you design an asynchronous retry policy?

Classify failures, use bounded retries with an appropriate delay or scheduling mechanism, and retain a stable operation identity. Authentication errors, invalid data, and missing permissions usually need correction rather than endless retries. I would track attempts and final outcomes durably, avoid retry storms, and provide a path for responsible owners to inspect failed work. A retry must be safe after partial completion or an uncertain result. Queueable chaining alone is not a complete policy for backoff, deduplication, and business reconciliation.

103. What are the risks of unbounded Queueable chaining?

A chain can create a long-running workflow with hidden capacity consumption, difficult recovery, and unclear completion status. Platform limits and enqueueing rules also depend on context. I would bound the work, persist checkpoints, and make each stage's outcome visible. If the job represents processing a large stable population, Batch Apex or another supported integration pattern may fit better. Chaining should express a real dependency, not become a way to postpone a design decision about data volume, scheduling, or how a failed middle stage is recovered.

104. How would you monitor asynchronous processing operationally?

Use the relevant platform job and event information together with application-level correlation and business status. A queued or completed platform job does not necessarily prove every intended record or remote effect is correct. I would expose counts, failures, retry state, and age of pending work without excessive sensitive logs. Alerts should identify an actionable owner and threshold. Periodic reconciliation helps detect silent gaps, while dashboards should distinguish platform execution success from successful completion of the actual business workflow.

105. How would you select a Batch Apex scope size?

I would consider work per record, relationship fan-out, callouts, locking, heap, and CPU, then test representative distributions. A smaller scope can reduce per-transaction pressure but increase overhead and total transaction count; a larger scope can improve throughput until a constrained resource dominates. There is no universally best scope size. I would measure failures and throughput in an appropriate environment, keep the query selective, and ensure the recovery design remains correct if one scope fails while others have already committed.

106. How would you test a multi-stage asynchronous workflow?

Separate stage logic from orchestration so each unit has meaningful controlled tests, then test supported scheduling and handoff behavior explicitly. Do not assume one Test.stopTest invocation proves every nested or chained stage ran as it will in production. I would use mocks for external dependencies and persistent state assertions for handoffs, failures, and retries. An authorized integration test can validate the broader workflow in a suitable environment. Record the limits of each test layer instead of claiming a unit test simulates real queue timing and capacity.

107. How would you make test data realistic without relying on production records?

Create fixtures representing the data relationships, permission personas, and edge distributions relevant to the feature. Include missing optional values, duplicate business keys where allowed, and multiple records that share parents. Factories can reduce repetition, but their defaults should not hide the condition being tested. I would avoid copying sensitive production data unnecessarily and use configuration-aware setup for required metadata. Realistic tests model the important constraints, not the entire organization, and performance validation may require a separate volume-oriented environment.

108. What should a bulk trigger test assert beyond record count?

It should verify field values, related-record identities, absence of duplicate side effects, and correct behavior for every relevant input category. Include unchanged records and records that cross the triggering business condition, then inspect errors where expected. I would also check that the code remains within appropriate limits under a representative batch. A count can look correct while the wrong records were updated. Tests should exercise the actual trigger path, since helper-only tests can miss context-variable handling or interactions with existing automation.

109. How would you plan a deployment that changes data and metadata together?

I would sequence schema additions, compatible code, permission changes, data backfills, and eventual cleanup so intermediate states remain safe. A destructive rename or removal can break integrations before a migration finishes. Validate dependencies and rehearse with representative data, including recovery from a partially completed backfill. I would retain reconciliation evidence and a rollback or forward-fix strategy. Deploying the old metadata cannot automatically undo transformed data or external effects, so operational recovery must be designed separately from version-control rollback.

110. How would you manage environment-specific configuration?

Keep deployable application structure in version control while separating environment-specific endpoints, credentials, and intentionally different settings through supported mechanisms. I would document required configuration and validate its presence without printing secrets. Avoid hardcoded IDs or hostnames that happen to work in one sandbox. A deployment should fail clearly or remain safely disabled when a required dependency is missing. Configuration drift needs detection and ownership, because a codebase can be identical across environments while its effective behavior differs substantially.

111. How would you diagnose a failure that occurs only for one permission persona?

Reproduce the exact operation and compare class access, object permissions, field security, sharing, licenses, and relevant configuration. Also inspect API version and explicit operation modes. I would avoid using administrator access as the fix or treating every security exception as evidence that the user needs more permissions. The code may be selecting unnecessary fields or attempting an unauthorized action. Test the minimal intended grant and verify that unrelated access remains restricted, preserving a clear record of why the chosen behavior is correct.

112. How would you instrument Apex without leaking sensitive data?

Log stable correlation identifiers, operation names, counts, timings, and controlled error categories rather than entire records, tokens, or request bodies by default. Diagnostic detail should be proportional to the need and subject to retention and access controls. I would ensure error handling does not expose internal stack details to an ordinary user while preserving useful evidence for authorized support. Excessive logging can also add overhead and obscure the signal. Test failure paths so the absence of a successful response still leaves actionable, safe diagnostics.

113. How would you review a Salesforce integration's field ownership rules?

For every synchronized field, define which system is authoritative, how conflicts are resolved, and what happens on deletion or deactivation. Bidirectional copying without ownership can create update loops or overwrite deliberate changes. I would preserve stable identity mappings and provenance, then test concurrent updates and replayed events. Timestamp-based conflict rules need careful clock and semantic assumptions. The integration should report ambiguous cases rather than silently choose a winner, and reconciliation should compare meaningful field values as well as record counts.

114. How would you prevent schema changes from silently breaking consumers?

Inventory Apex, flows, LWCs, reports, integrations, and packages that depend on the affected metadata. Use source references and metadata tools, but also verify dynamic usages that static dependency checks may miss. I would prefer compatible additions and a deprecation period where possible, with contract tests for external consumers. A field label change differs from an API-name or type change. Communicate the actual contract change and validate read and write paths before removing the old representation or assuming a successful deployment proves compatibility.

115. What should a technical review of a metadata-driven Apex framework examine?

It should examine whether configuration makes the business behavior clearer, validates invalid combinations, and preserves security and predictable limits. I would inspect dynamic query construction, ordering, recursion, caching, and error reporting, not only the framework's extension points. Excessive genericity can hide which records an operation touches or make unit tests harder to understand. A good framework reduces repeated risk while keeping individual rules traceable. Require representative end-to-end examples and a plan for changing configuration safely, with ownership and recovery evidence.

116. How would you decide whether logic belongs inside Salesforce or externally?

I would compare data locality, transaction requirements, latency, volume, operational ownership, and platform limits. Logic tightly coupled to Salesforce record validation may fit inside the transaction, while long-running computation or broad cross-system coordination may suit an external service. Externalizing work introduces authentication, delivery, and consistency obligations rather than removing complexity. I would choose the smallest architecture that meets the requirement and test its failure modes. The decision should be based on workload evidence, not a blanket preference for either platform code or microservices.

117. How would you handle a production automation incident safely?

First contain further unintended effects through authorized controls and preserve evidence of affected records and operations. Identify whether changes propagated to external systems before planning recovery. I would restore from verified before-values or a reviewed correction rule, test a small representative subset, and reconcile the full intended population. Re-enabling the automation requires fixing the trigger condition or logic and validating the original failure case. A successful deployment alone does not prove the damaged data or downstream effects have been repaired.

118. How would you assess an Apex performance improvement claim?

Require equivalent business results and a comparison under representative data, security context, and automation configuration. Measure the constrained dimensions, such as CPU, queries, heap, locks, and total workflow latency, rather than report only one faster local loop. Asynchronous execution can shift latency outside the initiating request without reducing total work. I would check repeated side effects and access behavior after the change. A credible claim explains its workload assumptions and limitations instead of asserting that one pattern is always faster across organizations.

119. How would you design a senior Salesforce Developer interview exercise?

I would provide a small bulk-update scenario with a query-in-loop defect, a permission-sensitive field, and a retryable external handoff. Ask the candidate to identify transaction boundaries, propose a data-access contract, and write meaningful tests before optimizing. Then change the caller or API version and ask what must be revalidated. Strong candidates separate record sharing from field permissions, distinguish platform completion from business completion, and explain recovery. The exercise should evaluate practical judgment rather than reward memorized limit numbers or a large unreviewable framework.

120. What does a dependable Salesforce development operating model include?

It combines a clear data model, explicit security, bounded automation, reliable integration contracts, and evidence-based testing and deployment. I would define ownership for configuration, credentials, asynchronous failures, and production recovery, with source-controlled changes and appropriate validation environments. Monitor business outcomes as well as platform jobs and preserve a way to reconcile uncertain writes. Success is not merely passing coverage or deploying metadata: it is a maintainable system whose ordinary users can complete their work safely and whose failures can be diagnosed and recovered predictably.

Salesforce Developer Documentation and Further Reading

Use these official Salesforce references to verify behavior for the relevant API version, product, license, and execution context. Validate examples in an authorized development environment with representative permissions and data before using them in a real application.

Team Sherlock.sh

Building fraud intelligence for live high-stake video interactions (financial discussions, hiring interviews, board meeting etc).

Catch candidate fraud before it costs you.

Sherlock AI helps you detect AI-assisted, proxy, and deepfake candidates, so every hiring decision is backed by evidence.

Ask AI about Sherlock.sh

Similar Posts