Definition
Apex-Managed Sharing is a programmatic method of granting record access using Apex code. Developers write Apex to insert sharing records (such as AccountShare or CustomObject__Share) with a reason field set to a custom Apex sharing reason. Unlike standard sharing rules, Apex-managed sharing records can only be created or deleted by Apex code and are preserved during sharing recalculations.
Real-World Example
At their company, a Salesforce developer at CodeBridge leverages Apex-Managed Sharing to create a robust integration between Salesforce and an external system. Using Apex-Managed Sharing, the developer builds an efficient solution that syncs data in near real-time, handles error scenarios gracefully, and includes detailed logging for troubleshooting.
Why Apex-Managed Sharing Matters
Apex-Managed Sharing works by inserting records into the Share object that exists for every custom object (and for standard objects like Account, Opportunity, and Case). For a custom object named Project__c, the associated share object is Project__Share, and each record in it grants a specific user or group access to a specific Project__c record. What makes Apex-Managed Sharing distinct from standard sharing rules is the RowCause field: Apex sets this to a custom Apex Sharing Reason defined on the object, which tells Salesforce that this share record is owned by code and should not be touched during sharing recalculations.
The preservation-across-recalculations behavior is the whole reason Apex-Managed Sharing exists. If you insert a regular sharing record with RowCause 'Manual', Salesforce will wipe it whenever the record's owner changes or a sharing recalculation runs. With a custom Apex Sharing Reason, the share survives, because Salesforce knows your code is authoritative for that access grant. This makes it the right pattern for complex access logic like 'grant read access to every user in the record's region, plus any account executive listed on the related Opportunity'.
How Organizations Use Apex-Managed Sharing
- •CodeBridge — Built an Apex-Managed Sharing trigger on a custom Project__c object that grants read access to every member of the project team, which is stored in a related list. The trigger inserts Project__Share records with a custom reason called 'Project_Team_Member', so team membership changes propagate to sharing automatically.
- •TerraForm Tech — Uses Apex-Managed Sharing to implement a compliance requirement where certain regulated records must be visible only to users in specific compliance groups. The logic is too dynamic for criteria-based sharing rules, so a scheduled Apex job maintains the shares nightly.
- •Quantum Labs — Replaced a brittle workflow-based sharing approach with Apex-Managed Sharing after discovering that sharing recalculations were silently wiping their access grants. The custom Apex Sharing Reason fixed the problem permanently.
