Sub topic 14
Generating synthetic data instead of copying it
This chapter assumes you can run sf commands, read a plan file, and write basic Apex. It also assumes you know what an external ID field is. Earlier chapters exported real records and imported them. Here you generate records from rules instead, so no production row ever reaches a scratch org or developer sandbox.
Why generate instead of copy
Copying records with sf data export tree is quick, but it carries three costs:
- Sensitive data travels with it. Names, emails, and phone numbers in a production export are personal data. A JSON file on a laptop or in a repository is a leak waiting to happen.
- The source org drifts. A query like
WHERE Industry = 'Technology' LIMIT 10returns different rows next month. Tests written against "whatever came back" break without any code change. - You can't dial the volume. If the source has 10 matching accounts, you get 10. You can't ask for 5,000 to check a batch job or a list view.
Synthetic data reverses these. You describe the shape of the data, and a generator produces as many records as you ask for. The values look realistic but belong to no real person.
| Concern | Copied data | Synthetic data |
|---|---|---|
| Privacy risk | Real values need masking or filtering | None, if no real values are used as input |
| Reproducibility | Depends on the source org's state | Depends on the recipe, which lives in version control |
| Volume control | Limited by the source | Set by a count |
| Realistic edge cases | Real oddities appear naturally | You must add them on purpose |
| Setup effort | Low | Higher at first |
The last row matters. Real data contains accents, very long names, empty fields, and duplicates that no one planned. Generated data has only the cases you describe, so you have to describe them.
Two ways to generate
You can generate data outside Salesforce and load it, or generate it inside the org with Apex. The diagram shows both paths.
The external-tool path suits large volumes and varied, realistic values. The Apex path needs no extra tools and can build related records in a single transaction. For most scratch-org setups, start with Apex and move to a generator once you need volume or realism.
Generating with an Apex script
An Apex script can produce data from loop counters. That makes it deterministic: run it twice and you get the same records. Pair that with an external ID and the script is also safe to re-run, as the earlier chapter on idempotent scripts explained.
This script assumes Account and Contact each have a text field named External_Id__c marked as an external ID.
List<String> industries = new List<String>{
'Technology', 'Finance', 'Retail', 'Healthcare'
};
List<Account> accounts = new List<Account>();
for (Integer i = 1; i <= 50; i++) {
accounts.add(new Account(
Name = 'Synthetic Account ' + i,
Industry = industries[Math.mod(i, industries.size())],
External_Id__c = 'SYN-ACC-' + i
));
}
Database.upsert(accounts, Account.External_Id__c, true);
List<Contact> contacts = new List<Contact>();
for (Integer i = 0; i < accounts.size(); i++) {
for (Integer j = 1; j <= 3; j++) {
contacts.add(new Contact(
FirstName = 'Test',
LastName = 'Contact ' + (i + 1) + '-' + j,
Email = 'contact' + (i + 1) + '.' + j + '@example.com',
AccountId = accounts[i].Id,
External_Id__c = 'SYN-CON-' + (i + 1) + '-' + j
));
}
}
Database.upsert(contacts, Contact.External_Id__c, true);Four details make this script safe and useful:
- Use
example.comfor email domains. That domain is reserved and never delivers mail. If a workflow or flow sends email in a sandbox, a made-up address at a real domain could reach a stranger. - Cycle values with
Math.mod. Every industry appears, so reports and filters have something to group on. - Keep the external ID tied to the loop index. The same index always produces the same key, so a second run updates rows rather than duplicating them.
- Pass
trueforallOrNone. A failed row stops the run with an error. This is easier to debug than a half-seeded org.
Run it with sf apex run --file scripts/apex/synthetic.apex --target-org my-scratch.
Apex has limits. A single anonymous run can insert at most 10,000 rows through DML, so this approach tops out well below bulk volumes. Anonymous Apex also cannot produce "realistic" names without a hand-written list.
Generating with Snowfakery
Snowfakery is an open-source tool from Salesforce.org for generating related records from a YAML recipe. You install it with pip install snowfakery. A recipe lists objects, how many of each to create, and a rule for each field. The fake keyword draws a realistic value, such as a company name or an email address.
- object: Account
count: 10
fields:
Name:
fake: Company
Industry: Technology
External_Id__c: SEED-${{id}}
friends:
- object: Contact
count: 3
fields:
FirstName:
fake: FirstName
LastName:
fake: LastName
Email:
fake: Email
AccountId:
reference: AccountThe friends block creates three contacts for each account. reference: Account points each contact at the account created just before it. The ${{id}} expression inserts the row counter, which gives each account a stable key such as SEED-1.
Save the recipe as data/recipe.yml and generate CSV files:
snowfakery data/recipe.yml --output-format csv --output-folder data/generatedThis writes one CSV per object, Account.csv and Contact.csv.
What to watch for when loading
Snowfakery's CSV output has two properties that affect loading.
First, the AccountId column in Contact.csv holds the recipe's row number for the account, not a Salesforce ID. A plain sf data upsert bulk call cannot resolve that value, because the org assigns real IDs only after the accounts exist. You have three options:
- Load through CumulusCI, which has tasks that generate data from a recipe and map references to real IDs.
- Load accounts first, then rewrite the contact CSV so it uses a relationship column that points at the account's external ID, such as
Account.External_Id__c. - Use the Apex approach above, where references come from the IDs the org just returned.
Second, the values from fake can differ from run to run. The external ID above comes from the row counter, not from a fake value, so re-runs still match the same rows. Never build a key from a faked name or email.
Designing synthetic data that tests something
Generated data is only useful if it exercises your code. Some habits help:
- Cover each branch. If a trigger behaves differently for accounts with no contacts, generate some accounts with none.
- Include awkward values on purpose. Add a name with an apostrophe, one at the maximum field length, and one with non-Latin characters.
- Respect validation rules. Synthetic rows go through the same validation rules and required-field checks as user input. If a rule needs a Billing Country when Industry is set, the generator must supply one. This is the most common cause of failed loads.
- Keep a small default set. Load 50 accounts for daily work. Add a separate recipe or a count parameter for a 5,000-row performance run, and keep that out of the default scratch-org setup.
- Version the generator, not the output. Commit the recipe or Apex script. Treat generated CSV files as build artifacts and add them to
.gitignore.
Choosing between the approaches
Use Apex when the dataset is small, relationships are simple, and you want no tooling beyond the CLI. Use a generator such as Snowfakery when you need thousands of rows, varied realistic values, or several linked objects with different counts. Copy and mask real data only when a test depends on real-world structure that you can't describe in rules, and then follow the sensitive-data practices from the earlier chapter.
Exercise
A teammate's seed script builds each Contact's external ID from fake: Email, so the key is something like [email protected]. The script uses bulk upsert. What goes wrong on the second run, and how do you fix it?
Show answer
The faked email is different on every run, so the external IDs never match existing rows. Each upsert inserts new contacts instead of updating the old ones, and duplicates pile up. Fix it by deriving the external ID from something stable, such as the row counter (SEED-CON-${{id}}), and keep the email as an ordinary field.
Exercise
You need 20,000 synthetic Accounts in a scratch org for a performance test. Why is a single anonymous Apex script a poor fit, and what would you use instead?
Show answer
A single anonymous Apex run is capped at 10,000 DML rows, so the script would fail partway through or need splitting. Generate the records with a tool such as Snowfakery into CSV files and load them with sf data upsert bulk using an external ID field, which uses the Bulk API and handles large volumes.