Performance Optimization
Ensure Salesforce operates within governor limits while delivering sub-second user experiences.
Key Duties
Optimize SOQL/SOSL selectivity and indexing
: SOQL/SOSL queries must use selective filters to leverage Salesforce's query optimizer. Selective queries use indexed fields and have high selectivity ratios (>0.03 for standard objects, >0.0001 for custom). Create custom indexes on frequently queried fields, especially those used in WHERE clauses. Use Query Plan Tool to analyze query execution plans and identify non-selective queries that cause full table scans. Optimize by adding compound indexes for multi-field queries and consider skinny tables for frequently accessed fields.Reduce synchronous processing
: Move long-running operations to asynchronous processing using @future methods, Queueable Apex, or Batch Apex. Synchronous processes are limited to 10 seconds of CPU time and 120 seconds total execution time. Break complex operations into smaller chunks, implement pagination for large data sets, and use Platform Events for decoupling processes. Avoid synchronous callouts in triggers and user-facing operations.Leverage caching, async Apex, and platform events
: Use Platform Cache (Session and Org cache) to store frequently accessed data and reduce database hits. Implement async patterns with Queueable Apex for complex business logic that doesn't need immediate response. Platform Events enable event-driven architecture, allowing near real-time communication between Salesforce and external systems without synchronous API calls. Use Change Data Capture for efficient data synchronization.Monitor and analyze performance metrics using Event Monitoring
: Enable Event Monitoring to track API calls, Apex execution, report performance, and user activity. Analyze EventLogFile objects to identify slow queries, high CPU usage, and performance bottlenecks. Set up dashboards to monitor governor limit usage, response times, and error rates. Use Lightning Usage App for real-time performance insights and predictive analytics.Implement efficient data models with proper relationships
: Design data models with appropriate relationship types (Master-Detail vs Lookup) based on business requirements and ownership needs. Use junction objects for many-to-many relationships and avoid excessive formula fields that impact performance. Implement data archiving strategies for historical records and consider Big Objects for high-volume data that doesn't require frequent updates.Use selective filters and avoid full table scans
: Ensure all SOQL queries have WHERE clauses with selective filters on indexed fields. Avoid queries without filters on large tables (>100,000 records) as they trigger full table scans. Use bind variables in dynamic SOQL to enable query plan caching. Implement query optimization by adding LIMIT clauses and using FOR UPDATE sparingly to avoid locking issues.Optimize Visualforce/Lightning page load times
: Minimize server round-trips by using Lightning Data Service and Apex actions efficiently. Implement lazy loading for components and use client-side caching. Optimize Lightning Web Components by reducing bundle sizes and using efficient data fetching patterns. Minimize the use of formula fields in page layouts and list views, as they calculate on-the-fly and impact performance.
Common Anti-Patterns
- Queries inside loops
- Unselective filters on large objects
- Over-automation in before triggers
- Excessive use of formula fields in reports and list views
- Ignoring governor limits in bulk operations
- Hardcoding record IDs instead of using dynamic queries
Tools
- Salesforce Optimizer
- Query Plan Tool
- Event Monitoring
- Apex Replay Debugger
- Platform Cache
- Debug Logs Analysis
Online References
Scalability Planning
Design orgs that survive exponential data growth and user expansion.
Key Strategies
Archive high-volume historical data
: Implement data archiving solutions to move aged records to external storage systems, reducing the active dataset size in Salesforce. Use Salesforce's Data Archiving feature or third-party tools to automatically archive records older than specified timeframes. This improves query performance, reduces storage costs, and maintains compliance with data retention policies while keeping historical data accessible.Use Big Objects and External Objects
: Big Objects store massive volumes of historical data (up to billions of records) without impacting org performance. They're ideal for audit trails, IoT data, or analytics datasets. External Objects connect to external data sources via OData without storing data in Salesforce, enabling real-time access to large external datasets while maintaining performance.Evaluate multi-org vs single-org strategy
: Assess whether a single org can handle projected user and data growth or if multiple orgs are needed. Consider business units, geographic regions, compliance requirements, and data sharing needs. Multi-org architectures provide isolation but increase complexity and integration overhead. Use Salesforce's org strategy decision guides to evaluate trade-offs.Implement data partitioning and archiving strategies
: Partition large datasets by business units, time periods, or record types to improve query performance. Implement automated archiving workflows that move data to cheaper storage tiers based on age and access patterns. Use skinny tables for frequently accessed fields and consider data lakes for advanced analytics workloads.Use Salesforce Connect for external data integration
: Connect to external data sources without data replication using OData protocols. This enables real-time access to large external datasets for reporting and analytics without impacting Salesforce storage limits. Ideal for integrating with ERP systems, data warehouses, or external databases while maintaining performance.Monitor storage usage and plan for data growth
: Track data storage consumption across all objects and regularly forecast growth based on business metrics. Set up alerts for approaching storage limits and implement data cleanup processes. Use Salesforce's Storage Usage dashboard and Event Monitoring to identify data growth trends and plan capacity accordingly.Optimize sharing rules and visibility settings for large datasets
: Complex sharing rules can severely impact performance with large datasets. Use role hierarchies efficiently, minimize criteria-based sharing, and leverage public groups. Consider record ownership strategies and implement sharing recalculation scheduling during off-peak hours to minimize user impact.Consider read-only replicas for reporting workloads
: High Volume Customer (HVC) orgs can use read-only replicas to offload reporting queries from the primary database. This improves performance for transactional users while providing near real-time reporting capabilities. Replicas are automatically synchronized and can handle complex analytical queries without impacting production performance.Leverage platform events for real-time data synchronization
: Use Platform Events and Change Data Capture to enable event-driven data synchronization between systems. This reduces API polling, minimizes data latency, and scales better than traditional batch synchronization. Implement event-driven architectures for real-time dashboards, external system updates, and cross-org data flows.
Online References
Codebase Review & Optimization
Maintain clean, efficient, and maintainable Apex and Lightning codebases.
Key Practices
Refactor triggers into handler frameworks
: Replace individual triggers with trigger handler patterns that implement the Trigger Handler Interface. This enables proper separation of concerns, easier testing, and prevents trigger recursion. Use trigger context variables and bulk-safe patterns to handle multiple records efficiently. Implement trigger frameworks like Kevin O'Hara's or custom handler classes that route logic based on trigger context.Adopt bulk-safe, testable Apex patterns
: Write Apex code that can handle bulk operations (up to 200 records in triggers/batches). Use collections and loops instead of individual record processing. Implement proper error handling that doesn't fail the entire batch. Make code testable by avoiding hardcoded IDs, using dependency injection, and creating mock data factories. Follow the Single Responsibility Principle for maintainable code.Reduce cyclomatic complexity
: Break down complex methods with multiple conditional branches into smaller, focused methods. Use early returns to simplify conditional logic and improve readability. Implement guard clauses and extract complex boolean expressions into well-named methods. Aim for cyclomatic complexity under 10 per method using tools like PMD Apex to identify and refactor complex code paths.Implement proper error handling and logging
: Use try-catch blocks strategically and provide meaningful error messages. Implement custom exception classes for different error scenarios. Use Platform Events or custom objects for centralized logging instead of debug logs. Create error handling frameworks that gracefully degrade functionality and provide user-friendly error messages while logging technical details for debugging.Use Apex Design Patterns (Singleton, Factory, etc.)
: Implement Singleton pattern for service classes to ensure single instance and reduce heap usage. Use Factory pattern for object creation and Strategy pattern for interchangeable algorithms. Apply Service Layer pattern to encapsulate business logic and Repository pattern for data access abstraction. These patterns improve code reusability, testability, and maintainability.Optimize test coverage and efficiency
: Achieve at least 75% test coverage with meaningful test methods that cover positive, negative, and edge cases. Use @TestSetup for efficient data creation and avoid using SeeAllData=true. Implement test utilities and mock frameworks to isolate units under test. Optimize test execution time by using smaller datasets and avoiding unnecessary DML operations in test methods.Review and optimize batch jobs and schedulers
: Implement proper batch size optimization (typically 200 records) and monitor batch performance metrics. Use Queueable Apex for complex chains of jobs and implement proper error handling for failed batches. Schedule jobs during off-peak hours and monitor Apex job queues. Consider using Platform Events for real-time processing instead of scheduled batch jobs where appropriate.Adopt declarative automation over code where possible
: Use Process Builder, Flows, and Workflow Rules for business logic instead of Apex where feasible. Leverage formula fields, validation rules, and roll-up summary fields for calculations. Prefer configuration over customization to reduce technical debt and improve maintainability. Reserve Apex for complex business logic that cannot be handled declaratively.Regular code reviews and refactoring sessions
: Establish code review processes using pull requests and automated code analysis tools like PMD and CodeScan. Conduct regular refactoring sessions to address technical debt and improve code quality. Implement coding standards and use tools like Prettier for consistent formatting. Maintain code documentation and conduct knowledge sharing sessions for complex implementations.
Tools
- PMD Apex
- CodeScan / SonarQube
- Checkmarx / Security Code Scan
- Force.com IDE / VS Code Extensions
- Apex Code Analyzer
Online References
Integration Optimization
Build robust, efficient integrations that minimize overhead and maximize reliability.
Key Practices
Use async and event-driven patterns
: Implement asynchronous processing using Queueable Apex, Batch Apex, or @future methods for long-running integrations. Use Platform Events and Change Data Capture for event-driven architectures that reduce polling and enable real-time data synchronization. Implement message queues and pub/sub patterns to decouple systems and improve resilience.Minimize API chatter with Bulk & Composite APIs
: Use Salesforce Bulk API 2.0 for large data operations to reduce API calls and improve throughput. Implement Composite API calls that combine multiple operations in single requests. Use SObject Collections for batch operations and minimize round-trips by fetching related records in single queries.Implement retries and circuit breakers
: Build resilient integrations with exponential backoff retry logic for transient failures. Implement circuit breaker patterns to prevent cascading failures when external systems are unavailable. Use dead letter queues for failed messages and implement proper error handling with meaningful logging for troubleshooting.Use platform events and change data capture for near real-time sync
: Leverage Platform Events for one-way event publishing and Change Data Capture for tracking data changes across objects. Implement event-driven integrations that respond to data changes in real-time rather than batch polling. Use high-volume platform events for massive-scale event publishing.Implement proper authentication and authorization
: Use OAuth 2.0 flows (JWT Bearer, Web Server, User-Agent) for secure API authentication. Implement proper session management and token refresh logic. Use Connected Apps for external integrations and implement IP whitelisting or certificate-based authentication for enhanced security.Monitor integration performance and error rates
: Set up comprehensive monitoring using Event Monitoring to track API usage, performance metrics, and error rates. Implement custom logging and alerting for integration failures. Use Salesforce's Integration Cloud or third-party monitoring tools to track end-to-end performance and identify bottlenecks.Use middleware solutions like MuleSoft for complex integrations
: Implement enterprise service bus (ESB) patterns using MuleSoft Anypoint Platform for complex multi-system integrations. Use middleware for protocol transformation, message routing, and orchestration. Implement canonical data models to standardize data exchange between disparate systems.Version APIs and handle backward compatibility
: Implement API versioning strategies using URL versioning (/v1/, /v2/) or custom headers. Maintain backward compatibility during API evolution and communicate deprecation timelines. Use API gateways for traffic management, rate limiting, and gradual rollout of new API versions.Implement rate limiting and throttling
: Respect Salesforce API limits (24,000 calls for most orgs, 100,000 for Performance Edition) by implementing intelligent throttling. Use bulk operations to maximize throughput within limits. Implement client-side rate limiting and queue management to handle API quota exhaustion gracefully.
Tools
- Postman for API testing
- Data Loader / Workbench for data operations
- MuleSoft Anypoint Platform
- Integration Cloud Services
Online References
Security Optimization
Implement comprehensive security measures to protect data and ensure compliance.
Key Practices
Flatten role hierarchies
: Minimize the depth of role hierarchies to reduce complexity and improve performance. Deep hierarchies can cause sharing calculation delays and make permission management difficult. Use public groups and permission sets to simplify access control while maintaining security. Regularly audit and flatten hierarchies to prevent performance degradation.Encrypt sensitive data using Shield
: Implement Salesforce Shield Platform Encryption to protect sensitive data at rest and in transit. Use deterministic encryption for fields that need to be queried while encrypted. Implement tenant secret for additional encryption key management. Encrypt PII, financial data, and other sensitive information to comply with regulations like GDPR, HIPAA, and CCPA.Regular security posture reviews
: Conduct quarterly security assessments using Salesforce's Health Check and Security Center. Review user access patterns, permission sets, and sharing rules. Perform penetration testing and vulnerability scans. Implement automated security monitoring and alerting for suspicious activities. Maintain security documentation and incident response plans.Implement least privilege access controls
: Grant users only the minimum permissions required to perform their job functions. Use permission sets instead of profiles for granular access control. Implement role-based access control (RBAC) and regularly review user entitlements. Use login flows and validation rules to enforce business logic security requirements.Use multi-factor authentication
: Enable MFA for all users, especially administrators and those accessing sensitive data. Implement adaptive authentication based on risk factors like location and device. Use Salesforce Authenticator or third-party MFA solutions. Require MFA for API access and high-risk operations.Conduct regular vulnerability assessments
: Perform automated code security scans using Checkmarx, PMD, or CodeScan. Implement SAST (Static Application Security Testing) and DAST (Dynamic Application Security Testing). Review third-party packages for vulnerabilities using dependency scanning. Conduct regular penetration testing and security code reviews.Monitor for suspicious activities with Event Monitoring
: Enable comprehensive Event Monitoring to track login attempts, API calls, and data access patterns. Set up alerts for anomalous behavior like multiple failed login attempts or unusual data exports. Use Transaction Security policies to block suspicious activities in real-time. Implement SIEM integration for advanced threat detection and response.Implement data classification and handling policies
: Classify data based on sensitivity levels (Public, Internal, Confidential, Restricted). Implement data handling policies for encryption, masking, and retention. Use Salesforce's Data Classification feature to tag sensitive fields. Implement data loss prevention (DLP) policies to prevent unauthorized data exfiltration.Enforce password policies and session timeouts
: Implement strong password policies with complexity requirements and regular expiration. Set appropriate session timeouts based on data sensitivity (15-30 minutes for high-security orgs). Use password history to prevent reuse and implement account lockout policies. Enable passwordless authentication options where appropriate.
Tools
- Salesforce Shield Platform Encryption
- Identity Verification
- Health Check
- Security Center
- Field Audit Trail
Online References
User Experience Tuning
Enhance user interfaces for optimal performance and usability across devices.
Key Practices
Optimize Lightning components
: Use Lightning Web Components (LWC) over Aura components for better performance and smaller bundle sizes. Implement efficient component lifecycle management and avoid unnecessary re-renders. Use lightning-data-table with server-side pagination for large datasets. Leverage Lightning Data Service (LDS) for automatic caching and optimistic updates.Reduce server round-trips
: Implement client-side caching using Platform Cache and browser storage. Use Lightning Data Service wire adapters to minimize server calls. Batch multiple operations using Apex actions and implement debounced search inputs. Use Platform Events for real-time updates instead of polling.Use client-side caching
: Implement browser storage (localStorage/sessionStorage) for user preferences and temporary data. Use Service Workers for offline capability and caching static assets. Leverage Lightning Data Service caching to reduce server round-trips. Implement intelligent cache invalidation strategies to ensure data freshness.Implement responsive design principles
: Use Lightning Design System (SLDS) responsive utilities and grid system. Implement mobile-first design with appropriate breakpoints. Use CSS Grid and Flexbox for flexible layouts. Test across different screen sizes and devices using Salesforce's mobile preview tools.Minimize JavaScript bundle sizes
: Use dynamic imports and code splitting to load components on demand. Remove unused dependencies and implement tree shaking. Use Lightning Web Components' smaller bundle sizes compared to Aura. Implement lazy loading for non-critical components and use CDN for third-party libraries.Use lazy loading for images and components
: Implement intersection observer API for lazy loading images and components. Use placeholder images and progressive loading techniques. Load components asynchronously using dynamic imports. Implement virtual scrolling for large lists to improve initial load performance.Optimize database queries for list views
: Use selective SOQL queries with proper indexing for list view filters. Implement pagination with LIMIT and OFFSET clauses. Use skinny tables for frequently accessed fields in list views. Avoid complex formula fields that calculate on-the-fly in list views and reports.Implement progressive web app features
: Add web app manifest for installability and offline capability. Implement service workers for caching and background sync. Use push notifications through Platform Events. Ensure fast loading times and responsive design for mobile users.Conduct user testing and gather feedback
: Perform usability testing with real users across different roles and devices. Implement analytics tracking to monitor user behavior and identify pain points. Use Salesforce's Lightning Usage App for adoption metrics. Conduct regular user feedback sessions and iterate on design improvements based on data-driven insights.
Tools
- Lightning Web Components
- Salesforce Mobile SDK
- Chrome DevTools for performance analysis
- Experience Cloud
- App Builder
Online References
Governance & Compliance
Establish processes and controls for sustainable development and regulatory compliance.
Key Practices
CI/CD with Copado / Gearset
: Implement continuous integration and deployment pipelines using Copado or Gearset for automated testing, validation, and deployment. Set up multiple sandbox environments (dev, staging, UAT) with automated promotion between stages. Implement quality gates that prevent deployment of code with low test coverage or security vulnerabilities. Use deployment history tracking for audit compliance and rollback capabilities.Sandbox & release strategy
: Maintain a structured sandbox hierarchy with dedicated environments for development, testing, training, and staging. Implement release management processes with change approval workflows and deployment windows. Use sandbox templates for consistent environment setup and data masking for sensitive information. Establish release calendars and communication protocols for production deployments.Audit trails and documentation
: Enable comprehensive audit logging using Field Audit Trail and Setup Audit Trail to track all configuration changes. Implement change management documentation for all deployments and customizations. Maintain technical debt registers and conduct regular code quality assessments. Create architecture decision records (ADRs) to document important technical choices and their rationales.Implement version control and branching strategies
: Use Git with a branching strategy like GitFlow or trunk-based development. Implement pre-commit hooks for code quality checks and automated testing. Use GitHub/GitLab for code reviews, issue tracking, and release management. Maintain separate repositories for managed packages and implement semantic versioning for releases.Automate testing and quality gates
: Implement automated unit tests, integration tests, and end-to-end tests with minimum 75% code coverage requirements. Use tools like Selenium for UI testing and Postman for API testing. Set up quality gates that block deployments based on test failures, code quality metrics, or security scan results. Implement performance regression testing for critical user paths.Maintain comprehensive documentation
: Create and maintain technical documentation using tools like Confluence, GitHub Wiki, or ReadMe. Document system architecture, data flows, integration points, and business processes. Implement API documentation with Swagger/OpenAPI specifications. Maintain runbooks for incident response and operational procedures.Conduct regular architecture reviews
: Schedule quarterly architecture review meetings to assess technical debt, scalability concerns, and alignment with best practices. Review performance metrics, error rates, and user adoption data. Evaluate new Salesforce features and plan migration strategies. Document architectural decisions and maintain a technology roadmap.Manage third-party packages and dependencies
: Track all installed packages (managed and unmanaged) with their versions and security status. Implement package governance policies for evaluation, testing, and approval. Monitor package dependencies for security vulnerabilities and plan upgrade paths. Use Salesforce's AppExchange security reviews and maintain package compatibility matrices.Establish data retention and deletion policies
: Define data retention policies based on business requirements and regulatory compliance (GDPR, CCPA, etc.). Implement automated data deletion processes for expired records. Use Salesforce's Data Retention policies for platform-managed cleanup. Maintain audit trails for data deletion activities and implement data archival strategies for long-term retention needs.
Tools
- Git / GitHub
- Jenkins / GitLab CI
- Salesforce CLI
- Org Comparison Tools
- Metadata API