Salesforce interview questions and answers
1,743 Salesforce interview questions with answers in simple English, for freshers and experienced professionals. Pick your experience level or role below, or test yourself in a timed mock interview.
Start here
By experience
Most searched topics
How Salesforce interviews work
Salesforce interviews follow similar rounds around the world, whether at a consulting partner such as Accenture, Deloitte or TCS, at Salesforce itself, or at a company that uses Salesforce. Knowing them tells you what to prepare.
- Screening call. A recruiter checks your experience, certifications, notice period and salary expectations.
- Technical round 1. Core concepts for your role: security and automation for admins; Apex, SOQL, triggers and LWC for developers.
- Technical round 2 or scenario round. Real problems: "How would you design this?" or "What would you do if this broke in production?" Experienced candidates get more design and integration questions.
- Managerial or behavioural round. Your projects, your role in them, how you handle deadlines, clients and team members. In the US, UK and Europe this is often structured around past examples ("Tell me about a time when…").
- HR or recruiter round. Salary, start date or notice period, and fit. Some employers add a take-home exercise, a live build or a client interview for project roles.
Freshers usually get more definitions and basics. From about three years of experience, expect most questions to be scenarios built on your own projects. Read the scenario-based questions and the company-wise questions for examples.
By role
Full question sets for each job title and level of experience.
- Admin48 questions
- Admin: security and sharing36 questions
- Admin: reports and dashboards15 questions
- Developer40 questions
- Architect20 questions
- Consultant12 questions
- Business Analyst15 questions
- DevOps31 questions
- Freshers18 questions
- 2 years experience18 questions
- 3 years experience20 questions
- 4 years experience16 questions
- 5 years experience18 questions
- 7 years experience18 questions
- 10 years experience16 questions
- Experienced (senior)15 questions
Apex
Code, async processing and testing.
Lightning Web Components (LWC)
Front-end questions, from decorators to debugging.
Flow & automation
Declarative automation, and knowing when to use Apex instead.
Integration
APIs, authentication and middleware.
Agentforce & AI
AI agents, the Trust Layer and real use cases.
Clouds & industries
Product and industry cloud questions, from Sales Cloud to Health and Nonprofit.
Scenario-based questions
Real project problems: how would you design it, and what would you do when it breaks.
Recent interview questions (company-wise)
Questions candidates report from recent interviews at TCS, Infosys, Accenture, Cognizant, Capgemini, the Big 4 and more.
Learning topics
Step-by-step tutorials from setup basics to Agentforce.
Learning practice questions
Hands-on exercises by topic, each with a check and a model answer.
Learning projects
Complete apps to build end to end, from data model to Agentforce.
- All practice projectsOverview
- B2B sales pipeline (Sales Cloud)20 exercises
- Customer support desk (Service Cloud)20 exercises
- University student success20 exercises
- Event and conference management21 exercises
- Hospital management21 exercises
- Real estate listings and offers20 exercises
- Recruitment and hiring21 exercises
General Salesforce questions
Fundamentals that come up in screening rounds for every role.
General
01What is Salesforce and how is it used in organizations?
What is Salesforce and how is it used in organizations?
Salesforce is a cloud-based CRM platform that helps businesses manage customer relationships, sales, and operations. It centralizes data like leads, accounts, and opportunities in one place. Teams use it to track interactions, automate processes, and improve customer experience. Since it's cloud-based, users can access it from anywhere. It's widely used across sales, service, marketing, and more.
02What are the key components of Salesforce architecture?
What are the key components of Salesforce architecture?
Salesforce is built on a multi-tenant architecture, meaning multiple customers share the same infrastructure securely. Key components include objects, fields, records, metadata, and the platform services like Apex and APIs. It also has a detailed security model. Everything is metadata-driven, so changes don't affect the core system. This makes customization fast and scalable.
03What is a multi-tenant architecture?
What is a multi-tenant architecture?
Multi-tenancy means multiple customers share the same application and infrastructure. Each customer's data is isolated and secure. It allows Salesforce to deliver updates to everyone at once. This reduces maintenance effort for customers. It also makes the platform cost-efficient and highly scalable.
04What are standard and custom objects?
What are standard and custom objects?
Standard objects are pre-built, like Account, Contact, and Opportunity. Custom objects are created by users to meet specific business needs. For example, a company might create a 'Project' object. Both can have fields, relationships, and automation. Custom objects behave just like standard ones.
05What is metadata in Salesforce?
What is metadata in Salesforce?
Metadata defines the structure of the application, like objects, fields, layouts, and workflows. Instead of storing data, it describes how data is organized. Salesforce uses metadata to deploy changes across environments. This makes development flexible and easy to migrate.
06What is the difference between SaaS, PaaS, and IaaS?
What is the difference between SaaS, PaaS, and IaaS?
Salesforce mainly operates as SaaS (Software as a Service), providing ready-to-use applications. It also offers PaaS via the Force.com platform for building custom apps. IaaS is about infrastructure, which Salesforce manages internally. Users mostly interact with SaaS and PaaS layers.
07What is CRM and why is it important?
What is CRM and why is it important?
CRM stands for Customer Relationship Management. It helps businesses manage interactions with customers and prospects. It improves sales tracking, customer service, and marketing efforts. With CRM, companies can make data-driven decisions. It also enhances customer satisfaction.
08What is the role of AppExchange?
What is the role of AppExchange?
AppExchange is Salesforce's marketplace for apps and integrations. Users can install pre-built solutions instead of building from scratch. It saves time and effort. Many apps are industry-specific. It's widely used in real-world implementations.
09What are environments in Salesforce?
What are environments in Salesforce?
Salesforce provides environments like Developer, Sandbox, and Production. Sandboxes are used for testing and development. Production is the live system. This separation ensures safe deployments. It helps avoid direct changes in live data.
10What is a record in Salesforce?
What is a record in Salesforce?
A record is a single instance of an object, like one Account or Contact. It stores data in fields. Users interact with records daily. Records are the core data units in Salesforce. They can be created, updated, and deleted.
11What is the difference between logical and physical data model in Salesforce?
What is the difference between logical and physical data model in Salesforce?
Logical defines relationships and structure (objects, relationships), while physical includes actual implementation (fields, indexes, storage).
12What is schema builder used for?
What is schema builder used for?
A visual tool to design and manage objects, fields, and relationships in a graphical format.
13Explain lookup vs master-detail in terms of behavior.
Explain lookup vs master-detail in terms of behavior.
Lookup is loosely coupled; master-detail enforces dependency, cascade delete, and roll-ups.
14What is data skew and why is it problematic?
What is data skew and why is it problematic?
Occurs when many records relate to one parent, causing performance and locking issues.
15What is selective query in Salesforce?
What is selective query in Salesforce?
A query that uses indexed fields to return results efficiently under large data volumes.
16What are external objects?
What are external objects?
Objects that map to external data sources using OData without storing data in Salesforce.
17What is a junction object?
What is a junction object?
A custom object used to create many-to-many relationships via two master-detail fields.
18What is skinny table?
What is skinny table?
A performance optimization feature that creates a denormalized table for frequently accessed fields.
19What is deferred sharing calculation?
What is deferred sharing calculation?
A way to delay sharing rule recalculations during large data operations.
20What is the difference between big objects and standard objects?
What is the difference between big objects and standard objects?
Big objects handle massive data volumes with limited querying; standard objects support full functionality.
21How do you design a scalable data model for millions of records?
How do you design a scalable data model for millions of records?
Use indexing, partitioning, archiving strategy, avoid data skew, and design selective queries.
22What is the impact of ownership skew?
What is the impact of ownership skew?
Large number of records owned by one user causes locking and sharing recalculation issues.
23How does Salesforce indexing work internally?
How does Salesforce indexing work internally?
Uses selective indexes (standard/custom) and query optimizer to decide execution path.
24What are polymorphic relationships?
What are polymorphic relationships?
Fields like WhoId/WhatId that reference multiple object types.
25Explain multi-org strategy vs single-org strategy.
Explain multi-org strategy vs single-org strategy.
Single-org simplifies management; multi-org improves isolation but increases integration complexity.
26What is large data volume (LDV) strategy?
What is large data volume (LDV) strategy?
Includes archiving, indexing, query optimization, async processing.
27How do you handle record locking issues?
How do you handle record locking issues?
Use smaller transactions, avoid parent updates, use async processing.
28What is eventual consistency in Salesforce?
What is eventual consistency in Salesforce?
Some async operations (like sharing recalculation) may not reflect immediately.
29What is platform cache?
What is platform cache?
In-memory caching to improve performance for frequently accessed data.
30How do you design multi-currency applications?
How do you design multi-currency applications?
Use advanced currency management and dated exchange rates.
Administration
31What does a Salesforce Administrator do?
What does a Salesforce Administrator do?
An admin manages users, security, and system configuration. They create objects, fields, and automation tools. Admins ensure users have the right access. They also maintain data quality. In real projects, admins are the backbone of system management.
32What is a profile in Salesforce?
What is a profile in Salesforce?
A profile controls what users can do in Salesforce. It defines object permissions, field access, and system permissions. Every user must have one profile. Profiles ensure proper access control. They are essential for security.
33What is the difference between profile and role?
What is the difference between profile and role?
Profiles control permissions, while roles control data visibility. Roles define hierarchy and record access. For example, managers can see their team's data. Profiles define actions, roles define access scope. Both work together.
34What is a permission set?
What is a permission set?
Permission sets extend user permissions without changing profiles. They are useful for temporary or additional access. For example, giving API access to a few users. They provide flexibility. Multiple permission sets can be assigned to one user.
35What is a validation rule?
What is a validation rule?
Validation rules ensure data quality by enforcing conditions. They prevent incorrect data from being saved. For example, making a field mandatory based on criteria. They improve data accuracy. Users get error messages if rules fail.
36What is a workflow rule?
What is a workflow rule?
Workflow rules automate simple actions like email alerts, field updates, and tasks. They trigger based on record changes. Though being retired in favor of Flows, they're still widely used. They simplify repetitive tasks.
37What are record types?
What are record types?
Record types let you offer different page layouts and picklist values for different users. For example, different opportunity layouts for sales vs. partner teams. They customize the user experience per business process.
38What is a page layout?
What is a page layout?
Page layouts control which fields, buttons, and related lists appear on a record page. Admins assign layouts by profile. They help users see only relevant information. Layouts improve productivity.
39What are sharing rules?
What are sharing rules?
Sharing rules extend record access beyond the org-wide defaults. They grant access to groups or roles. Criteria-based rules share records matching specific conditions. Owner-based rules share based on ownership.
40What is a report type in Salesforce?
What is a report type in Salesforce?
Report types define which objects and fields are available in reports. Standard report types come built-in. Custom report types let you combine objects. They are the foundation of reporting.
41What is the difference between OWD and sharing rules?
What is the difference between OWD and sharing rules?
OWD sets the baseline access level for all records. Sharing rules open up access beyond OWD. OWD restricts, sharing rules extend. They work together to control data visibility.
42How do you handle field-level security?
How do you handle field-level security?
Field-level security controls which fields users can see and edit. It's set per profile or permission set. It works alongside page layouts. Even if a field is on the layout, FLS can hide it.
43What is a permission set group?
What is a permission set group?
A collection of permission sets assigned together. It simplifies permission management. You can mute specific permissions within the group. It's recommended over single permission sets for complex setups.
44What are dynamic forms?
What are dynamic forms?
Dynamic forms let you place fields anywhere on Lightning record pages. They replace traditional page layouts for flexibility. You can add visibility rules per field. This provides a highly customized user experience.
45What is the difference between lookup filter and validation rule?
What is the difference between lookup filter and validation rule?
Lookup filters restrict which records can be selected in a lookup field. Validation rules check data on save. Lookup filters work at the UI level, validation rules at the data level.
46How do you implement territory management?
How do you implement territory management?
Territory management assigns accounts to territories based on rules. It supports complex sales structures. Enterprise Territory Management is the latest version. It works alongside the role hierarchy.
47What is data loader and when do you use it?
What is data loader and when do you use it?
Data Loader is a tool for importing, exporting, updating, and deleting large volumes of data. Use it for operations over 50,000 records. It supports CSV files and can be automated via command line.
48What are custom metadata types?
What are custom metadata types?
Custom metadata types store configuration data that can be deployed. Unlike custom settings, they're metadata. They're perfect for app configuration, mappings, and business rules. They can be packaged and deployed.
49How do you set up multi-factor authentication?
How do you set up multi-factor authentication?
MFA adds a second verification step during login. Salesforce requires MFA for all users. Admins configure it via Session Settings. Users can use authenticator apps or security keys.
50What is the difference between custom settings and custom metadata types?
What is the difference between custom settings and custom metadata types?
Custom settings store org-specific data accessible in code. Custom metadata types are deployable configuration. Custom metadata can be packaged; custom settings cannot. Use metadata types for app config, settings for runtime data.
51How do you design a complex approval process?
How do you design a complex approval process?
Map out the business process first. Use multiple steps with different approvers. Add entry criteria and approval actions. Consider parallel approvals and delegated approvers. Test thoroughly with different scenarios.
52How do you handle org-wide email management?
How do you handle org-wide email management?
Configure organization-wide email addresses for different departments. Set up email deliverability settings. Use email relay for custom domains. Monitor email logs for issues.
53What is the Salesforce Shield platform?
What is the Salesforce Shield platform?
Shield provides enhanced security features including Platform Encryption, Event Monitoring, and Field Audit Trail. It's an add-on for compliance-heavy industries. It encrypts data at rest with tenant-specific keys.
54How do you plan a data migration strategy?
How do you plan a data migration strategy?
Assess source data quality. Map fields between systems. Plan the loading order (accounts before contacts). Use sandbox for testing. Validate data after migration with reports.
55What is the impact of enabling person accounts?
What is the impact of enabling person accounts?
Person accounts merge Account and Contact into one record for B2C scenarios. Once enabled, it cannot be disabled. It affects data model, reporting, and integrations significantly.
56A user reports they can't see a field on a record page. How do you troubleshoot?
A user reports they can't see a field on a record page. How do you troubleshoot?
Check field-level security on the user's profile and permission sets first. Then verify the field is on the page layout assigned to their profile/record type. Also check if it's hidden by a dynamic form visibility rule. Finally, ensure the field has a value if it's conditionally displayed.
57You need to prevent duplicate records from being created. What's your approach?
You need to prevent duplicate records from being created. What's your approach?
Use duplicate rules and matching rules for declarative prevention. Add Apex trigger logic for complex scenarios. Consider using external ID fields for integration-created records. Implement fuzzy matching for name-based deduplication.
58A sales team needs different views of the same object. How do you implement this?
A sales team needs different views of the same object. How do you implement this?
Use record types for different page layouts and picklist values. Create role-based list views. Use dynamic forms with visibility rules. Consider Lightning App pages specific to different user groups.
59How would you design a complex approval process with multiple conditional paths?
How would you design a complex approval process with multiple conditional paths?
Map the business process flow first. Use entry criteria to route to different approval steps. Set up parallel approvers where possible. Use initial and final submission actions. Consider using Flow for very complex scenarios that exceed approval process capabilities.
Development
60What is Apex in Salesforce?
What is Apex in Salesforce?
Apex is Salesforce's proprietary programming language. It's similar to Java. Developers use it for complex business logic, triggers, and integrations. It runs on Salesforce servers. It's strongly typed and object-oriented.
61What is a trigger in Salesforce?
What is a trigger in Salesforce?
A trigger is Apex code that runs before or after DML operations. It automates actions on record changes. Triggers can validate data, update related records, or call external services. They're powerful but should follow best practices.
62What is the difference between SOQL and SOSL?
What is the difference between SOQL and SOSL?
SOQL queries one object at a time (like SQL). SOSL searches across multiple objects using text search. SOQL is for precise queries; SOSL is for keyword searches. Both have governor limits.
63What are governor limits?
What are governor limits?
Governor limits are runtime restrictions that prevent any single tenant from monopolizing shared resources. Examples include 100 SOQL queries per transaction, 150 DML statements, and 6 MB heap size. They enforce efficient coding.
64What is a Visualforce page?
What is a Visualforce page?
Visualforce is a markup language for building custom UI pages. It uses a tag-based syntax similar to HTML. It's being replaced by Lightning Web Components but is still widely used. It works with Apex controllers.
65What is Lightning Web Components (LWC)?
What is Lightning Web Components (LWC)?
LWC is Salesforce's modern UI framework built on web standards. It uses JavaScript, HTML, and CSS. It's faster and more efficient than Aura components. LWC is the recommended approach for new development.
66What is a test class in Salesforce?
What is a test class in Salesforce?
Test classes verify that Apex code works correctly. They simulate real scenarios. They are mandatory for deployment; you need at least 75% code coverage. Test classes should cover positive, negative, and bulk scenarios.
67What is the difference between before and after triggers?
What is the difference between before and after triggers?
Before triggers run before a record is saved to the database. They're used for validation and field updates. After triggers run after the record is saved. They're used when you need the record ID or to update related records.
68What is a batch Apex class?
What is a batch Apex class?
Batch Apex processes large volumes of records asynchronously. It breaks data into chunks (default 200 records). It implements Database.Batchable interface. Use it for operations exceeding governor limits.
69What are Salesforce APIs?
What are Salesforce APIs?
Salesforce provides REST API, SOAP API, Bulk API, Streaming API, and Metadata API. They enable integration with external systems. REST API is the most commonly used. Each API has specific use cases and limits.
70What is bulkification in Apex?
What is bulkification in Apex?
Writing code that handles multiple records efficiently instead of one at a time. Use collections (Lists, Sets, Maps) instead of single records. This prevents hitting governor limits. It's a fundamental best practice.
71What is the difference between Apex managed sharing and declarative sharing?
What is the difference between Apex managed sharing and declarative sharing?
Declarative sharing uses OWD, roles, and sharing rules. Apex managed sharing uses code to create share records. Use Apex sharing for complex scenarios that can't be handled declaratively.
72How do you handle callouts in Apex?
How do you handle callouts in Apex?
Use HttpRequest and HttpResponse classes. Mark methods with @future(callout=true) for async callouts. Add remote site settings for the endpoint. Handle timeouts and errors gracefully.
73What is a wrapper class?
What is a wrapper class?
A custom class that combines multiple data types into a single object. Used in Visualforce for displaying complex data. Also useful in LWC for structured data passing.
74What is the difference between @future and Queueable?
What is the difference between @future and Queueable?
@future is simpler but limited: no chaining, no complex types. Queueable supports chaining, complex parameters, and monitoring. Use Queueable for most async needs.
75How do you implement error handling in Apex?
How do you implement error handling in Apex?
Use try-catch-finally blocks. Create custom exception classes. Log errors to custom objects. Use Database.SaveResult for partial DML operations. Always handle null references.
76What is Platform Events?
What is Platform Events?
Platform Events enable event-driven architecture in Salesforce. They publish and subscribe to events in real-time. They work across Apex, Flows, and external systems. They're ideal for loosely coupled integrations.
77What is the difference between static and instance methods?
What is the difference between static and instance methods?
Static methods belong to the class and are called without an instance. Instance methods require an object. Static methods can't access instance variables. Use static for utility methods.
78How do you optimize SOQL queries?
How do you optimize SOQL queries?
Use selective filters on indexed fields. Avoid querying in loops. Use relationship queries instead of multiple queries. Limit fields to what's needed. Use WHERE clauses effectively.
79What is Apex Enterprise Patterns?
What is Apex Enterprise Patterns?
Design patterns for organizing large Apex codebases. Includes Service Layer, Domain Layer, Selector Layer, and Unit of Work. They promote separation of concerns. They make code testable and maintainable.
80How do you design a trigger framework?
How do you design a trigger framework?
Create a handler interface and dispatcher class. One trigger per object that delegates to the handler. Support before/after, insert/update/delete. Include recursion control and bypass mechanisms.
81What is the difference between synchronous and asynchronous Apex?
What is the difference between synchronous and asynchronous Apex?
Synchronous runs immediately in the user's context with standard limits. Asynchronous runs in background with higher limits. Types include @future, Queueable, Batch, and Scheduled. Choose based on volume and timing needs.
82How do you handle large data volumes in Apex?
How do you handle large data volumes in Apex?
Use Batch Apex for processing. Implement selective queries. Use Platform Cache for frequently accessed data. Consider async patterns. Monitor heap size and query performance.
83What is Salesforce DX and how does it change development?
What is Salesforce DX and how does it change development?
Salesforce DX is a modern development experience. It uses source-driven development with scratch orgs. CLI-based tooling enables automation. It integrates with Git for version control. It's the recommended development approach.
84You need to update 5 million records. What approach do you take?
You need to update 5 million records. What approach do you take?
Use Batch Apex with an appropriate batch size (200-2000). Consider using the Bulk API if coming from external system. Run during off-peak hours. Monitor for governor limits. Use Database.Stateful if you need to track state across batches.
85Your Apex trigger is hitting governor limits. How do you fix it?
Your Apex trigger is hitting governor limits. How do you fix it?
Move SOQL queries and DML operations outside of loops. Use collections (Maps, Lists, Sets) for data processing. Implement a trigger handler pattern. Consider moving to asynchronous processing for heavy operations. Profile the code to identify bottlenecks.
86What is the Singleton design pattern in Apex and when do you use it?
What is the Singleton design pattern in Apex and when do you use it?
CONCEPT ANSWER The Singleton pattern ensures that a class has only one instance throughout the entire transaction and provides a global point of access to it. We implement it using a private static variable that holds the instance. The constructor is private so no external code can instantiate it directly. A public static getInstance() method checks if the instance is null: creates it if so, returns it otherwise.
87What is the Trigger Handler pattern and why is it important?
What is the Trigger Handler pattern and why is it important?
CONCEPT ANSWER The Trigger Handler pattern moves all business logic out of the trigger file and into a dedicated handler class. The trigger itself becomes a thin dispatcher. Without this pattern triggers become large, unmaintainable files where multiple developers cause merge conflicts. Logic cannot be unit tested without firing DML. The same logic cannot be reused from other contexts like REST APIs or batch jobs. The pattern: create OpportunityTriggerHandler with static or instance methods for each trigger event; beforeInsert, afterUpdate etc.
88What is the Service Layer pattern and why should business logic not live in the trigger handler?
What is the Service Layer pattern and why should business logic not live in the trigger handler?
CONCEPT ANSWER The Service Layer contains all business logic for a domain, for example OpportunityService, completely independent of how it was invoked. The trigger handler knows about trigger context. The service layer does not. Service methods are context-agnostic; they accept data, execute logic, return results. They do not know whether they were called from a trigger, an LWC, a REST API, or a batch job. This is critical in enterprise applications where the same business rule is triggered from multiple entry points.
89What is the Selector (Repository) pattern? Why should SOQL not be written directly in service classes?
What is the Selector (Repository) pattern? Why should SOQL not be written directly in service classes?
BEST PRACTICE ANSWER The Selector pattern creates a dedicated class responsible for all SOQL queries for a specific object: OpportunitySelector, ContactSelector etc. Without a selector, the same query is scattered across 10 service classes. Adding a new field or enforcing FLS requires updating 10 locations. One missed location becomes a bug or security vulnerability. With a Selector there is one place for all queries. Security (WITH USER_MODE) is applied consistently in one place. Queries are named descriptively making code self-documenting.
90What is trigger recursion and how do you prevent it?
What is trigger recursion and how do you prevent it?
CONCEPT ANSWER Trigger recursion occurs when a trigger fires, performs DML that updates a record, and that update re-fires the same trigger: creating an infinite loop until governor limits are hit. Most common cause: an after-update trigger that calculates something and updates the same object it fired on. Prevention 1: Static Boolean flag: a static Boolean in a utility class holds its value for the entire transaction. Set it to true on first entry, skip execution if already true. Prevention 2: Static Set of Ids: more granular than boolean. Track which Ids have been processed.
91What are the 6 core best practices for writing Apex triggers?
What are the 6 core best practices for writing Apex triggers?
BEST PRACTICE ANSWER One: One trigger per object. Multiple triggers fire in unpredictable order. Consolidate all logic into one trigger per object. Two: Thin trigger, fat handler. No business logic inside the trigger file. Trigger only calls a handler class. Three: Always bulkify. Never assume a trigger fires for one record. Always treat Trigger.new as a list. No SOQL or DML inside loops. Four: Correct trigger events. Use before insert/update for field manipulation: record not yet saved, no DML needed. Use after insert/update for operations needing record Ids or related object updates.
92Mass import of 500 Contacts via Data Loader hits governor limit errors. The trigger creates a Task per Contact. How do you fix it?
Mass import of 500 Contacts via Data Loader hits governor limit errors. The trigger creates a Task per Contact. How do you fix it?
The root cause is DML inside a loop. For 500 contacts the trigger is calling insert task 500 times: the DML limit is 150. Immediate fix: collect all Task records in a List inside the loop and do one bulk insert after the loop. Also check for @future calls per record: the limit is 50 per transaction. 500 records will fail. Switch to Queueable with batching. Check for any workflow rules or process builders on Contact that fire additional DML; they share the same transaction limits.
93What are the most important governor limits every Apex developer must know?
What are the most important governor limits every Apex developer must know?
CONCEPT ANSWER Salesforce enforces runtime limits to prevent any single tenant from monopolizing shared resources. SOQL: 100 synchronous queries per transaction, 200 async. Query result rows: 50,000. Heap: 6 MB sync, 12 MB async. DML: 150 DML statements, 10,000 DML rows per transaction. CPU: 10,000 ms synchronous, 60,000 ms asynchronous. Callouts: 100 callouts, 120 seconds total callout time per transaction. Async: 50 @future calls per transaction. 250,000 async jobs in queue daily. The most commonly hit in production: SOQL in loops (100 limit) and DML in loops (150 limit).
94Describe the correct bulkification pattern in Apex with a practical example?
Describe the correct bulkification pattern in Apex with a practical example?
BEST PRACTICE ANSWER Bulkification means writing code that processes 1 or 10,000 records with equal correctness and efficiency. Pattern: Collect → Query → Map → Process in memory → DML. Step 1 Collect: gather all foreign-key Ids from the input list into a Set before any SOQL. Step 2 Query: one SOQL with IN :idSet; never query inside a loop. Step 3 Map: store query results in Map<Id,SObject> for O(1) lookup. Step 4 Process: iterate the input list, use map.get() to find related data, build output collections.
95Your batch job processes 1 million records and hits heap size errors in production. How do you diagnose and fix it?
Your batch job processes 1 million records and hits heap size errors in production. How do you diagnose and fix it?
Heap limit is 12 MB for async Apex including batch. 1 million records with broad field selection fills heap quickly. Fix 1: Reduce batch scope size. Default is 200; set it to 50 or even 10 using Database.executeBatch(job, 50). Fewer records in memory per execute() call. Fix 2: Query only necessary fields. SELECT Id, Status__c instead of SELECT all fields reduces per-record heap footprint significantly. Fix 3: Avoid accumulating data across execute() calls. Instance variables that grow between batches cause heap to increase with each scope. Process and clear within each execute().
96What is CPU time governor limit and what patterns cause it to spike?
What is CPU time governor limit and what patterns cause it to spike?
BEST PRACTICE ANSWER CPU time limit is 10,000 ms synchronous and 60,000 ms asynchronous. Salesforce measures CPU consumed by Apex code execution only: time waiting for SOQL results or callout responses does not count. Pattern 1: Nested loops: O(n²) complexity. If a trigger processes 200 records and for each record loops through another 200-item list, that is 40,000 iterations. Fix: replace inner loops with Map lookups; O(1) per access. Pattern 2: String operations in loops: String concatenation creates new String objects each iteration because Strings are immutable.
97What are the 6 most common SOQL anti-patterns and how do you fix each?
What are the 6 most common SOQL anti-patterns and how do you fix each?
CONCEPT ANSWER 1. SOQL in a loop: the most common mistake. Fix: collect Ids into Set, one SOQL with IN clause, store in Map. 2. Selecting every field (for example FIELDS(ALL) in tools): querying all fields when 2-3 are needed. Wastes heap. Fix: SELECT only fields actually used. 3. Missing WHERE on large objects: querying millions of rows without a filter. Fix: always filter on indexed fields. 4. Non-selective queries: WHERE clause uses a non-indexed field on a large object. Salesforce may throw a row count error. Fix: use indexed fields (Id, Name, external Id, lookup fields), add LIMIT, or request a custom index. 5.
98What is the difference between static SOQL and dynamic SOQL (Database.query)? When is each appropriate?
What is the difference between static SOQL and dynamic SOQL (Database.query)? When is each appropriate?
BEST PRACTICE ANSWER Static SOQL is written inline with square brackets and validated at compile time. Salesforce checks field names, object names, and syntax during compilation. This is the default choice: safer, cleaner, and easier to read. Dynamic SOQL uses Database.query() with a String built at runtime. Only validated at runtime. Use it when fields, objects, or conditions must be determined dynamically: user-selectable columns, optional search filters, multi-object queries.
99What is the difference between List, Map, and Set for storing SOQL results? When do you use each?
What is the difference between List, Map, and Set for storing SOQL results? When do you use each?
CONCEPT ANSWER List<SObject> is the default: ordered, allows duplicates. Use it for sequential processing and DML operations. DML accepts Lists not Sets. Map<Id,SObject> wraps SOQL results in new Map<Id,SObject>([...]). Provides O(1) lookup by Id. Use it whenever you need to find a record by Id inside a loop: the most common trigger pattern. Set<Id> stores unique Ids only. Use it to collect parent Ids before a SOQL query (auto-deduplicates), to check membership with contains(), or to deduplicate Id lists. O(1) lookup.
100What is SOQL for loops and when should you use them?
What is SOQL for loops and when should you use them?
CONCEPT ANSWER A SOQL for loop: for(SObject s : [SELECT...]): processes query results in chunks of 200 records at a time instead of loading all results into heap at once. Each chunk is automatically discarded from memory after processing. Use SOQL for loops when querying large result sets that would exceed heap size if loaded into a List at once. They are the Apex equivalent of streaming a query. Regular List<SObject> = [SELECT...] loads ALL results into heap immediately. For 50,000 records this can easily exceed the 6 MB heap limit.
101What is the difference between DmlException, QueryException, and AuraHandledException?
What is the difference between DmlException, QueryException, and AuraHandledException?
CONCEPT ANSWER DmlException is thrown when a DML operation fails: required field missing, validation rule violation, record locked, duplicate blocked. It exposes getDmlMessage(i) and getDmlIndex(i) to get per-record error details. QueryException is thrown when a SOQL query expecting one result returns zero or more than one: the too many rows error. Fix: always query into a List and check size() before accessing index 0. AuraHandledException is special: when thrown in an @AuraEnabled method it propagates the message cleanly to LWC as error.body.message.
102How do you create and use custom exceptions in Apex? Why are they better than generic Exception?
How do you create and use custom exceptions in Apex? Why are they better than generic Exception?
CONCEPT ANSWER Custom exceptions extend the Exception class. Convention: suffix with Exception. They can be inner classes or standalone classes. Advantage of custom exceptions: specificity. A catch(Exception e) cannot distinguish a business rule violation from a system error. Custom exceptions allow different handling per error type: retry for PaymentException, user message for ValidationException, admin alert for SystemException. Custom exceptions can carry extra properties, error codes, record Ids, lists of validation messages, that generic exceptions cannot.
103What is the difference between try-catch-finally and Database.Savepoint? When do you use each?
What is the difference between try-catch-finally and Database.Savepoint? When do you use each?
BEST PRACTICE ANSWER Try-catch-finally controls exception flow. The catch block runs on exception. The finally block always runs: perfect for cleanup like resetting loading states or flushing logs. It does NOT roll back DML that already committed. Database.Savepoint is for transaction rollback; it undoes all DML performed since the savepoint was set. Essential when multiple DML steps must all succeed or all fail together: atomicity. Use try-catch-finally for: error handling, resource cleanup, loading state management, translating exceptions to user messages.
104You process records in a loop where one record's DML failure must not stop others from processing. How do you implement this?
You process records in a loop where one record's DML failure must not stop others from processing. How do you implement this?
Standard try-catch inside a loop rolls back the whole transaction on failure, not what we want. The solution is Database.insert/update/upsert with allOrNothing=false. This processes each record independently. Successes commit, failures do not, but processing continues for all records. The method returns List<Database.SaveResult> with one result per record. We iterate results, check isSuccess(), and collect errors from getErrors() for failed records. We log all failures to a custom Error_Log__c object with record Id and error message, allowing ops teams to review and retry failed records.
105How do you implement a centralized error logging framework in Apex?
How do you implement a centralized error logging framework in Apex?
BEST PRACTICE ANSWER A centralized error logging framework ensures all exceptions across the org are captured consistently, stored durably, and queryable for operations teams. Create a singleton Logger class (using Singleton pattern) that accumulates log entries in a List during the transaction. Using a singleton prevents multiple SOQL/DML calls for logging. At the end of critical operations, or in finally blocks, call Logger.getInstance().flush() which does one bulk insert of all accumulated logs. Log levels: INFO, WARNING, ERROR, CRITICAL.
106What is the difference between CRUD, FLS, and Sharing in Salesforce? How does Apex handle each by default?
What is the difference between CRUD, FLS, and Sharing in Salesforce? How does Apex handle each by default?
CONCEPT ANSWER CRUD controls whether a user can perform object-level operations: Create, Read, Update, Delete. Defined on profiles and permission sets. FLS controls which fields on an object a user can view or edit. Also defined on profiles and permission sets. Sharing controls which records a user can see: record-level access. Controlled through OWD, sharing rules, role hierarchy, and manual sharing. By default Apex runs in system context and ignores all three. An Apex class can read any field, any object, and any record regardless of the running user's permissions.
107What is the difference between with sharing, without sharing, and inherited sharing? What are the risks of each?
What is the difference between with sharing, without sharing, and inherited sharing? What are the risks of each?
BEST PRACTICE ANSWER with sharing enforces the running user's sharing rules. Records outside the user's access are excluded from SOQL. Use this for all @AuraEnabled classes and REST resources: safest default for user-facing code. without sharing ignores sharing rules. All records are accessible regardless of user permissions. Use ONLY for backend automation: batch jobs, scheduled jobs, admin-only service classes. Never use in user-triggered code: data exposure risk. inherited sharing uses the sharing context of the calling code. If called from a with sharing class it enforces sharing.
108A user sees data in LWC that they should not have access to. The Apex class is marked with sharing. What else could cause this?
A user sees data in LWC that they should not have access to. The Apex class is marked with sharing. What else could cause this?
with sharing enforces record-level sharing rules but does NOT enforce FLS. The user can see all fields on their accessible records even if FLS restricts certain fields. Cause 1: FLS not enforced: SOQL returns restricted fields because with sharing does not check FLS. Fix: add WITH USER_MODE to SOQL or call Security.stripInaccessible(AccessType.READABLE, results) before returning data.
109What is Apex Managed Sharing? When would you use it over standard sharing rules?
What is Apex Managed Sharing? When would you use it over standard sharing rules?
CONCEPT ANSWER Apex Managed Sharing allows Apex code to programmatically create, update, or delete sharing records: the Share objects like AccountShare, OpportunityShare, or custom object Share records. Use Apex Managed Sharing when sharing requirements are too dynamic or complex for declarative sharing rules. Examples: share a record with a specific user only after a specific approval step completes, share a record with a team that is stored in a custom object relationship rather than roles, or grant temporary time-based access.
110What are the differences between List, Set, and Map in Apex? When do you choose each?
What are the differences between List, Set, and Map in Apex? When do you choose each?
CONCEPT ANSWER List: ordered, allows duplicates, index-based access. Use for sequential processing, DML operations (DML requires List), maintaining order, or iterating results. Set: unordered, unique elements, no index. Use for collecting unique Ids before SOQL, checking membership with contains(): O(1), or deduplicating values. Map: key-value pairs, unique keys, O(1) lookup by key. Use whenever you need to find a record by Id inside a loop: the most critical performance pattern in Salesforce.
111What is the difference between shallow copy and deep copy for Apex collections? Why does it matter?
What is the difference between shallow copy and deep copy for Apex collections? Why does it matter?
BEST PRACTICE ANSWER Shallow copy copies the reference: both variables point to the same object in memory. Changing one changes the other. Deep copy creates a new independent copy. Changing the copy does not affect the original. In Apex, List<String> copy = original is a shallow copy: same list object. new List<String>(original) creates a new list with the same elements: a deep copy for primitives. For SObjects, even new List<Account>(original) gives a new list but the Account objects inside still share references.
113What is the best way to remove duplicates from a List of custom objects in Apex?
What is the best way to remove duplicates from a List of custom objects in Apex?
BEST PRACTICE ANSWER Removing duplicates from a List<String> or List<Id> is simple: add to a Set which auto-deduplicates, then convert back to List. For List<SObject> or custom objects it is more complex because Sets use reference equality for objects: two different Account instances with the same Id are not considered equal by a Set. Approach 1 for SObjects: use a Map<Id,SObject>. Iterating the list and putting each record into the map by Id automatically deduplicates: later entries overwrite earlier ones with the same key. Then call map.values() for the deduplicated List.
114What are the best practices for writing Apex test classes?
What are the best practices for writing Apex test classes?
CONCEPT ANSWER 1. Use @testSetup for shared test data: data inserted in @testSetup is rolled back after all tests in the class run, not after each test, so it is created once and available to all test methods. 2. Test bulk behavior: always test with 200 records, not just 1. Triggers and service classes must work for bulk operations. 3. Assert specific values: do not just assert that no exception was thrown. Assert exact field values, record counts, and state changes. 4.
115What is the difference between unit tests and integration tests in Apex? How do you write true unit tests?
What is the difference between unit tests and integration tests in Apex? How do you write true unit tests?
BEST PRACTICE ANSWER Integration tests test the full stack: trigger fires, handler runs, service is called, DML executes, related records update. Most Salesforce test classes are integration tests; they insert real data and rely on the full chain executing. Unit tests test one method or class in complete isolation: all dependencies are replaced with mocks or stubs. The method under test is the only real code running. True Apex unit tests: use Stub API (Test.createStub) or dependency injection to replace real SOQL calls, DML operations, and external callouts with controlled fakes.
116Your test class has 75% code coverage but your deployment fails saying you need 75% overall org coverage. What could be wrong?
Your test class has 75% code coverage but your deployment fails saying you need 75% overall org coverage. What could be wrong?
The 75% requirement is not per-class; it is the aggregate coverage across ALL Apex classes and triggers in the org. Your individual test might cover 75% of its target class, but other classes in the org with low or zero coverage pull the overall percentage below 75%. Step 1: check the Apex Test Results in Setup to see which classes have the lowest coverage. Zero-coverage classes are the biggest problem. Step 2: check for classes that cannot be covered; inner classes, abstract base classes, or deprecated code. These still count in the denominator.
117How do you test a method that calls an external API AND performs DML AND sends an email in the same transaction?
How do you test a method that calls an external API AND performs DML AND sends an email in the same transaction?
This test has three dependencies to mock: HTTP callout, DML (database), and email sending. Each needs a different approach. Callout: use Test.setMock(HttpCalloutMock.class, new MockCallout()) before Test.startTest(). The mock responds with controlled data. DML: DML in tests is real; it executes against the test database which is rolled back after each test. We just need to create test data in @testSetup or directly in the test method. Email: wrap the email sending in a check for Test.isRunningTest(): if true, skip actual email dispatch and log to a list instead.
118What is System.runAs() in Apex tests and when must you use it?
What is System.runAs() in Apex tests and when must you use it?
BEST PRACTICE ANSWER System.runAs() executes a block of test code as a specified user, enforcing that user's permissions, profile, role, and sharing settings. By default test methods run as the running test user, usually a System Admin, which bypasses all permission and sharing checks. This means tests pass for admins but fail for regular users in production. Use System.runAs() for: testing with sharing enforcement; verifying that a user in a specific role sees only their records. Testing permission-based UI: a button that should only show for users with a custom permission.
119What are the four types of async Apex? Give a one-line use case for each?
What are the four types of async Apex? Give a one-line use case for each?
CONCEPT ANSWER @future method: simplest async. Use for single callouts from triggers or mixed DML operations. Limitation: cannot chain, cannot monitor, only accepts primitives. Queueable interface: powerful async with job Id for monitoring. Use for sequential async processing, chaining jobs, passing SObjects, or callouts with complex data. Supports Database.AllowsCallouts. Batch Apex: for processing large volumes of records; up to 50 million. Divided into scope-sized chunks. Use for data migration, mass updates, scheduled cleanup, or any process that exceeds transaction limits.
120A scheduled batch job runs at 2 AM and processes 50,000 records. Recently it started failing with UNABLE_TO_LOCK_ROW errors. What is happening and how do you fix it?
A scheduled batch job runs at 2 AM and processes 50,000 records. Recently it started failing with UNABLE_TO_LOCK_ROW errors. What is happening and how do you fix it?
UNABLE_TO_LOCK_ROW means a DML operation is trying to update a record that another transaction already has locked. At 2 AM if another process is also running, another batch, a trigger, a user saving a record, or another scheduled job, they compete for the same records. Fix 1: stagger job schedules. If multiple batch jobs run at the same time and touch the same objects, offset their start times by 15-30 minutes. Fix 2: reduce batch scope size. Smaller batches lock fewer records at a time, reducing the window of contention. Change from executeBatch(job, 200) to executeBatch(job, 50).
Integration
121What are the main integration patterns in Salesforce?
What are the main integration patterns in Salesforce?
Request-Reply (real-time sync), Fire-and-Forget (async), Batch Data Sync, and Remote Call-In. Choose based on data volume, timing, and reliability needs. Each pattern has specific implementation approaches.
122What is REST API in Salesforce?
What is REST API in Salesforce?
REST API provides a simple way to interact with Salesforce data over HTTP. It uses JSON or XML. It supports CRUD operations on records. It's the most commonly used API for integrations.
123What is connected app?
What is connected app?
A connected app configures how an external application integrates with Salesforce. It handles OAuth authentication. It defines permissions and access policies. It's required for API integrations.
124What is middleware and why is it used?
What is middleware and why is it used?
Middleware sits between Salesforce and external systems to handle data transformation, routing, and error handling. Tools like MuleSoft, Dell Boomi, and Informatica are common. It simplifies complex integrations.
125What is Salesforce Connect?
What is Salesforce Connect?
Salesforce Connect accesses external data in real-time without copying it into Salesforce. It uses External Objects and OData adapters. It's ideal for large datasets that change frequently.
126What is the difference between inbound and outbound integration?
What is the difference between inbound and outbound integration?
Inbound: external systems push data into Salesforce. Outbound: Salesforce sends data to external systems. Both use APIs, webhooks, or middleware. The direction determines the pattern and tools used.
127How do you handle authentication in integrations?
How do you handle authentication in integrations?
OAuth 2.0 is the standard for API authentication. Named Credentials store credentials securely. JWT Bearer flow works for server-to-server. Session-based auth is used for UI integrations.
128What is Change Data Capture?
What is Change Data Capture?
CDC publishes real-time change events when records are created, updated, deleted, or undeleted. External systems can subscribe to these events. It's efficient for near real-time data sync.
129How do you handle error handling in integrations?
How do you handle error handling in integrations?
Implement retry logic for transient failures. Log errors to custom objects. Use dead letter queues for failed messages. Set up monitoring and alerts. Design idempotent operations.
130What is the Bulk API and when do you use it?
What is the Bulk API and when do you use it?
Bulk API processes large data sets asynchronously. It's optimized for loading or deleting thousands to millions of records. Use it when Data Loader or REST API can't handle the volume.
131How do you design an enterprise integration architecture?
How do you design an enterprise integration architecture?
Define integration patterns per use case. Use an API-led approach with system, process, and experience layers. Implement centralized error handling and monitoring. Document data mappings and SLAs.
132What is MuleSoft and how does it integrate with Salesforce?
What is MuleSoft and how does it integrate with Salesforce?
MuleSoft is Salesforce's integration platform. It provides Anypoint Platform for building APIs. It has native Salesforce connectors. It enables API-led connectivity across systems.
133How do you handle real-time vs near-real-time integration?
How do you handle real-time vs near-real-time integration?
Real-time uses synchronous APIs or Platform Events. Near-real-time uses CDC or outbound messages. Consider latency, volume, and reliability requirements. Real-time has tighter governor limits.
134An integration is intermittently failing. How do you investigate?
An integration is intermittently failing. How do you investigate?
Check debug logs for error details. Review the integration user's API usage. Verify endpoint availability and response times. Check for governor limit violations. Implement retry logic and error logging if not already in place.
135You need to sync data bidirectionally between Salesforce and an ERP system. How?
You need to sync data bidirectionally between Salesforce and an ERP system. How?
Define the system of record for each field. Use Change Data Capture or Platform Events for real-time sync. Implement conflict resolution logic. Use external IDs for record matching. Consider middleware like MuleSoft for transformation and orchestration.
136How do you make a REST API callout from Apex?
How do you make a REST API callout from Apex?
[BASIC] ANSWER We use the HttpRequest, Http, and HttpResponse classes in Apex. First we create an HttpRequest object and set the endpoint, method (GET/POST), headers, and body. Then we create an Http object and call send() passing the request. This returns an HttpResponse with the status code and body. In our Razorpay integration we set the endpoint using Named Credential syntax as callout:Razorpay/v1/orders, set method as POST, set Content-Type header as application/json, serialize our request object as JSON and set it as the body.
137What is the difference between GET and POST in REST API?
What is the difference between GET and POST in REST API?
[BASIC] ANSWER GET is used to retrieve or fetch data from an external system. It does not have a request body: parameters are passed in the URL itself. For example, fetching order status from Razorpay by passing order ID in the URL. POST is used to create or send data to an external system. It has a request body where we send JSON or XML data. For example, creating a new payment order in Razorpay; we send amount, currency, and receipt in the POST body. In our Razorpay integration we use POST to create the order because we are sending data to Razorpay to create a new record on their system.
138How do you parse a JSON response in Apex?
How do you parse a JSON response in Apex?
[BASIC] ANSWER There are two ways to parse JSON in Apex. First way is using JSON.deserializeUntyped(); this gives us a Map of String to Object. We then cast individual values to the expected type like String or Integer. This is flexible but requires manual casting. Second way is using JSON.deserialize() with a specific Apex wrapper class; we define a class with matching field names and Salesforce automatically maps the JSON fields to class properties. This is cleaner and type-safe.
139Can you make a callout directly from a trigger? Why or why not?
Can you make a callout directly from a trigger? Why or why not?
No, we cannot make a direct callout from a trigger. Salesforce does not allow synchronous callouts from triggers because triggers run inside a database transaction. If the callout is made synchronously, the database transaction would be held open waiting for the external system to respond; this can cause lock issues and timeouts. The solution is to use an @future method with callout=true annotation, or a Queueable class that implements the Database.AllowsCallouts interface. These run asynchronously after the transaction is committed.
140What is callout timeout and how do you handle it?
What is callout timeout and how do you handle it?
Callout timeout is the maximum time Salesforce waits for a response from an external system. The default timeout is 10 seconds and the maximum allowed is 120 seconds. We set it using req.setTimeout() in milliseconds. If the external system does not respond within the timeout, Salesforce throws a CalloutException with a timeout message. To handle this properly, we wrap our callout in a try-catch block catching CalloutException specifically. In the catch block we log the error, update the record with a failure status, and optionally retry using a Queueable job.
141What is the maximum number of callouts allowed in a single transaction and how do you handle bulk scenarios?
What is the maximum number of callouts allowed in a single transaction and how do you handle bulk scenarios?
Salesforce allows a maximum of 100 callouts per transaction; this is a governor limit. Each call to http.send() counts as one callout. In bulk scenarios, for example if 200 Opportunities are closed won at the same time, we cannot make 200 callouts in one transaction. The solution is to use @future methods which run per record, or better a Queueable chain where each job processes one record and chains the next job. There is also a daily limit of 250,000 callouts per org.
142What is an @future method and when do you use it?
What is an @future method and when do you use it?
[BASIC] ANSWER An @future method is an asynchronous Apex method that runs in a separate thread after the current transaction is committed. We annotate it with @future and it must be static and return void. We use @future in three main scenarios: first, when we need to make a callout from a trigger (we add callout=true to the annotation). Second, when we need to avoid mixed DML operations. Third, when we want to offload heavy processing so it does not slow down the current transaction. The limitations of @future are that it cannot take SObject as a parameter, only primitive types.
143Why can @future methods not accept SObject parameters?
Why can @future methods not accept SObject parameters?
[BASIC] ANSWER @future methods run asynchronously in a separate transaction that executes later. If we passed an SObject directly, by the time the @future method runs, the SObject data in memory could be stale or different from what is actually in the database. To avoid this inconsistency, Salesforce restricts @future parameters to primitives only, like String, Integer, Id, or collections of primitives like List of Id. The correct pattern is to pass the record Id as a parameter and then re-query the latest data inside the @future method itself.
144What is the difference between @future, Queueable, and Batch Apex? When would you use each?
What is the difference between @future, Queueable, and Batch Apex? When would you use each?
@future is the simplest: fire and forget. Use it for quick async operations like single callouts from triggers or mixed DML fixes. Limitation is you cannot chain jobs or monitor them. Queueable is more powerful than @future. It can accept SObject parameters, can be chained: meaning one Queueable can enqueue another, and you get a job ID to monitor. Also supports callouts with Database.AllowsCallouts interface. Batch Apex is for processing large volumes of records: up to 50 million records. It processes records in chunks called scope.
145How do you test @future methods in test classes?
How do you test @future methods in test classes?
@future methods do not execute during a test until we call Test.stopTest(). This is because they are asynchronous: Salesforce holds them in a queue. The correct pattern is to set up test data, call Test.startTest() which resets governor limits, perform the action that triggers the @future method, then call Test.stopTest(). When Test.stopTest() is called, Salesforce executes all queued async operations synchronously before returning. We also need to use Test.setMock() with HttpCalloutMock before the Test.startTest() block to mock the external API response.
146What happens if an @future method fails? How do you handle retries?
What happens if an @future method fails? How do you handle retries?
If an @future method throws an unhandled exception, Salesforce marks the job as failed and it does not retry automatically. The failure is logged in Apex Jobs in Setup but no notification is sent to users. To handle failures properly we should always wrap the entire @future method body in a try-catch block. In the catch block we should log the error to a custom Error Log object, update the record with a failure status, and optionally send an email notification to an admin.
147Can you explain what OAuth 2.0 is and how it works?
Can you explain what OAuth 2.0 is and how it works?
[BASIC] ANSWER OAuth 2.0 is an authorization framework that allows an application to access resources on behalf of a user without sharing the user's password. Instead of credentials, it uses tokens. The basic flow: our application first requests an access token from the authorization server by providing a Client ID and Client Secret. The authorization server validates these and returns an access token with an expiry time. We then use this access token in the Authorization header of every API request as a Bearer token. When the token expires we request a new one using a refresh token.
148How do you configure OAuth 2.0 in Salesforce using Named Credentials?
How do you configure OAuth 2.0 in Salesforce using Named Credentials?
To configure OAuth 2.0 in Salesforce we need three things: an Auth Provider, an External Credential, and a Named Credential. First we create an Auth Provider in Setup. We select the provider type, for example Custom for PayPal. We enter the Client ID, Client Secret, and the token endpoint URL. Salesforce uses this to fetch and refresh access tokens. Second we create an External Credential and set the Authentication Protocol to OAuth 2.0. We link it to the Auth Provider. We also add a Principal and map it to the appropriate Permission Set.
149What is the difference between Client Credentials flow and Authorization Code flow?
What is the difference between Client Credentials flow and Authorization Code flow?
Client Credentials flow is for machine-to-machine communication where no user is involved. The application authenticates directly using its own Client ID and Secret. There is no login screen or user consent step. This is used for server-side integrations like our Salesforce to PayPal integration. Authorization Code flow is for user-facing applications where the actual user needs to authenticate and grant permission. The user is redirected to the external system's login page, they log in and approve access, and then the application exchanges an authorization code for an access token.
150What happens when an OAuth access token expires during a callout? How does Salesforce handle it?
What happens when an OAuth access token expires during a callout? How does Salesforce handle it?
When an OAuth access token expires, the external system returns a 401 Unauthorized response. If we are using Named Credentials with an Auth Provider, Salesforce handles this automatically. When it receives a 401, it uses the refresh token to request a new access token, then retries the original callout with the new token: completely transparent to our Apex code. However if we are managing tokens manually in Apex, storing them in Custom Settings or Custom Metadata, we need to handle expiry ourselves.
151What is HttpCalloutMock and why do we need it in test classes?
What is HttpCalloutMock and why do we need it in test classes?
[BASIC] ANSWER HttpCalloutMock is an interface in Salesforce that we implement to simulate HTTP callout responses in test classes. Salesforce does not allow actual HTTP callouts during test execution: if we try to make a real callout in a test, it throws an exception. We create a class that implements HttpCalloutMock and override the respond() method. In this method we construct and return a fake HttpResponse with the status code and body we want to simulate. Then in our test method we call Test.setMock() to register our mock class before executing the callout code.
153How do you handle errors in Apex callouts? What are best practices?
How do you handle errors in Apex callouts? What are best practices?
There are multiple types of errors we need to handle in callouts. First, network or system errors; we catch CalloutException for timeouts and connection failures. Second, HTTP error responses; we check the status code. 200 means success. 400 means bad request. 401 means unauthorized. 404 means not found. 500 means external system error. Third, JSON parsing errors: if the response body is not valid JSON, JSON.deserializeUntyped() throws an exception, so we wrap parsing in a try-catch too. Best practices: always use try-catch with specific exception types.
154What is the difference between CalloutException and System.Exception?
What is the difference between CalloutException and System.Exception?
CalloutException is a specific exception thrown by Salesforce when there is a network-level problem with the callout itself: things like timeout, connection refused, SSL handshake failure, or the callout limit being exceeded. It means the request never got a proper response from the server. System.Exception or generic Exception catches everything else, like null pointer errors, JSON parsing failures, type cast errors, or any other unexpected runtime error in our code.
155How would you design a retry mechanism for failed callouts in Salesforce?
How would you design a retry mechanism for failed callouts in Salesforce?
A retry mechanism needs to be asynchronous because we cannot do a synchronous loop of retries inside a transaction; we would hit timeout limits. The best design uses a Queueable chain with a retry count. We create a Queueable class that accepts the record Id and a retry count. Inside execute() we attempt the callout. If it fails and retry count is less than max retries, say 3, we enqueue a new instance of the same Queueable with retry count plus one. We also need a custom field on the record to track retry count and last error for monitoring.
LWC
156What is Lightning Web Components (LWC)?
What is Lightning Web Components (LWC)?
LWC is Salesforce's modern component framework built on web standards. It uses native JavaScript, HTML templates, and CSS. It's faster than Aura components. It's the recommended framework for new Salesforce UI development.
157What is the difference between Aura and LWC?
What is the difference between Aura and LWC?
LWC uses native web standards while Aura uses a custom framework. LWC is more performant. Aura has more lifecycle events. LWC can be used inside Aura but not vice versa. New development should use LWC.
158What is the Lightning App Builder?
What is the Lightning App Builder?
A drag-and-drop tool for building Lightning pages. Admins can customize record pages, home pages, and app pages. It supports standard and custom components. No coding required.
159What are Lightning record pages?
What are Lightning record pages?
Custom page layouts built in Lightning App Builder. They can contain standard and custom components. They're assigned by app, record type, or profile. They replace Visualforce page overrides.
160What is the wire service in LWC?
What is the wire service in LWC?
The wire service reactively provisions data to LWC components. It connects to Salesforce data via wire adapters. It automatically refreshes when data changes. It's the recommended way to read data in LWC.
161How do you communicate between LWC components?
How do you communicate between LWC components?
Parent to child: use public properties (@api). Child to parent: use custom events. Unrelated components: use Lightning Message Service (LMS) or pub-sub pattern.
162What is Lightning Data Service?
What is Lightning Data Service?
LDS provides a centralized data cache for Lightning components. It handles CRUD operations without Apex. It ensures data consistency across components. It respects sharing and FLS automatically.
164What is Lightning Message Service?
What is Lightning Message Service?
LMS enables communication between LWC, Aura, and Visualforce components on the same page. It uses message channels defined in metadata. It's the recommended cross-technology communication method.
165How do you make LWC components reusable?
How do you make LWC components reusable?
Use @api properties for configuration. Design components with single responsibility. Create base components that others extend. Use slots for content projection. Document the component API.
166What are Lightning Web Security and Locker Service?
What are Lightning Web Security and Locker Service?
Security frameworks that isolate components in namespaces. LWS is the newer, more permissive replacement for Locker. They prevent components from accessing each other's DOM. They enforce secure coding practices.
167How do you optimize LWC performance?
How do you optimize LWC performance?
Minimize wire calls and Apex invocations. Use lazy loading for heavy components. Cache data client-side when appropriate. Avoid unnecessary re-renders. Use if:true directives to conditionally render.
168What are the lifecycle hooks in LWC and in what order do they execute?
What are the lifecycle hooks in LWC and in what order do they execute?
LWC has five main lifecycle hooks that execute in a specific order. constructor() fires first when the component is created. At this point the component is not yet in the DOM and we cannot access child elements. We use it for initializing variables. connectedCallback() fires when the component is inserted into the DOM. This is where we typically do setup work like subscribing to message channels or fetching initial data that does not need reactive properties. renderedCallback() fires after every render of the component: both the initial render and every subsequent re-render.
169What is the difference between @api, @track, and @wire decorators?
What is the difference between @api, @track, and @wire decorators?
These three decorators serve completely different purposes in LWC. @api marks a property or method as public; it can be set by a parent component or accessed externally. If a parent passes a value to a child, the child's receiving property must be decorated with @api. Objects and arrays decorated with @api are read-only inside the component; you cannot mutate them directly. @track marks a property for deep reactivity. In modern LWC (API 39+), primitive properties are already reactive by default: the component re-renders when they change.
170What is Shadow DOM in LWC and why does it matter?
What is Shadow DOM in LWC and why does it matter?
Shadow DOM is a web standard that provides encapsulation for a component's HTML, CSS, and JavaScript. In LWC, every component has its own shadow root: meaning the component's internal DOM is hidden from the outside world. This matters for three reasons. First, CSS encapsulation: styles defined inside a component do not leak out to the parent, and parent styles cannot bleed into the child. This prevents unintentional style conflicts. Second, DOM isolation: external JavaScript cannot directly query elements inside a component using document.querySelector.
171What is the difference between LWC and Aura components? Why did Salesforce move to LWC?
What is the difference between LWC and Aura components? Why did Salesforce move to LWC?
LWC and Aura are two different component frameworks on the Salesforce platform. Aura was the original framework, and LWC is the modern replacement introduced in 2019. The key technical differences are: LWC is built on modern web standards like Web Components, Shadow DOM, and ES6+ modules. Aura was a proprietary framework with its own abstractions that added overhead. LWC is significantly faster because it compiles to native browser APIs, whereas Aura had a heavy JavaScript framework layer. In LWC we use standard JavaScript classes and decorators.
172What is a getter in LWC and when do you use it instead of a tracked property?
What is a getter in LWC and when do you use it instead of a tracked property?
A getter is a JavaScript class accessor that computes a value derived from other properties. In LWC we use getters frequently in templates as dynamic computed values. We use getters instead of tracked properties when a value is always computed from other state rather than stored independently. For example: a fullName getter that combines firstName and lastName, a CSS class getter that returns different classes based on a status property, or a formatted currency getter.
173How does data binding work in LWC? What is the difference between one-way and two-way binding?
How does data binding work in LWC? What is the difference between one-way and two-way binding?
LWC uses one-way data binding by default: data flows down from parent to child through properties, and events flow up from child to parent. This is the unidirectional data flow pattern. In templates we use curly braces for one-way binding: value={myProperty}. When myProperty changes, the template re-renders. But changes in the template input do not automatically update myProperty; we need an event handler like onchange to capture the change and update the property manually. There is no automatic two-way binding in LWC like Angular's ngModel or older frameworks.
174How does parent-to-child communication work in LWC?
How does parent-to-child communication work in LWC?
Parent-to-child communication in LWC happens through public properties and public methods. For properties: the child component exposes a property with the @api decorator. The parent sets this property directly in the HTML template as an attribute. When the parent updates the value, the child automatically re-renders with the new value. For methods: the child exposes a method with the @api decorator. The parent gets a reference to the child using the template.querySelector selector and then calls the method directly.
175How does child-to-parent communication work in LWC?
How does child-to-parent communication work in LWC?
Child-to-parent communication in LWC is done using CustomEvents. The child dispatches a custom event and the parent listens to it. In the child component we create a CustomEvent object with an event name and optionally a detail payload. We dispatch it using this.dispatchEvent(). If we need the event to cross shadow boundaries and reach grandparent components, we set bubbles true and composed true. In the parent template we listen to the event using the on prefix followed by the event name as an attribute.
177How do you handle a scenario where a deeply nested child needs to update data in a grandparent component?
How do you handle a scenario where a deeply nested child needs to update data in a grandparent component?
A deeply nested child communicating with a grandparent is a common architectural challenge in LWC. We have two clean patterns. Pattern one: event bubbling. The child dispatches a custom event with bubbles true and composed true. Each intermediate parent does not need to handle it: the event bubbles up automatically to the grandparent which has the listener. This is clean but can lead to unexpected event handling if intermediate components accidentally have the same event name. Pattern two: Lightning Message Service.
178What is the Wire Service in LWC and how does it work?
What is the Wire Service in LWC and how does it work?
Wire Service is a reactive data provisioning mechanism in LWC. It automatically fetches data from a wire adapter and re-fetches it whenever the reactive parameters change, without us needing to write imperative callout code. Wire works with built-in Salesforce adapters like getRecord, getRelatedListRecords, getPicklistValues, and also with Apex methods annotated with @AuraEnabled(cacheable=true). We can wire data to either a property or a function. When wired to a property, the result has data and error attributes.
179What is the difference between @wire and imperative Apex calls? When do you use each?
What is the difference between @wire and imperative Apex calls? When do you use each?
Wire and imperative calls are two ways to call Apex from LWC and each has its use case. @wire is declarative and reactive. Salesforce automatically calls the Apex method when the component loads and re-calls it when parameters change. The Apex method must be cacheable=true. Use wire for read-only data that should load automatically, like displaying a record's details, loading a list on page load, or any data that refreshes when a record ID changes. Imperative calls are explicit; we call the imported Apex method like a regular JavaScript function inside an event handler or lifecycle hook.
180How does Lightning Data Service (LDS) work in LWC and what are its advantages?
How does Lightning Data Service (LDS) work in LWC and what are its advantages?
Lightning Data Service is a client-side data layer that Salesforce provides for reading, creating, updating, and deleting records. It acts as a shared cache between components on the same Lightning page. LDS works through wire adapters like getRecord, getRecordCreateDefaults, and through the lightning-record-form, lightning-record-view-form, and lightning-record-edit-form base components which use LDS internally. The key advantages are: first, shared cache: if two components on the same page wire the same record, LDS serves both from a single cached copy.
181What is refreshApex and when do you use it? What are its limitations?
What is refreshApex and when do you use it? What are its limitations?
refreshApex is a function imported from salesforce/apex that forces a wired property to re-fetch its data from the server, bypassing the client-side cache. We use it after performing a DML operation imperatively. For example: if we have a wired list of contacts and the user adds a new contact through an imperative Apex call, the wire cache still holds the old list. Calling refreshApex on the wired property forces it to go back to the server and get the updated list. To use refreshApex, we must wire data to a property and store the entire wire result, not just the data.
182What is the difference between bubbles and composed in CustomEvent?
What is the difference between bubbles and composed in CustomEvent?
bubbles and composed are two properties that control how a custom event travels through the DOM. bubbles controls whether the event travels up the DOM tree. When bubbles is false, the default, the event stays at the component that dispatched it and only the direct parent listening with an event handler on the child tag will receive it. When bubbles is true, the event travels up through ancestor components. composed controls whether the event crosses shadow DOM boundaries.
183What is Lightning Message Service (LMS) and when do you use it?
What is Lightning Message Service (LMS) and when do you use it?
Lightning Message Service is Salesforce's publish-subscribe messaging system for communication between components that do not share a direct parent-child relationship on a Lightning page. We use LMS when: two components are in different regions of a Lightning record page, one is an LWC and the other is an Aura component or Visualforce, or they simply do not have a common parent component to mediate. LMS requires three things. First a Message Channel: a metadata file with .messageChannel-meta.xml extension that defines the channel.
184What are the key differences between LMS and the older pubsub module?
What are the key differences between LMS and the older pubsub module?
LMS is Salesforce's officially supported publish-subscribe solution, while pubsub was a community-built JavaScript module that developers imported manually as a utility. The key differences are: first, official support: LMS is built into the platform and officially maintained by Salesforce. pubsub was a community pattern with no official support or guarantee. Second, cross-framework: LMS works across LWC, Aura, and Visualforce on the same page. pubsub only worked between LWC components. Third, page scoping: LMS messages are scoped to the Lightning page context using MessageContext.
187What is the difference between lightning-record-form, lightning-record-view-form, and lightning-record-edit-form?
What is the difference between lightning-record-form, lightning-record-view-form, and lightning-record-edit-form?
All three are LDS-based base components for working with Salesforce records, but they offer different levels of control. lightning-record-form is the simplest. It automatically renders fields in view or edit mode based on the layout-type or fields you pass. It handles everything: labels, values, edit/save/cancel buttons. Use it when you want a quick form with minimal customization. lightning-record-view-form gives more control over the display.
188What are lazy loading and conditional rendering in LWC and how do they improve performance?
What are lazy loading and conditional rendering in LWC and how do they improve performance?
Lazy loading means deferring the loading of data or components until they are actually needed: instead of loading everything upfront when the page first renders. In LWC we implement lazy loading by not calling Apex or wire in connectedCallback for data that is not immediately visible. Instead we trigger the load on user action, like clicking a tab, expanding a section, or scrolling to a part of the page. This reduces the initial load time and server requests.
189How do you avoid infinite loops in renderedCallback? What are other common LWC performance pitfalls?
How do you avoid infinite loops in renderedCallback? What are other common LWC performance pitfalls?
renderedCallback fires after every render including re-renders triggered by state changes. If we change state inside renderedCallback it triggers another render which calls renderedCallback again: causing an infinite loop. The solution is to use a boolean flag: a private property like _isRendered. At the start of renderedCallback we check if _isRendered is true and return early. Otherwise we set it to true and do our work. This ensures the code inside runs only once after the first render.
190What is the difference between this.template.querySelector and document.querySelector in LWC?
What is the difference between this.template.querySelector and document.querySelector in LWC?
this.template.querySelector searches for an element within the component's own shadow DOM; its own template. It respects shadow DOM encapsulation and is the correct way to access child elements inside a component. document.querySelector searches the entire document DOM including all shadow trees. In LWC, due to synthetic shadow DOM, this can sometimes work, but it is considered an anti-pattern because it breaks encapsulation, can accidentally select elements from other components, and may break in future Salesforce releases that move to native shadow DOM.
191What are slots in LWC and how do you use them for component composition?
What are slots in LWC and how do you use them for component composition?
Slots are placeholders in a child component's template where a parent can inject its own markup. They are a powerful pattern for building reusable container or layout components. A default slot, written as slot tag with no name, accepts any content the parent places inside the child component tags. A named slot has a name attribute and the parent targets it using the slot attribute on the injected element. Slots enable component composition: instead of duplicating layout code, we build a generic container component with slots and reuse it with different content in each usage.
192What are the best practices for writing secure LWC components? What replaced Locker Service?
What are the best practices for writing secure LWC components? What replaced Locker Service?
Lightning Web Security (LWS) has replaced Locker Service as the security architecture that isolates JavaScript code running in Lightning components; Locker Service is the older version of the same idea. It prevents components from one namespace from accessing the DOM or JavaScript of components in another namespace. Under Locker Service, DOM access is restricted; we cannot use document.cookie, access native DOM APIs directly in some cases, or manipulate elements outside our component's shadow. This protects against XSS attacks and malicious third-party components.
Scenario-Based
193Design a Salesforce–Payment Gateway Integration from Scratch?
Design a Salesforce–Payment Gateway Integration from Scratch?
When an Opportunity is marked Closed Won, a payment order should be created automatically and the payment link stored on the record. How would you design this end-to-end? MODEL ANSWER I would design this in four layers: trigger, handler, callout service, and LWC display. Layer 1: Trigger: I would create an after-update trigger on Opportunity. Direct callouts from triggers are not allowed, so the trigger would call a handler class. Layer 2: Trigger Handler: The handler checks if StageName changed to Closed Won and if a payment order does not already exist.
194Callout is Failing with 401 Unauthorized: How Do You Debug?
Callout is Failing with 401 Unauthorized: How Do You Debug?
The same code was working fine in sandbox. What steps would you take to debug and fix this? MODEL ANSWER A 401 in production but not sandbox almost always means a credentials or authentication configuration issue. Step 1: Check Named Credentials / External Credentials. The sandbox and production have separate Named Credentials. When we deploy code, the Named Credential metadata deploys but the actual credential values, API keys, secrets, tokens, do NOT migrate. Someone needs to manually enter the credentials in production.
195@future vs Queueable; Which to Use for Callouts?
@future vs Queueable; Which to Use for Callouts?
A junior developer suggests using @future methods. Would you agree? What would you recommend? MODEL ANSWER I would not fully agree with @future for this scenario. Let me explain the trade-offs. @future works fine for a single callout per record. But for a batch of records with multiple callouts each, @future has serious limitations; you cannot chain @future calls, cannot monitor them, cannot pass complex data, and each @future is a separate async job with no guaranteed order. For this scenario I would recommend Queueable with Database.AllowsCallouts for the following reasons.
196@future Method Not Updating the Record?
@future Method Not Updating the Record?
In testing they find the Opportunity fields are not being updated after the callout. The debug log shows the update DML ran. What could be wrong? MODEL ANSWER There are three common causes for this scenario. Cause 1: The @future method is querying stale data. If the Opportunity was modified after the @future was enqueued but before it ran, the method might be querying an old version. However since the update DML is running, this alone would not explain why fields are not saved: unless there is a validation rule or trigger rolling it back.
197Handling API Rate Limits from External System?
Handling API Rate Limits from External System?
Interviewer: The external payment gateway you are integrating with has a rate limit of 100 requests per minute. Your Salesforce org processes up to 500 Opportunities per hour during peak time. How do you handle this? MODEL ANSWER This is a rate limiting design problem. Firing all callouts immediately would exceed the gateway's limit and cause 429 Too Many Requests errors. Solution 1: Queueable with delay. We use a Queueable chain that processes one record at a time with a controlled pace.
198Design Bidirectional Sync Between Salesforce and External CRM?
Design Bidirectional Sync Between Salesforce and External CRM?
Contact records must stay in sync: changes in Salesforce push to the external CRM, and changes in the external CRM must update Salesforce. How do you design this bidirectional sync without creating infinite loops? MODEL ANSWER Bidirectional sync is complex and the biggest risk is sync loops: Salesforce updates external CRM, external CRM calls back to Salesforce, Salesforce triggers again and updates external CRM again, infinitely. The key design principle is: each system must mark records it owns to avoid re-processing its own updates.
199Callout Limit Exception in Bulk Trigger?
Callout Limit Exception in Bulk Trigger?
It happens when a large data import updates many Opportunities at once. How do you fix this? MODEL ANSWER This error means more than 100 http.send() calls happened in a single transaction: the governor limit. In a bulk trigger scenario, if we make a callout per record inside the trigger's loop, 101 records will exceed the limit. The root cause is that the integration was designed for single-record updates and not bulk-safe. Fix 1: Move callouts out of the trigger entirely. Replace the synchronous callout with an @future or Queueable call per record.
200Named Credentials vs Hardcoded Endpoint: Making the Case?
Named Credentials vs Hardcoded Endpoint: Making the Case?
It's simpler.' How do you respond? MODEL ANSWER I would respectfully disagree and explain why Named Credentials are worth the setup. Security: Hardcoding in Custom Settings stores credentials in plaintext that any admin or developer with access to Custom Settings can see. Named Credentials store credentials encrypted on the platform with no way to retrieve the raw value. Audit and Compliance: In environments with compliance requirements like PCI-DSS or SOC2, credentials must be stored securely. Named Credentials satisfy this requirement. Custom Settings do not.
201External API Returns Inconsistent JSON Structure?
External API Returns Inconsistent JSON Structure?
Interviewer: The external API you are calling sometimes returns a flat JSON object and sometimes wraps the data in a nested results key depending on whether it found one record or multiple. How do you handle this in Apex? MODEL ANSWER This is a classic inconsistent API response problem and requires defensive parsing. First I would document the two response shapes and write the parser to handle both cases. The approach is: after deserializing the response to a Map<String,Object>, I first check if the results key exists.
202Design a Retry Mechanism for Failed Payment Callouts?
Design a Retry Mechanism for Failed Payment Callouts?
Business requires that failed payments are retried up to 3 times before being marked as permanently failed. How do you design this? MODEL ANSWER I would design this using a Queueable chain with exponential backoff: a well-established retry pattern. Step 1: Custom fields on Opportunity: Razorpay_Retry_Count__c (Number), Razorpay_Last_Error__c (Text), Razorpay_Order_Status__c (Text). Step 2: Queueable class accepts oppId and retryCount. Inside execute(), it makes the callout. On success, it updates the Opportunity with the order details and sets status to Created.
203How Do You Secure Inbound API Calls to Salesforce?
How Do You Secure Inbound API Calls to Salesforce?
Interviewer: An external system needs to call Salesforce to push data. You expose a custom Apex REST endpoint. The external team asks how the endpoint is secured so no unauthorized system can call it. What do you tell them? MODEL ANSWER Salesforce Apex REST endpoints are not publicly accessible by default; they require authentication. Here is how we secure them. Option 1: OAuth 2.0 Connected App: We create a Connected App in Salesforce and configure OAuth 2.0.
204Choosing Between Platform Events and @future for Async Processing?
Choosing Between Platform Events and @future for Async Processing?
Another says @future is simpler. For a scenario where 50 records need callouts when updated, which would you choose and why? MODEL ANSWER Both are valid but for different scenarios. Let me compare them for this specific case. @future approach: Simple to implement, works well for low volume. Each record update fires an @future. Works fine for 50 records if they do not all update simultaneously. Limitations: no visibility into queue, no retry built in, order not guaranteed. Platform Events approach: The trigger publishes a Platform Event per record.
205Test Class Failing with CalloutException: Callouts Not Permitted?
Test Class Failing with CalloutException: Callouts Not Permitted?
The test is failing with 'System.CalloutException: You have uncommitted work pending. Please commit or rollback before calling out.' What is wrong? MODEL ANSWER This error means there is a DML operation, insert, update, delete, that happened before the callout attempt in the same test context without being committed or rolled back. Salesforce does not allow callouts after uncommitted DML in the same transaction. This is a real platform restriction, not just a test issue.
206Design a Product Selector LWC with Parent-Child Communication?
Design a Product Selector LWC with Parent-Child Communication?
When the user selects a product, a child component shows the product details and the price updates in real time. How would you architect this? MODEL ANSWER I would build this with three components: a product-list parent, a product-card child for each product, and a product-detail child for the selected product details. Component 1: product-list (parent): Wires getProducts Apex method to load the product list. Renders a list of product-card components passing each product as @api prop. Listens to a productselect event from product-card.
207LWC Component Not Re-rendering After Data Change?
LWC Component Not Re-rendering After Data Change?
After the user clicks a button that calls an Apex method to insert a new record, the list does not update to show the new record. What is wrong and how do you fix it? MODEL ANSWER This is a very common issue: the wire cache is stale after an imperative DML operation. Root cause: @wire with cacheable=true Apex methods use a client-side cache. When the imperative insert runs, it adds a record to the database but the wire cache is not automatically invalidated. The component still shows data from the old cache.
208CSS Styles Not Applying to Child Component?
CSS Styles Not Applying to Child Component?
The developer is confused. What is the problem and what is the fix? MODEL ANSWER The problem is Shadow DOM CSS encapsulation. In LWC, every component has its own shadow root. CSS styles defined in the parent component's CSS file cannot pierce into the child component's shadow DOM. This is intentional and a feature; it prevents style pollution between components. But it means the parent cannot directly style the internals of a child. There are two correct solutions. Solution 1: CSS Custom Properties (CSS Variables): The parent sets a CSS custom property on the child component's host element.
209Show Different UI Based on User's Profile or Permission?
Show Different UI Based on User's Profile or Permission?
Interviewer: You need to show a Delete button in an LWC component only to System Administrators and users with a specific custom permission. How do you implement this? MODEL ANSWER There are two ways to check this in LWC, custom permissions and user data, and I would combine both. For custom permissions: Salesforce provides @salesforce/customPermission imports in LWC. We import the custom permission using import hasDeletePermission from '@salesforce/customPermission/Delete_Payment_Records'. This returns a boolean at runtime based on whether the current user has the permission assigned.
210When to Use LMS vs CustomEvent for Component Communication?
When to Use LMS vs CustomEvent for Component Communication?
Component A is in the left sidebar, Component B is in the main content area. They are not related parent-child. When user selects something in A, B should update. Do you use CustomEvents or LMS? MODEL ANSWER For this scenario I would use LMS, Lightning Message Service, and here is exactly why. CustomEvents with bubbles and composed true travel up the DOM tree. But Component A and Component B are in different regions of the Lightning page; they are rendered in completely separate DOM trees that do not share a common parent within our control.
211Infinite Loop in renderedCallback Crashing the Browser?
Infinite Loop in renderedCallback Crashing the Browser?
The browser tab keeps crashing and the console shows renderedCallback being called thousands of times. How do you fix this? MODEL ANSWER This is the classic renderedCallback infinite loop. Here is exactly what is happening and how to fix it. The root cause: inside renderedCallback, the developer is probably setting a tracked property or calling a method that changes component state. Any state change in LWC triggers a re-render. A re-render calls renderedCallback again. This creates an infinite loop. The fix is the _isRendered boolean guard pattern.
212Design an LWC Form with Validation, Save, and Cancel?
Design an LWC Form with Validation, Save, and Cancel?
It must validate that First Name, Last Name, and Email are filled, show inline validation errors, save via Apex, show a success toast, and reset the form on Cancel. How do you build this? MODEL ANSWER I would build this as a self-contained LWC component with clear state management. Template structure: three lightning-input fields for First Name, Last Name, Email. Each input has value={contact.firstName} and onchange={handleFieldChange} with a data-field attribute to identify which field changed. Below each input, a conditional error message using if:true={errors.firstName}.
213LWC on a Record Page Needs to Refresh After Another Component Saves?
LWC on a Record Page Needs to Refresh After Another Component Saves?
Interviewer: You have two LWC components on the same Opportunity record page. Component A is a form that saves data. Component B displays a summary that includes the saved data. After Component A saves, how do you make Component B refresh automatically? MODEL ANSWER This is a cross-component refresh scenario and there are three clean solutions. Solution 1: LMS: Component A publishes an LMS message after a successful save. Component B subscribes to the channel. When B receives the message, it calls refreshApex on its wired data.
214Handling Apex Errors Gracefully in LWC: Best Practices?
Handling Apex Errors Gracefully in LWC: Best Practices?
A junior developer is just console.logging the error. What improvements would you suggest? MODEL ANSWER Console.log is fine for debugging but terrible for user experience and production support. Here is the complete best practice. First: understand the error structure. Apex errors returned from LWC wire or imperative calls have a body property. body.message contains the user-friendly message. body.stackTrace has the stack trace. For AuraHandledException thrown in Apex, body.message is what we set in the constructor. Second: display user-friendly errors in the UI.
215Build a Searchable Data Table with Pagination in LWC?
Build a Searchable Data Table with Pagination in LWC?
The list has 10,000 contacts. How do you design this for performance? MODEL ANSWER With 10,000 records, client-side operations are not an option. All filtering, sorting, and pagination must happen on the server side. Architecture: The LWC component maintains state for searchTerm, sortField, sortDirection, pageNumber, and pageSize. Whenever any of these change, an imperative Apex call is made with all parameters. The Apex method does a dynamic SOQL query with WHERE, ORDER BY, LIMIT, and OFFSET.
217Should You Use lightning-record-edit-form or Custom Apex for a Complex Save Operation?
Should You Use lightning-record-edit-form or Custom Apex for a Complex Save Operation?
Should you use lightning-record-edit-form or a custom Apex method? Justify your choice. MODEL ANSWER For this scenario I would use a custom Apex method called imperatively, not lightning-record-edit-form. Here is why. lightning-record-edit-form uses LDS under the hood. It can only save the single record's fields. It cannot execute custom business logic like sending emails or updating related records in the same transaction. The requirement has three operations, save Contact, send email, update Account counter, that must happen atomically.
Salesforce interview FAQ
01How do I prepare for a Salesforce interview?
How do I prepare for a Salesforce interview?
Start with the questions for your role and experience level on this page, and answer them out loud rather than just reading. Then practise scenario questions based on your own projects, because most interviews after the first round are about what you have built. Finish with a timed mock interview to check your weak areas.
02What are the most important Salesforce interview topics in 2026?
What are the most important Salesforce interview topics in 2026?
For admins: security and sharing, Flow, and data management. For developers: Apex triggers, SOQL, governor limits, asynchronous Apex, LWC and integration. For everyone: Agentforce and Data 360 basics, because interviewers now ask about them in most roles.
03How many questions should I practise before an interview?
How many questions should I practise before an interview?
Quality matters more than quantity. Practise 50 to 100 questions for your role until you can explain each one with an example from your work, then 10 to 20 scenario questions. That is more useful than reading 1,000 answers once.
04Are Salesforce interview questions different for freshers and experienced candidates?
Are Salesforce interview questions different for freshers and experienced candidates?
Yes. Freshers are asked definitions and basic how-to questions, such as the difference between a role and a profile. Experienced candidates get scenarios and design questions, such as how to handle data skew or design an integration, and are expected to give examples from real projects.
05Do I need a Salesforce certification to get an interview?
Do I need a Salesforce certification to get an interview?
It helps a lot, especially at service companies and partners, where certifications are often a filter on job descriptions. Platform Administrator for admin roles and Platform Developer for developer roles are the usual first choices. See the full list of Salesforce certifications.