Sub topic 13
Pitfalls and good practices
This chapter assumes you know the four sandbox types, how a scratch org is created from a Dev Hub, and the basics of the Salesforce CLI and Git. It collects the mistakes teams most often make with these environments, explains why each one happens, and gives a practice that prevents it.
Pitfalls with sandboxes
Treating a sandbox as the source of truth
A sandbox is a copy of production at one moment. A refresh replaces its metadata and data with a new copy. Any change that exists only in the sandbox is lost. Teams get caught when a developer builds a flow or a permission set directly in a long-lived Developer sandbox and never commits it.
Good practice: version control holds the truth, and orgs are disposable copies of it. Commit metadata before every refresh. If a change exists only in an org, retrieve it now:
sf project retrieve start --target-org dev1 --manifest manifest/package.xml
git statusLetting sandboxes go stale
Refresh intervals limit how often you can refresh each type. The usual limits are 1 day for Developer and Developer Pro, 5 days for Partial Copy, and 29 days for Full. Check your own org's limits, because they can change. A sandbox that is months old drifts from production. Tests pass there and fail after deployment because production has newer metadata, different data volumes, or changed settings.
Good practice: set a refresh schedule for each sandbox, write it down, and tell the people who use it. Refresh a Full sandbox before a major release rehearsal, not after.
Refreshing without a plan for what comes next
After a refresh, a sandbox has production's configuration but not the setup your team needs. Common leftovers are:
- Integration endpoints and named credentials that still point at production services.
- Scheduled jobs and automation that you do not want running in a test org.
- Missing test users, or users with the wrong permissions.
- Email deliverability settings that need checking.
Doing this by hand after each refresh is slow and easy to get wrong. Use a SandboxPostCopy class so the steps run every time.
Unmasked production data
Full and Partial Copy sandboxes can contain real customer data. Developer and Developer Pro sandboxes copy metadata only, so they are lower risk. A sandbox usually has weaker access controls than production. More people have access, and debug logs and exports leave the org easily.
Good practice:
- Treat any sandbox that holds copied production data as sensitive.
- Mask or anonymize sensitive fields at copy time. Salesforce Data Mask is an add-on for this.
- Limit who gets access and restrict profile and permission set assignments.
- Prefer sandboxes with no copied data, or scratch orgs with generated data, whenever the task does not need real records.
Pitfalls with scratch orgs
Definition file drift
A scratch org matches production only as far as its definition file says. If production enables a feature or setting and the file does not, developers build and test against an org that behaves differently. This is the scratch-org version of a stale sandbox.
Good practice: keep config/project-scratch-def.json in the repository and review it in pull requests like code. When an admin turns on a feature in production that your code depends on, update the file in the same change. Add only the features and settings your project needs. A short file is easier to keep accurate.
Ignoring source tracking
Source tracking records which components changed in the org and which changed locally. If you work around it, for example by deploying with a manifest into an org that tracks changes, you lose its conflict detection. You can also overwrite a teammate's change or miss one of your own.
Good practice: use sf project deploy start and sf project retrieve start without a manifest in a tracked scratch org. Read the output for conflicts before using overwrite options. Settings and some metadata types are not always tracked, so check before you assume that "no changes" means nothing changed.
Hitting allocation limits
A Dev Hub limits both the number of active scratch orgs and the number created per day. Both limits depend on the Dev Hub's edition. Teams that create an org for every pull request, and never delete them, hit the limit during a busy week and block all development.
Good practice: check the limits before they bite, and delete orgs you no longer need.
sf org list limits --target-org devhub
sf org list --cleanIn the first command, look for ActiveScratchOrgs and DailyScratchOrgs in the output. The second command removes expired scratch orgs from your local list. It does not free allocation for orgs that are still active.
Using a long lifespan as storage
A scratch org lasts from 1 to 30 days. The default is 7 days. Extending the lifespan to keep work safe is a trap. When the org expires, everything in it is gone, including data and anything never retrieved.
Good practice: set the shortest duration that fits the task. Push your source to Git daily. Make the org rebuildable from the repository with one script.
Pitfalls in the pipeline
Skipping environments, or adding too many
Teams sometimes deploy straight from a developer environment to production. Others add many intermediate sandboxes, each of which needs refreshing and drifts from the others. Both extremes cause surprises.
Good practice: give each environment one clear job, and remove any environment that has no job. A common shape is shown below.
Different deployment paths in different orgs
If developers deploy by hand in one org, use change sets in another, and use the CLI in a third, the orgs diverge in ways that nobody can reconstruct. The usual symptom is a deployment that works in the sandbox and fails in production because of a missing dependency.
Good practice: use the same deployment method for every environment above the developer level. Automate it, and run it from the same repository.
Configuration drift
Drift is any difference between environments that nobody chose. It comes from manual edits, partial deployments, and skipped refreshes. It hides bugs, because a test result in one org says little about another.
Good practice:
- Make changes in the lowest environment and promote them through the pipeline. Do not make hotfixes directly in production without also committing them.
- Compare environments on a schedule. Retrieve metadata from each and diff it against the repository.
- Treat a manual change as a defect to be captured in source, not as a finished task.
Good practices that apply everywhere
Automate the repeatable parts
Automate everything you do more than twice: creating the org, deploying, assigning permission sets, loading data. A single script lets a new developer get a working org in minutes. The same script then runs in CI.
This example creates a scratch org, runs tests, and always deletes the org, even when a step fails:
#!/usr/bin/env bash
set -euo pipefail
ORG_ALIAS="ci-${GITHUB_RUN_ID:-local}"
cleanup() {
sf org delete scratch --target-org "$ORG_ALIAS" --no-prompt || true
}
trap cleanup EXIT
sf org create scratch \
--definition-file config/project-scratch-def.json \
--alias "$ORG_ALIAS" \
--duration-days 1 \
--target-org devhub
sf project deploy start --target-org "$ORG_ALIAS"
sf apex run test --target-org "$ORG_ALIAS" --test-level RunLocalTests --result-format human --wait 20The trap line is what prevents leaked scratch orgs, which are the usual cause of exhausted allocations in CI. The one-day duration is a second safeguard: if cleanup fails, the org still expires.
Make post-copy setup safe to repeat
A SandboxPostCopy class runs after every refresh, so write it to be idempotent. Running it twice should give the same result as running it once. Keep the class small and hand heavy data work to a batch job, because post-copy execution is subject to normal Apex limits.
This example shows the post-copy class starting a batch job that changes contact email addresses so that test activity cannot reach real customers. It is an illustration, not a complete masking solution.
global class PrepareSandbox implements SandboxPostCopy {
global void runApexClass(SandboxContext context) {
System.debug('Post-copy setup for ' + context.sandboxName());
Database.executeBatch(new MaskContactsBatch(), 200);
}
}global class MaskContactsBatch implements Database.Batchable<SObject> {
global Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator('SELECT Id, Email FROM Contact WHERE Email != null');
}
global void execute(Database.BatchableContext bc, List<Contact> scope) {
for (Contact c : scope) {
if (!c.Email.endsWith('.invalid')) {
c.Email = c.Email + '.invalid';
}
}
update scope;
}
global void finish(Database.BatchableContext bc) {}
}The endsWith check keeps the job idempotent. Without it, a second run would append .invalid again.
Test the post-copy class
Salesforce provides Test.testSandboxPostCopyScript so you can run the class in a unit test. A post-copy class that has never been run is likely to fail on the first real refresh, when you are least able to debug it.
Name and document environments
Use names that show purpose, such as dev1, qa, and uat. Record for each environment its type, owner, refresh schedule, and what data it holds. A short table in the repository's README is enough.
| Environment | Type | Owner | Refresh | Data |
|---|---|---|---|---|
| `dev1` | Developer sandbox | Platform team | Monthly | None |
| `qa` | Partial Copy | QA lead | Every two weeks | Sampled and masked |
| `uat` | Full | Release manager | Before each release | Masked |
Review the checklist regularly
Before you trust an environment, check these points:
- Is all its metadata in version control?
- When was it last refreshed, and is that on schedule?
- Does it hold production data, and is that data masked?
- Do integrations point at test services, not production?
- Can you rebuild it from a script?
Summary of pitfalls and fixes
| Pitfall | Effect | Fix |
|---|---|---|
| Work exists only in an org | Lost on refresh or expiry | Commit to Git before refresh or expiry |
| Stale sandbox | Tests pass here, fail in production | Scheduled refreshes |
| Unmasked data | Privacy and compliance exposure | Masking and restricted access |
| Definition file drift | Code tested on wrong configuration | Review the file in pull requests |
| Leaked scratch orgs | Allocation exhausted | Cleanup in CI and short durations |
| Mixed deployment methods | Environments diverge | One automated path |
Exercise
Your CI job creates a scratch org for every pull request. After two weeks, new jobs fail at the create step with a limit error, although most pull requests are closed. Name two likely causes and one fix for each.
Show answer
First, the job does not delete the org when it finishes or fails, so closed pull requests leave active orgs. Fix: delete the org in a cleanup step that always runs, such as a shell trap. Second, the job uses the default 7-day duration, so orgs stay active long after the job is done. Fix: set --duration-days 1 so any org that escapes cleanup expires quickly. You can also check sf org list limits to see how close you are to the active and daily limits.
Exercise
A Full sandbox was refreshed last night. This morning a developer reports that the integration with an external billing system is sending test invoices to the real billing system. What went wrong, and how do you prevent it on the next refresh?
Show answer
The refresh copied production configuration, including endpoints or credentials that point at the real billing service, and nothing reset them afterward. To prevent it, add a SandboxPostCopy class that points the integration at the billing system's test endpoint or disables it, make the class idempotent, and test it with Test.testSandboxPostCopyScript. Also keep a checklist item to confirm integrations before anyone uses the sandbox.