1. Explain the difference between before and after triggers in Salesforce, and provide a realistic scenario where you would choose one over the other.
Before triggers execute before a DML operation is committed to the database, allowing you to validate or modify records before insertion or update, while after triggers execute post-commit and are useful for side effects like creating related records or calling external APIs. A before insert trigger on Account would be ideal for auto-populating a field or preventing duplicate names, whereas an after insert trigger would be appropriate for creating related Opportunity records or logging to an external system, since you need the Account ID that's only generated after insert.
2. You have a trigger that processes bulk records, but the org is hitting CPU time limit exceptions sporadically during month-end close. What are three specific optimization techniques you would apply and why?
First, batch SOQL queries outside loops using maps instead of querying inside the loop for each record—for example, query all related Opportunities once and build a Map<AccountId, List<Opportunity>> instead of querying per Account. Second, use selective query filters and avoid querying all fields; select only necessary fields and add WHERE clauses to reduce data volume. Third, defer expensive callouts to a queueable or batch job using System.enqueueJob() rather than executing them synchronously in the trigger, since callouts consume CPU time and can cause governor limit failures. This approach dramatically reduces CPU consumption and prevents timeout errors.
3. A junior developer wrote a trigger that queries Account records inside a for loop over Contact inserts. The trigger works fine in sandbox but fails in production with 50,000 Contact records. Diagnose the issue and propose a solution.
The issue is non-bulkified code violating the SOQL query limit of 100 queries per transaction; querying inside a loop means 50,000 queries are attempted. The solution is to refactor the trigger to query all related Accounts once before the loop using a Set of AccountIds, then build a Map<Id, Account> and look up values by key inside the loop. This reduces the query count from 50,000 to 1, staying well within governor limits and ensuring predictable performance at scale.
4. How would you prevent recursive trigger execution when an after insert trigger on Opportunity creates a Task, which then fires a workflow that updates the Opportunity?
Implement a static Boolean flag in a utility class to track trigger execution state; for example, set a static variable like TriggerExecutionControl.isOpportunityTriggerExecuting = true before processing and check this flag at the trigger entry point to skip execution if already running. Alternatively, use a static Set to track processed record IDs and skip records that have already been processed in the current transaction. Additionally, configure workflow rules or process builder to not fire on specific field updates, or redesign the solution to consolidate logic into a single after trigger that handles both the Task creation and Opportunity update in one transaction to avoid round-tripping.
5. Design a trigger-based solution for syncing Account billing address changes to all related Opportunities and Contracts within 5 seconds. What are the trade-offs of a synchronous vs. asynchronous approach?
A synchronous after update trigger on Account querying all related Opportunities and Contracts, then updating them in a single DML statement, guarantees immediate sync but risks hitting CPU and DML row limit (10,000 per transaction) if the Account has thousands of related records. An asynchronous approach using System.enqueueJob() with a queueable defers execution, allowing larger batches via a batch job, but introduces a 5-10 second delay and added complexity. For a 5-second requirement, use synchronous logic with a size check: if related records exceed safe limits, throw a validation error requesting manual sync or use a scheduled batch job. The trade-off is between guaranteed consistency and performance; synchronous is simpler but riskier at scale, asynchronous is resilient but slower.
6. Write the logical flow for an after update trigger on Case that prevents a Case from being closed if there are open child Cases, and logs a custom error to a tracking object if attempted.
In the after update trigger, identify Cases transitioning to closed status by comparing old and new maps (if newMap.Status == 'Closed' and oldMap.Status != 'Closed'). Collect the Case IDs and query all related child Cases with Status != 'Closed'. For any parent Case with open children, insert a CaseAuditLog record capturing the user ID, timestamp, and case details, then use addError() on the parent Case record in a before update context (or re-query in before update) to prevent closure and display a user message. Note: addError() must be called in a before trigger, so this logic should split between before update (for validation) and after insert/update (for logging), ensuring clean separation of concerns.
7. A before insert trigger on Lead runs a validation callout to an external API. In 2% of cases, the API times out. How should you architect this to prevent Lead creation failures, and what Salesforce governor limits apply?
Callouts are not allowed in before triggers; you must refactor to an after insert trigger that calls System.enqueueJob() to execute the callout asynchronously in a queueable, catching timeout exceptions and logging failures without blocking Lead creation. Alternatively, make the callout in a before trigger only if using a REST-based approach via a mock or stored validation, but this violates best practices. Governor limits include 100 callouts per transaction (synchronous) and 100 per queueable job; timeouts are typically 10 seconds for HTTP callouts and 30 seconds for tooling API. By deferring to async, you isolate timeouts and allow Lead creation to succeed; failed validations are logged asynchronously without user-facing impact.
8. You need to enforce that Contact email addresses are unique across the org, even during bulk imports. What are the limitations of a database-level unique constraint vs. a trigger-based approach, and which should you use?
A database-level unique constraint is faster and prevents duplicates at the persistence layer, but it blocks the entire DML operation if any record violates uniqueness, providing poor user experience during bulk operations and generating cryptic errors. A trigger-based approach queries existing Contacts, builds a Set of emails, and provides granular error messages per duplicate record, allowing partial inserts if using AllOrNone=false in API calls. However, triggers are slower and the SOQL query can hit governor limits on large datasets. The best practice is to use a before insert/update trigger for validation and custom error messages, combined with a unique constraint for data integrity as a safety net; this balances user experience with correctness.
9. A trigger updates a field on related Accounts whenever an Opportunity is closed won. After deployment, you notice the field is not updating in a specific scenario. How would you debug this, and what common trigger pitfalls might explain it?
Use debug logs set to FINEST level and deploy a temporary trigger log to capture the record IDs being processed, the query results for related Accounts, and the update DML result. Common pitfalls include: the after insert/update trigger not firing if you updated Opportunities via a workflow or process builder (which may not invoke triggers in certain contexts), the SOQL query using filters that exclude the related Account (e.g., wrong Account ID foreign key), the DML update hitting a validation rule on the Account that silently fails, or the user lacking update permissions on the Account object. Check the API version compatibility, system debugging logs, and Salesforce Setup > Monitoring > Debug Logs to confirm the trigger is executing; if not, verify the trigger logic includes the event combination (after update, for example) and that the records match the filter criteria.
10. Design a multi-object trigger strategy for a requirement where updating a Deal (custom object) must sync changes to related Accounts, Contacts, and Opportunities, all within a single transaction. How would you structure this and what risks does it carry?
Implement an after update trigger on Deal that collects related Account, Contact, and Opportunity IDs, queries all three objects in bulk (not in loops), builds updates for each, and executes three DML statements (one per object type) in sequence. This keeps all changes atomic; if any update fails, the entire transaction rolls back. Risks include hitting the DML statement limit (150 per transaction) if you execute more than 150 separate updates, exceeding the DML rows limit (10,000 per transaction) if related records are numerous, or encountering validation rule failures that cascade. Mitigation strategies include pre-validating records before update, batching updates by object type, and using try-catch blocks to log and recover from failures. For very large scales, consider deferring non-critical updates to a queueable job to keep the synchronous trigger lightweight.
11. Explain when you would use a trigger versus a Process Builder, Flow, or Apex trigger callback, and provide a realistic example where the wrong choice causes problems.
Triggers are best for complex logic, bulkification, and direct governor limit control; Process Builder and Flows are low-code alternatives suitable for simple field updates and notifications. A common mistake is using a Flow triggered by record change to perform 100 SOQL queries per record during bulk inserts of 5,000 records, causing CPU time limit failures, whereas a bulkified after insert trigger would execute only 1-2 queries regardless of volume. Conversely, using a trigger for a simple field update is over-engineering when Flow or Process Builder provides the same result with less maintenance. Trigger callbacks (reserved for platform events and CDC) are niche. The right choice depends on complexity, scale, and maintainability; for senior developers, triggers are appropriate when performance at scale or complex conditional logic is required.
12. A production trigger deployed without test coverage is causing daily issues. Outline a comprehensive test strategy for a before insert trigger on Opportunity that validates amount and updates probability, including edge cases and bulk scenarios.
Write test cases covering: (1) single record insert with valid amount and probability update verification, (2) bulk insert of 200 records to test non-bulkified queries and loops, (3) edge cases (zero amount, null probability, maximum amount limits), (4) field validation errors (missing required fields, invalid amount types), (5) related Account and User data dependencies using test data factories, and (6) rollback scenarios using try-catch to verify error handling. Use System.assertEquals() to verify probability was set correctly and verify no SOQL limit exceptions occurred. Aim for at least 85% code coverage, test both positive and negative paths, and simulate realistic bulk scenarios; avoid hardcoding IDs and use sObjDML.getLastInsertedId() for record references. Deploy with this test class achieving 100% coverage of trigger logic to prevent future regression.

