Home / security / apex-managed-sharing-patterns
apex-managed-sharing-patterns
Grant row-level access programmatically via __Share records when declarative sharing rules cannot express the policy. NOT for OWD, role hierarchy, or criteria-based sharing rule design — use admin/sharing-and-visibility.
Open the skill folder on GitHub
Apex Managed Sharing Patterns
Apex managed sharing writes rows into an object's __Share table with a developer-defined Apex sharing reason, so the platform maintains those rows across owner changes instead of reclaiming them. It is the last mechanism in the record-access model, reached only when org-wide defaults, the role hierarchy, sharing rules, teams, and manual sharing cannot express the policy.
The one constraint that determines whether this skill applies at all:
"Apex sharing reasons and Apex managed sharing recalculation are only available for custom objects." — Apex Developer Guide, Understanding Sharing
If the record needing programmatic access is an Opportunity, Account, Case, or any other standard object, Apex managed sharing is not available. You can still insert OpportunityShare rows from Apex, but they are user managed (manual) shares with RowCause = 'Manual', and the platform deletes them the moment the record owner changes. Establish which side of that line you are on before designing anything.
Before Starting
Answer these four questions. Three of the four regularly kill the design.
- Is the target a custom object? If not, Apex managed sharing is off the
table. Route to the built-in team feature (
AccountTeamMember,OpportunityTeamMember,CaseTeamMember), to criteria-based sharing rules, or accept manual-share lifecycle and plan the re-grant on owner change. - Is the object on the detail side of a master-detail relationship? Detail
records have no
__Shareobject at all; their access is derived from the master and the relationship's sharing setting. Changing that is a data-model migration, not a configuration change. - What is the org-wide default? A share row must grant access more
permissive than the OWD or the platform rejects it. On a Public Read/Write object no share row of any level is valid, and on Public Read Only a
Readshare is rejected. - Can a declarative mechanism still do this? The Salesforce Security Guide
allows "up to 300 total sharing rules for each object, including up to 50 criteria-based or guest user sharing rules." Teams routinely reach for code long before they are anywhere near that. Read