Sub topic 11
Preparing a refreshed sandbox with a post-copy Apex class
This chapter assumes you can write basic Apex, know how sandbox types and templates differ (covered in the previous chapter), and have the Salesforce CLI authorized to a production org or Dev Hub. It covers how to make a sandbox usable the moment its creation or refresh finishes, without a person logging in to patch it up.
Why a post-copy class exists
A sandbox copy brings across metadata and, depending on the sandbox type and template, some data. The copy has gaps. Integration endpoints still point at production systems. Email deliverability may be wrong. Test users, queues, and a known set of reference records are missing. Doing these steps by hand after every refresh is slow and easy to get wrong.
Salesforce lets you register an Apex class that runs once, automatically, after the sandbox has been created or refreshed. The class implements the SandboxPostCopy interface. It runs in the new sandbox, not in production.
The SandboxPostCopy interface
The interface has one method, runApexClass(SandboxContext context). The SandboxContext argument exposes three read-only values:
| Method | Returns |
|---|---|
| `organizationId()` | The ID of the sandbox org that was just created |
| `sandboxId()` | The ID of the sandbox record |
| `sandboxName()` | The name of the sandbox |
Here is the class from this tutorial's examples:
global class SeedAfterRefresh implements SandboxPostCopy {
global void runApexClass(SandboxContext context) {
System.debug('Seeding sandbox ' + context.sandboxName());
insert new Account(Name = 'Post-copy Seed Account');
}
}The class and its method must be global, because the interface is part of a managed API. The class must also have a public or global no-argument constructor. The implicit one is enough here.
How the class is attached to a sandbox
The class is not found by name or by convention. You choose it when you create or refresh the sandbox. In Setup, the sandbox creation and refresh wizard has an Apex class field. You pick a class that implements SandboxPostCopy. With the CLI, you name the class in the sandbox definition file. Because of this, the class must exist in production before the copy starts. Deploy it to production first. A class that only exists in a scratch org or in another sandbox is not available.
A sandbox definition file looks like this:
{
"sandboxName": "qa1",
"licenseType": "Developer",
"apexClassName": "SeedAfterRefresh"
}You can then create the sandbox from the CLI:
sf org create sandbox \
--definition-file config/sandbox-def.json \
--alias qa1 \
--target-org my-prod \
--wait 60Check the definition file keys against your CLI version with sf org create sandbox --help. The key names shown here are the ones the command documents at the time of writing.
What runs, and as whom
The following points matter when you design the class.
- The class runs after the copy finishes, when the sandbox is otherwise ready. Its work is not part of the copy itself.
- It runs as the user who started the creation or refresh. Sharing, field-level security, and permissions follow that user's profile.
- It runs in a single Apex transaction, so governor limits apply. Roughly 10,000 DML rows and 150 DML statements are the usual ceiling. A large seed will fail partway.
- A failure does not stop the sandbox from being created. The sandbox exists, but your setup work may be incomplete.
- Automation in the sandbox is live. Triggers, flows, and validation rules fire as your inserts happen, exactly as they do for any DML.
The last point catches many teams. If a validation rule requires a field you did not set, the insert throws an exception and the rest of the method does not run.
Structure the class for safety
A post-copy class should do little itself. Put the logic in a separate class you can unit-test, and make the entry point defensive. Catch exceptions so that one failed step does not hide the others, and log what happened.
global class SeedAfterRefresh implements SandboxPostCopy {
global void runApexClass(SandboxContext context) {
String name = context.sandboxName();
System.debug('Post-copy start for ' + name);
try {
SandboxSeeder.seedAccounts();
} catch (Exception e) {
System.debug(LoggingLevel.ERROR, 'Account seed failed: ' + e.getMessage());
}
try {
SandboxSeeder.maskSensitiveValues();
} catch (Exception e) {
System.debug(LoggingLevel.ERROR, 'Masking failed: ' + e.getMessage());
}
}
}public class SandboxSeeder {
public static void seedAccounts() {
List<Account> accounts = new List<Account>();
for (Integer i = 1; i <= 5; i++) {
accounts.add(new Account(
Name = 'Post-copy Seed Account ' + i,
Industry = 'Technology'
));
}
insert accounts;
}
public static void maskSensitiveValues() {
List<Contact> contacts = [
SELECT Id, Email
FROM Contact
WHERE Email != null AND (NOT Email LIKE '%.invalid')
LIMIT 200
];
for (Contact c : contacts) {
c.Email = c.Email.replace('@', '=') + '@example.invalid';
}
update contacts;
}
}Note that System.debug output from a post-copy run is hard to find, so consider also writing failures to a custom log object, if you have one. Debug logs only exist if a trace flag covers the running user.
Make the class idempotent
A refresh replaces the sandbox, so the class normally starts from a clean copy. That is not always true. Salesforce can run it again if you re-run it manually in tests, and a partial-copy sandbox may already contain records that match yours. Guard inserts so a second run does not create duplicates. Use an external ID and upsert, or check for existing rows first.
public class SandboxSeeder {
public static void seedAccountsOnce() {
Integer existing = [
SELECT COUNT() FROM Account WHERE Name LIKE 'Post-copy Seed Account%'
];
if (existing > 0) {
return;
}
List<Account> accounts = new List<Account>();
for (Integer i = 1; i <= 5; i++) {
accounts.add(new Account(Name = 'Post-copy Seed Account ' + i));
}
insert accounts;
}
}Testing the class
You do not need to refresh a sandbox to test the logic. Salesforce provides Test.testSandboxPostCopyScript, which runs your class inside a test context.
@IsTest
private class SeedAfterRefreshTest {
@IsTest
static void seedsAccountsAfterCopy() {
Test.startTest();
Test.testSandboxPostCopyScript(
new SeedAfterRefresh(),
UserInfo.getOrganizationId(),
UserInfo.getOrganizationId(),
'qa1'
);
Test.stopTest();
System.assertNotEquals(0, [SELECT COUNT() FROM Account]);
}
}The arguments are the class instance, the production org ID, the sandbox org ID, and the sandbox name. Using the current org ID for both is fine in a test. Because the class goes to production, this test also counts toward the code coverage that a production deployment requires.
The refresh flow
The diagram shows where the post-copy class sits in a refresh.
Common problems
- The class is not in the picker. It is not deployed to production, or it does not implement
SandboxPostCopy, or it is notglobal. - Nothing was seeded and no error is visible. The class likely threw an exception that you did not catch, or the logs were not captured. Add logging and try again.
- Inserts fail on required fields or validation rules. Production rules are active in the sandbox. Set every required field, or design the seed around the rules.
- Limits exceeded. Move bulky loads out of the class. Use a queueable job for medium volumes, or load larger sets afterwards with the bulk commands from the earlier chapter.
- Seed differs from the scratch org dataset. Keep one source of truth where you can, such as the same
SandboxSeederlogic used by your Apex script, so both environments get matching records.
A reasonable pattern is to keep the post-copy class small: masking, endpoint changes, user setup, and a minimal set of reference records. Then load larger datasets with sf data import tree or bulk upsert once the sandbox is ready.
Exercise
A teammate wrote a class that implements SandboxPostCopy and deployed it only to a developer sandbox. They cannot find it when refreshing a QA sandbox from production. What is wrong, and what is the fix?
Show answer
The class must exist in the production org that the sandbox is copied from, because that is where the refresh is started and where the class is selected. Deploy the class, with a passing test, to production. Then refresh the QA sandbox and select the class.
Exercise
Your post-copy class inserts 12,000 records in one loop and the seed stops with a limit error. Give two ways to fix it.
Show answer
Keep the class small and move the large load elsewhere. First option: split the work into a queueable job that processes batches in separate transactions. Second option: have the class create only minimal reference records, then load the large dataset after the refresh with sf data import tree or sf data upsert bulk.