Sub topic 7
Scratch org lifespan and limits
Scratch orgs are disposable by design. Every scratch org has an expiration date, and your Dev Hub caps how many you can create and keep. This chapter covers how the lifespan works, which limits apply, how to check your usage, and how to design your workflow around these constraints.
This chapter assumes you can already create a scratch org from a definition file and authorize a Dev Hub with the Salesforce CLI.
How the lifespan works
A scratch org lives for a number of days that you set when you create it.
- The default duration is 7 days.
- The maximum is 30 days.
- The minimum is 1 day.
You set the value with --duration-days on sf org create scratch. The clock starts at creation. When the expiration date passes, Salesforce deletes the org and everything in it. You cannot extend the lifespan, and you cannot recover an expired org.
sf org create scratch \
--definition-file config/project-scratch-def.json \
--alias feature-login \
--duration-days 14 \
--target-org devhubLong durations are not always better. A scratch org is meant to hold a known state that your source can rebuild at any time. A 30-day org tends to collect manual changes that never reach version control. A short duration keeps you honest, because if the org disappears tomorrow you should lose nothing.
| Use | Typical duration |
|---|---|
| Automated test run in CI | 1 day |
| Short feature or bug fix | 3 to 7 days |
| Larger feature, demo, or review environment | 14 to 30 days |
Two limits on the Dev Hub
Scratch org limits apply to the Dev Hub org, not to individual users. Everyone who creates scratch orgs against the same Dev Hub shares the same allocation. Two limits matter.
| Limit name | What it counts | When it frees up |
|---|---|---|
| `ActiveScratchOrgs` | Scratch orgs that currently exist (not expired or deleted) | When an org expires or you delete it |
| `DailyScratchOrgs` | Scratch orgs created in the last 24 hours | As creation events age out of the 24-hour window |
The two limits behave differently, and this causes the most confusion.
- Deleting a scratch org lowers your active count immediately.
- Deleting a scratch org does not give back the daily creation it used. The daily count tracks creations, so a create-and-delete loop in CI can exhaust the daily limit even though few orgs are active at any moment.
The numeric values depend on the Dev Hub edition. Larger editions get larger allocations, and a trial or free Developer Edition Dev Hub gets smaller ones. Salesforce changes these numbers over time, so do not hard-code them from a tutorial. Read the current values from your own Dev Hub, as shown in the next section.
Checking your usage
Use the CLI to see both limits for a Dev Hub.
sf org list limits --target-org devhubThe output is a table of limit names with Max and Remaining columns. Look for ActiveScratchOrgs and DailyScratchOrgs. Add --json if you want to process the result in a script.
To see which scratch orgs exist and when they expire, list them from the Dev Hub's side:
sf org list --allThe CLI shows scratch orgs it knows about, with their expiration dates. This only covers orgs created or authorized from your machine. Orgs that teammates or CI jobs created are not listed. To see every scratch org on the Dev Hub, query the ScratchOrgInfo object.
sf data query \
--target-org devhub \
--query "SELECT SignupUsername, Status, ExpirationDate, CreatedBy.Name FROM ScratchOrgInfo WHERE Status = 'Active' ORDER BY ExpirationDate"ScratchOrgInfo has one record per scratch org request. The Status field tells you whether the org is active, deleted, or failed. In the Dev Hub UI, the Active Scratch Orgs tab shows the same information.
Guarding against limit failures in scripts
A script that creates scratch orgs should check the remaining allocation first. Otherwise it fails partway through with a less obvious error. The following script reads the DailyScratchOrgs and ActiveScratchOrgs limits as JSON and stops early if either is exhausted. It needs jq installed.
#!/usr/bin/env bash
set -euo pipefail
DEVHUB="${1:-devhub}"
limits=$(sf org list limits --target-org "$DEVHUB" --json)
daily=$(echo "$limits" | jq '.result[] | select(.name == "DailyScratchOrgs") | .remaining')
active=$(echo "$limits" | jq '.result[] | select(.name == "ActiveScratchOrgs") | .remaining')
echo "Daily creates remaining: $daily"
echo "Active slots remaining: $active"
if [ "$daily" -lt 1 ] || [ "$active" -lt 1 ]; then
echo "No scratch org capacity available on $DEVHUB." >&2
exit 1
fi
sf org create scratch \
--definition-file config/project-scratch-def.json \
--alias "ci-$(date +%s)" \
--duration-days 1 \
--target-org "$DEVHUB"The check has a race. If several jobs run at once, they can all read "1 remaining" and then try to create. Treat the check as an early warning, not a lock. Your pipeline should still handle a failed creation cleanly.
Cleaning up
Active slots are a shared resource, so clean up after yourself. Delete a scratch org when you finish with it:
sf org delete scratch --target-org feature-login --no-promptIn CI, delete the org in a step that always runs, including after failed tests. Otherwise failed runs leave orgs behind until they expire. A 1-day duration on CI orgs is a cheap safety net, because even an orphaned org disappears within a day.
For orgs that people forget about, you can run a scheduled job that queries ScratchOrgInfo for old active orgs. Deleting someone else's org is disruptive, so agree on a policy first, such as a maximum duration for shared Dev Hubs.
Other limits to expect
The allocation limits are not the only constraints. Scratch orgs differ from sandboxes in other ways that affect planning.
- Storage: Scratch orgs have small data and file storage allocations compared with Partial Copy or Full sandboxes. Large data loads can fail. Check Setup > Storage Usage in the org if loads behave oddly.
- No production data: A scratch org starts with no data of your own, so you must load test data after creation (covered in the test data chapter). The
hasSampleDatasetting in the definition file only adds Salesforce's generic sample records. - The Dev Hub is required: Scratch orgs depend on their Dev Hub. If a scratch org's Dev Hub is unavailable or you lose access to it, you cannot create new ones. A scratch org cannot itself be a Dev Hub.
- Creation takes time: Creating an org usually takes a few minutes, and the time grows with the features and settings in the definition file. Creation time counts against how often you can afford to recreate orgs in a pipeline.
- Features depend on the definition file: The edition, features, and settings in the definition file decide what the org can do. A feature you do not request is not available.
Designing around the limits
Treat scratch orgs as cheap but not free, and plan for the shared allocation.
- Match duration to purpose. Use 1 day for CI and 7 days for typical feature work. Reserve long durations for orgs that serve a real need, such as a demo.
- Keep source as the record of truth. If the org can vanish at any time, the project in version control must be able to rebuild it. This makes expiration harmless.
- Monitor the daily limit in CI. Many parallel pull request builds can burn through daily creates. If you see failures in the afternoon, count how many orgs your pipeline creates per run.
- Reuse where it is safe. For long-lived feature work, keep one org for the duration of the feature rather than recreating it every day.
- Share the allocation fairly. On a team Dev Hub, agree on durations and cleanup rules. One runaway script can block everyone for 24 hours.
- Know the fallback. When you need long-lived configuration, a persistent shared environment, or production-sized data, use a sandbox. Scratch orgs are the wrong tool for those.
Common mistakes
- Recreating in a loop: Deleting and recreating an org to "get a clean state" many times a day uses daily creates without lowering them.
- Forgetting to pull: Letting an org expire with unpulled changes loses that work.
- Assuming the CLI list is complete:
sf org listshows only orgs your CLI knows about, so useScratchOrgInfofor the real picture. - Hard-coding limit numbers: Allocations vary by edition and change over time. Read them from
sf org list limits. - Using a 30-day duration by default: This hides drift and holds active slots longer than needed.
Exercise
Your CI pipeline creates a 1-day scratch org for every pull request and always deletes it when the run ends. At midday builds start failing with a message that the scratch org limit was reached, yet sf org list limits shows plenty of ActiveScratchOrgs remaining. Which limit is the likely cause, and what are two ways to reduce the problem?
Show answer
The DailyScratchOrgs limit is exhausted. Deleting an org frees an active slot but does not give back the daily creation it used, so a busy pipeline that creates many short-lived orgs can run out of daily creates. To reduce the problem, create fewer orgs per run, for example by running jobs that need an org only on the pull requests that require it, or by sharing one org across several test jobs. You can also check DailyScratchOrgs before creating and fail fast with a clear message, and use a Dev Hub in an edition with a higher allocation.
Exercise
A teammate says a scratch org you created with --duration-days 30 can be extended by running a command a few days before it expires. Is that correct? What should you do before the org expires?
Show answer
No. A scratch org's duration is fixed at creation, with a maximum of 30 days, and it cannot be extended. Before it expires, run sf project retrieve start (or pull changes if you use source tracking) to bring any metadata changes into your project, commit them, and save any test data you need elsewhere. Then create a new scratch org from the definition file and push the source to it.