Sub topic 12
Managing scratch org lifetime and cleaning up
This chapter assumes you have a Dev Hub authorized as my-hub, a DX project, and a scratch org created with sf org create scratch. Scratch orgs are temporary. Knowing how long they live and how to remove them keeps your Dev Hub tidy and your work safe.
How long a scratch org lives
Every scratch org has an expiration date. You set it at creation with --duration-days. The default is 7 days. The maximum is 30 days. When the date passes, Salesforce deletes the org and everything in it.
sf org create scratch --definition-file config/project-scratch-def.json --alias my-scratch --duration-days 14 --set-defaultYou can't extend a scratch org after you create it. If you need more time, create a new org and deploy your source to it.
Checking the expiration date
sf org display shows the expiration date along with the username and instance URL.
sf org display --target-org my-scratchLook for the Expiration Date field. sf org list shows all orgs the CLI knows about, with the expiration dates of scratch orgs. Add --clean to remove expired or deleted orgs from the list.
sf org list
sf org list --cleanWhat happens at expiry
The diagram shows the states of a scratch org.
An expired org leaves your local CLI list until you clean it up. Its login information stays on your machine, but the org no longer exists. Commands that target it fail.
Deleting a scratch org early
Delete an org when you finish with it. Each active scratch org counts against your Dev Hub's limit, so deleting frees a slot.
sf org delete scratch --target-org my-scratch --no-promptWithout --no-prompt, the CLI asks you to confirm. Keep the prompt when you work by hand. Use --no-prompt in scripts.
A cleanup routine
- Retrieve any changes you want to keep.
- Commit them to version control.
- Delete the org.
- Run
sf org list --cleanto remove stale entries.
Choosing a duration
Match the duration to the job.
| Use | Suggested duration |
|---|---|
| Quick experiment or bug check | 1 to 3 days |
| Feature development | 7 to 14 days |
| Long-running testing | Up to 30 days |
| Automated tests in CI | 1 day |
Short durations make forgotten orgs disappear on their own. That protects your active scratch org limit.
Exercise
You created a scratch org with the default duration and need it for two more weeks than that allows. What are your options, and what should you do before switching?
Show answer
You can't extend an existing scratch org. Retrieve your changes with sf project retrieve start, commit them, then create a new scratch org with a longer --duration-days value (up to 30). Deploy your source to the new org and delete the old one to free a slot.