Anonymous Apex is fast, powerful, and unaudited. Treat every production run as a controlled change: prepared script, peer review, retained log.
- Write the script in version control
Create the .apex file in the repo, even if it will not be deployed. The file is the artifact that change reviews attach to and that future engineers can read.
- Peer-review the script
Walk the script through a second engineer. Confirm DML counts, SOQL counts, and the records the script touches. Anonymous Apex does not have unit tests, so review is the only safety net.
- Run in sandbox first
Execute the script in a representative sandbox. Inspect the resulting data and the debug log. Only after a clean sandbox run should production be considered.
- Execute in production with logging on
Set the Apex debug log level to FINER. Run via the Developer Console, CLI, or Workbench. Watch for unexpected errors or limit warnings.
- Archive the log and the script
Save the debug log and the .apex script to the change ticket or release record. Anonymous Apex leaves no audit trail; preserving these two files is the audit trail.
- Anonymous Apex runs as the user who launches it, including their sharing model. To bypass sharing, wrap the logic in a without sharing class.
- Governor limits apply identically to a synchronous transaction. Large data fixes must call a batch class, not run inline.
- There is no test coverage requirement and no metadata trail. Audit logging falls on the operator, not the platform.
- Errors silently fail unless explicitly caught. Use try/catch with System.debug to surface any failures in the log.