Apex Managed Sharing is the most complex part of Salesforce sharing. Take the implementation in three deliberate steps: create the Apex Sharing Reason, write the granting code, then write the recalculation code that keeps shares accurate as data changes.
- Create an Apex Sharing Reason
Setup, Object Manager, open the custom object, then Apex Sharing Reasons. Create a reason with a clear name (e.g. Specialty_Engineer_Access). The reason becomes the RowCause on every __Share row your code creates.
- Write a trigger or service class that creates shares
On the right trigger event (insert, update of the driving field), collect the eligible record-user pairs, instantiate __Share rows with the right AccessLevel and RowCause, and insert them in bulk. Run with FOR UPDATE locking or sharing.share() inside SOQL when concurrent edits are likely.
- Handle revocation on data change
When the data driving the share changes (specialty reassignment, stage rollback), delete the existing share rows with the Apex Sharing Reason and re-insert the new set. Test that no orphan share rows survive a change.
- Implement Apex Sharing Recalculation
Create a class that implements the sharing recalculation interface and register it on the object. The platform calls it during recalculation events, including manual triggers from Sharing Settings.
- Audit and monitor
Build a SOQL query that compares expected shares to actual __Share rows for a sample of records. Schedule it weekly. Drift is the most common failure mode of long-lived Apex Managed Sharing implementations.
The auto-generated sharing object for the target object.
The record being shared.
The recipient user, public group, role, or queue.
Edit, Read, or All.
Manual on standard objects, or the Apex Sharing Reason on custom objects.
Admin-defined RowCause for custom objects; required for safe recalculation.
- Standard objects do not support custom Apex Sharing Reasons. Manual is the only practical RowCause, which complicates safe recalculation.
- Forgetting to revoke shares when the driving data changes leaves stale access in place; this is the most common audit finding.
- Apex Managed Sharing share rows count against DML and storage. Mass grant patterns can blow row limits at scale.
- Recalculation triggered from Sharing Settings runs synchronously and can time out on large orgs. Plan to test recalculation against full-volume sandboxes before relying on the button.