Apex Interview Questions
Bulkification, governor limits, async processing, and large data volume patterns.
114 unique questions in this topic
Difficulty Level
Focus Area (Triggers, Async, etc.)
Showing 114 of 114 Apex questions
What is Apex and when would you use it?
An admin hits Flow limits on complex validation. The lead asks when Apex is the right tool.
What is bulkification in Apex?
A data load updates 200 Accounts and a trigger fails. You explain why bulk-safe code matters.
What are governor limits?
A junior's integration works for one record but fails on batch jobs. You explain governor limits.
What is the difference between a trigger and a class?
A new hire puts all logic inside a trigger file. You explain separation of concerns.
What is SOQL and how is it different from SQL?
You need Accounts in California with open Opportunities. The interviewer asks how you query in Apex.
What is DML in Apex?
After processing Opportunities, you need to create Tasks. You explain DML operations.
What is a test class and why is 75% coverage required?
Deployment fails due to insufficient test coverage. You explain Apex testing basics.
What is the difference between before and after trigger context?
You must set a field before save and send email after save. You choose trigger contexts.
What are future methods and when use them?
A trigger must call an external API but callouts cannot run with pending DML. You mention @future.
What is CRUD and FLS security in Apex?
A class with sharing disabled exposes salary fields to users who should not see them. You explain security checks.
What is an Apex exception and basic error handling?
Users see a generic "Script-thrown exception" on save. You describe handling errors properly.
What debugging tools help Apex developers?
Your trigger works in sandbox but not production data. You list how you would debug as a junior.
Explain bulkification and why a single-record trigger pattern fails at scale
A data loader job inserting 10,000 Accounts fires a trigger that queries Contacts inside a for-loop. The job fails at record 150 with "Too many SOQL queries".
Design trigger framework with recursion and order-of-execution control
Account trigger updates related Opportunities causing Opportunity trigger to update Account again, hitting recursion limits and inconsistent rollups.
Choose between Queueable, Batch, and Scheduled Apex for async processing
Nightly job must recalculate territory assignments for 2M Accounts, call external geocoding API, and send summary email to admins.
Implement secure Apex with CRUD, FLS, and sharing enforcement
Security review found `@AuraEnabled` Apex returning Contact fields without FLS checks, exposing SSN to community users.
Architect large data volume strategies for 20M+ record objects
Custom Transaction__c object exceeds 18M records. Reports timeout and selective queries fail without custom indexes.
Handle callouts, timeouts, and retry patterns in Apex integrations
Payment gateway callouts from trigger cause failures when API latency spikes; users see DML rollback on unrelated records.
Design Apex test strategy achieving meaningful coverage and quality
Org has 86% coverage but production bugs slip through because tests only assert `System.assert(true)`.
Explain order of execution and where Apex fits with Flow and validation
Before-save Flow and Before Update trigger both modify the same field causing unpredictable final value depending on save path.
Implement platform caching for expensive Apex computations
Dashboard LWC calls Apex aggregating 50k child records on every page load causing timeouts.
Design invocable Apex for Flow and Agentforce action contracts
Twelve Flows duplicate credit check logic. Agentforce needs same capability as invocable action with structured error responses.
Optimize SOQL queries for selective filters and query performance
Query on Custom_Object__c with Status__c filter returns full table scan warning and times out in batch job.
Architect transaction boundaries and partial success DML
Bulk import must insert 500 related records where 20 fail validation but 480 should commit for manual correction later.
Implement custom metadata driven Apex configuration
Hardcoded endpoint URLs and feature toggles in Apex require deployments for every environment change.
Design Apex REST API for external system integration
Partner needs REST API to submit orders into Salesforce with OAuth and field validation mirroring UI rules.
Handle mixed DML operations involving setup and non-setup objects
Apex creating User and Account in same transaction fails with MIXED_DML_OPERATION error.
Explain heap size management in complex Apex transformations
Batch job processing CSV JSON payloads hits "Apex heap size too large" at 50k line items deserialized into List<Object>.
Design Apex for multi-currency and enterprise territory management
Global org with dated exchange rates and territory rules requires Apex rollups respecting currency and territory visibility.
Implement Platform Event publishing and subscribing patterns
Order status changes must notify warehouse, analytics, and email service with at-least-once delivery tolerance.
Architect Apex governor limit monitoring and defensive coding
Intermittent "Apex CPU time limit exceeded" errors plague production with no clear reproduction in sandbox.
Design package-friendly Apex for ISV and managed package contexts
ISV product needs extension points for customer-specific logic without modifying base package Apex.
Use Database.Stateful in batch Apex for running totals
Batch must track cumulative error count across execute methods for finish email summary.
Implement custom exception hierarchy for domain errors
Generic AuraHandledException messages confuse users and leak internal details.
Apply Selector layer pattern for SOQL centralization
SOQL duplicated across 15 classes querying Account with slightly different field lists.
Design Domain layer for business logic on SObject collections
Account business rules scattered between trigger, Flow, and LWC controller.
Use Savepoint and rollback for composite business operations
Opportunity creation with line items must rollback entirely if inventory check fails mid-process.
Implement Apex Continuation for long external callouts in LWC
Credit bureau callout takes 15 seconds exceeding synchronous Apex limit in Lightning.
Optimize trigger performance with lazy loading patterns
Before update trigger on Opportunity queries 8 related objects even when only Stage changed.
Design Apex sharing calculation helpers for manual sharing
Partner deals require dynamic AccountShare rows based on complex territory and team rules.
Handle encryption and Shield Platform Encryption in Apex
Encrypted fields break SOQL WHERE clauses in integration queries filtering on email.
Implement Callable interface for dynamic Apex invocation
Flow needs to invoke different Apex handlers based on record type without separate invocable per type.
Use SObject describe caching for dynamic Apex UIs
Admin-configured field display LWC calls describe on every render causing CPU spikes.
Architect delete and cascade behavior in Apex integrations
External MDM sends delete events but Salesforce lookup restrictions block Account deletion with open Cases.
Design Apex email services for inbound email-to-case parsing
Vendor invoices emailed to unique address must create Case with attachment and parsed PO number.
Implement row-level formula and validation in Apex for complex rules
Validation rules cannot express cross-object discount cap requiring query of related Quote lines.
Use Finisher pattern chaining Queueable jobs reliably
Multi-step provisioning requires 5 sequential callouts exceeding single Queueable chain depth concerns.
Design Apex for Experience Cloud guest and authenticated users
Guest users need product registration form but Apex controller exposes methods returning other customers data via IDOR.
Apply Apex enum and constant patterns for maintainability
Status strings scattered as literals cause typos breaking batch filters silently.
Implement scheduled job orchestration and dependency management
Five scheduled jobs run at 2 AM in random order causing dependency failures when job B needs job A output.
Optimize DML collections with upsert and external Id patterns
Nightly sync upserts 100k records using Database.upsert with external Id sometimes slower than expected.
Design Apex logging framework for production support
Production issues require reproducing user actions but debug logs unavailable and System.debug stripped.
Handle AccountContactRelation in Apex for multi-contact roles
B2B portal must display all buying committee contacts with roles but triggers only handled primary Contact.
Implement custom hash and deduplication logic in Apex
Lead import creates duplicates despite duplicate rules because vendor normalizes company names differently.
Use Test.isRunningTest branching carefully
Code skips callout in test via Test.isRunningTest but production callout failure path never tested.
Design Apex for record locking during approval processes
Integration updates Quote lines while stuck in approval causing pricing inconsistencies.
Architect Apex offload to Heroku or external compute
PDF generation and complex pricing matrix exceed Salesforce CPU limits for real-time quote UI.
Implement ContentDocument and file handling in Apex
Case auto-closure must archive email attachments to external storage via Apex without hitting heap limits.
Design Apex for optimistic locking with System Modstamp
Two reps edit same Opportunity offline mobile; last write wins silently drops first rep discount.
Use AggregateResult and GROUP BY efficiently in reporting Apex
Executive dashboard Apex aggregates Opportunity amounts by region but hits query row limit.
Implement custom setting and hierarchy for feature flags in Apex
New trigger logic needs gradual rollout by profile before org-wide enable.
Design Apex integration with Change Data Capture subscribers
External data warehouse needs near-real-time Account updates including field-level change metadata.
Handle Person Accounts in Apex trigger logic
Account trigger assuming Business Account fields breaks on Person Account records in unified B2B/B2C org.
Apply defensive null and empty collection handling in Apex
NullPointerException in production when optional lookup field blank on subset of records in batch.
Recover from a failed Data Loader job that partially committed 800k records
Nightly Account import via Data Loader inserted 800k rows before failing on row 812,000 with DML errors. Finance reports duplicate external IDs and orphaned child records.
Prevent trigger recursion when rollup updates cascade across five related objects
Opportunity line item trigger updates Opportunity, which updates Account rollup, which fires Account trigger updating child Contacts, causing MAXIMUM_TRIGGER_DEPTH exceeded during bulk order import.
Tune batch Apex scope size when processing 5 million Opportunity records nightly
Territory realignment batch on 5M Opportunities times out in execute method with scope 200 due to heavy per-record SOQL and CPU-intensive territory logic.
Chain Queueable jobs for sequential ERP callouts without losing pipeline state
Order export requires authenticate, create header, create lines, and confirm shipment—four REST callouts that must run in order with retry on transient failures.
Migrate legacy @future methods to Queueable without breaking integrations
Org has 40 @future(callout=true) methods called from triggers and Visualforce. Leadership wants Queueable for better monitoring and chaining without dual-write bugs.
Design high-volume Platform Event fan-out for 2M daily order status changes
Warehouse, analytics, and partner systems subscribe to Order_Status_Changed__e. Publish rate spikes to 500 events/sec during peak causing subscriber lag and replay gaps.
Implement inherited sharing in Apex for complex partner portal access
Partner users must see Opportunities on shared Accounts but not unrelated Accounts in same partner org. OWD is Private and sharing rules cannot express contract-scoped visibility.
Enforce field-level security in Apex REST endpoints serving mobile clients
Penetration test found mobile REST API returning Contact.Social_Security_Number__c to authenticated users whose profile hides the field in UI.
Handle SOQL query row limit when aggregating child records on LDV parent
Account with 45,000 related Task records breaks Account summary Apex that queries all children in single SOQL for activity counts.
Design compensating transaction when external payment API fails after Salesforce commit
Order saved in Salesforce triggers payment capture callout. Gateway timeout causes unknown payment state while Order shows Paid in Salesforce.
Optimize CPU time when regex and JSON parsing dominate trigger execution
Case trigger parses JSON payload and runs regex validation on Description for 200 cases per batch hitting CPU time limit during email-to-case floods.
Test trigger bulk paths with meaningful assertions not assert(true)
Account trigger tests insert one record with System.assert(true). Production bulk import fails with undeclared SOQL in loop.
Integrate MuleSoft or middleware bulk APIs with Apex ingestion patterns
Middleware pushes 500k Product updates nightly via Bulk API 2.0. Apex triggers on Product2 cause job failures at 15% completion.
Implement Database.Batchable with AllowsCallouts for external enrichment
Nightly job enriches 100k Lead records with external firmographic API. Batch execute must callout per chunk without exceeding callout limits.
Resolve row lock contention when parallel batches update same parent Accounts
Two parallel batch jobs updating Account.Last_Activity_Date__c from Task and Event triggers cause UNABLE_TO_LOCK_ROW errors during business hours.
Use System.runAs to test sharing and FLS in Apex test classes
Tests run as system user pass but partner user cannot see records in production. No runAs coverage for community profile.
Architect custom index strategy before LDV object reaches 10 million rows
Transaction__c at 8M rows. New reporting filters on Merchant_Id__c and Transaction_Date__c cause full table scans and timeout.
Publish Platform Events after DML commit without losing events on rollback
Trigger publishes Order_Created__e before save. Validation rule failure rolls back Order but warehouse receives event and ships phantom order.
Bulkify Apex that processes EmailMessage and Attachment imports
Email-to-case creates 500 cases per hour. After-insert trigger on EmailMessage queries Case and Contact per message causing SOQL limit failures.
Design Apex-friendly error envelope for external REST consumers
Partners parse Apex REST error bodies inconsistently. Some get generic 500 with stack trace fragments exposing internal class names.
Handle governor limit exceptions gracefully in user-facing Apex controllers
LWC search runs Apex returning 10k rows. Users see cryptic "Apex heap size too large" instead of actionable message.
Implement selective SOQL for multi-select picklist and semi-join queries
Report-style Apex query filters Accounts where Region__c INCLUDES ('North','South') on 3M Account table times out without index.
Secure dynamic SOQL with bind variables and field allowlists
Admin-configured report LWC builds dynamic SOQL from user filter input. Security review flags SQL injection via unsanitized field names.
Process millions of records with Iterable batch instead of QueryLocator
QueryLocator on Custom_Log__c with 12M rows hits heap in start() when driving complex pre-filter logic unavailable in SOQL alone.
Design nightly reconciliation batch comparing Salesforce to external MDM
MDM is source of truth for Customer master. Salesforce drifts with 15k mismatched addresses detected monthly by business users.
Avoid DML in loop when cascade updates touch six child object types
Contract activation trigger updates Status on Quote, Order, Asset, Entitlement, Subscription, and Invoice child records one DML per child per Contract.
Implement CRUD checks before dynamic object DML from invocable Apex
Generic invocable accepts object API name and field map from Flow. Community Flow accidentally updates objects guest users cannot access when runAs wrong.
Tune Queueable flex queue usage when org hits daily async limit
Org exceeds 24-hour AsyncApexJob limit during month-end billing. Queueable jobs queue in flex queue for 6 hours delaying customer invoices.
Write Apex tests for callout retry logic with multi-mock HttpCalloutMock
Callout utility retries three times on 503. Tests only mock single success missing retry and exhaustion paths.
Migrate synchronous trigger callouts to event-driven integration pattern
Legacy triggers make synchronous HTTP callouts on Case update causing user save timeouts and uncommitted work pending errors.
Handle Big Object ingestion from Apex for audit and telemetry archive
Api_Log__c at 20M rows degrades org performance. Architecture mandates Big Object archive with Apex write path from API gateway.
Implement sharing recalculation batch after territory model realignment
Enterprise Territory Management realignment affects 2M Accounts. Users report wrong record access for 48 hours until sharing catches up.
Design Apex transaction finalizers for Queueable failure cleanup
Queueable provisioning job fails mid-chain leaving staging records in Processing status blocking retries.
Optimize trigger SOQL with lazy relationship query pattern
Order trigger always queries Account, Pricebook, and Owner data even when only Ship_Date__c changes on update.
Build idempotent upsert integration keyed on external Id and hash
Middleware replays same product sync message after network retry creating duplicate Product2 rows with different external keys.
Explain when without sharing is justified and how to audit elevated access
Developer added without sharing to fix partner visibility bug. Security audit flags uncontrolled data exposure across 12 classes.
Handle Data Cloud or S3 file import triggering Apex on bulk insert
Marketing Cloud data import creates 300k Contact rows via automation. Contact trigger cannot handle volume and blocks import job.
Test negative sharing scenarios with assert on QueryException
Apex test asserts record found but never tests that unauthorized user receives empty result or exception on restricted record.
Design Apex cache stampede protection for hot reference data
Org cache partition for product catalog expires at noon. Thousand concurrent users hit Apex simultaneously causing SOQL storm and CPU limit errors.
Implement partial success handling in REST bulk upsert endpoint
Partner bulk order API accepts 200 orders per request. Twenty fail validation but partner expects 180 committed with per-row error detail.
Profile Apex CPU and SOQL in production without debug logs
Production debug logs unavailable for all users. Ops needs CPU hotspot identification on Account trigger without enabling full trace.
Architect delete and anonymize batch for GDPR with Apex DML limits
GDPR erasure request requires deleting Contact and cascading PII across 15 related object types for 50k contacts in single request.
Use FOR UPDATE SOQL to prevent lost updates in concurrent Apex
Two batch jobs allocate inventory from same Product stock field causing oversell when both read quantity 10 and each decrements by 8.
Design SOAP Apex web service for legacy ERP still on XML contracts
Legacy ERP cannot consume REST JSON. Salesforce must expose wsdl SOAP endpoint for order acknowledgment with bulk XML payload.
Handle trigger bypass hierarchy for data migration weekend cutover
Weekend cutover loads 3M historical records. Triggers firing enrichment callouts and emails would overwhelm org and external systems.
Implement cumulative limit tracking across trigger and helper call stack
Account trigger delegates to three services each querying related data. Total SOQL exceeds limit but each service appears healthy individually.
Build federated search integration from Apex using SOSL responsibly
Global search LWC calls Apex SOSL across Account, Contact, Lead, Case, and custom objects. SOSL times out at LDV with generic search terms.
Design Apex integration with OAuth token refresh in long-running batch
Batch job processing 8 hours hits expired OAuth token mid-execute causing thousands of failed callouts until manual restart.
Explain Database.Methods for convertLead and other specialized DML
Integration converts 500 Leads per batch using manual Account Contact Opportunity create instead of Database.convertLead causing duplicate Account matches.
Architect zero-downtime Apex deployment with parallel async job awareness
Deployment changes Queueable signature while 400 jobs from old version still in flex queue causing post-deploy failures.