Nov 23, 20268 min read

How to Seed a Database for Local Development

Seed scripts, fixture files, sanitized dumps and generated data compared for local development, how to make seeds idempotent and safe to run on every start, and an example where the local Postgres database is created, migrated and seeded when the app starts.

Illustration for How to Seed a Database for Local Development

A local database starts out empty, and the first developer who needs data clicks through signup and creates a few orders by hand. That lasts until a migration breaks the hand-made rows, or a new teammate clones the repo and gets an empty app.

A seed loads the same data every time the database is created. This guide compares the ways to build one.

How do you seed a database for local development?

Create the schema with your migrations, then run a seed that inserts a known set of rows, written so that running it twice changes nothing and guarded so that it can only run in local, test or preview environments. The approaches differ mainly in where the rows come from.

ApproachWhere the data comes fromGood forWatch out for
Seed on startup (Encore)A seed function in the service, run when the app starts locallyData that always matches the current schemaThe environment guard has to be right
Seed scriptA script you run after migrating, such as npm run seedTeams with any stack, explicit controlDevelopers forget to run it after a reset
SQL fixture files.sql files loaded with psql or by the appSmall, reviewable data setsFiles drift from the schema when columns change
Generated datagenerate_series or a fake data libraryVolume for pagination and query plansRandom data makes failures hard to reproduce
Sanitized dumppg_dump of staging or a scrubbed production copyRealistic distributions and edge casesPersonal data leaks if scrubbing misses a column

Should seed data go in migrations?

Only reference data that production also needs belongs in a migration, such as the list of supported currencies or the default roles a new account starts with, since every migration runs in every environment. Development data placed in a migration ships to production with the next deploy, which is how test accounts with weak passwords end up in a live database.

Keeping the two apart is a long-standing convention, and the Rails migration guide draws the same line with a separate db/seeds.rb file. Whatever stack you use, the rule is that migrations describe the schema and the seed describes a starting state for development.

How do you make a seed idempotent?

Give every seeded row a fixed natural key, such as an email address or an invoice number, and insert with ON CONFLICT DO NOTHING so a second run skips rows that already exist. Postgres documents this as the conflict clause of INSERT, and it lets the seed run on every start without failing on a unique constraint or doubling the data.

Rows that depend on other rows should look up their parent by that key instead of assuming an ID, since BIGSERIAL values differ between a fresh database and one that has been seeded twice. An INSERT ... SELECT that joins on the parent's email keeps the relationship correct whatever IDs the database assigned.

How much seed data do you need?

A handful of hand-written rows covers the cases you test by hand, such as a customer on a trial, one with an active subscription and one whose payment failed. Name them after the case they represent, so a developer reading pastdue@example.com in a log knows what it is for.

Volume is a separate need, and it shows up when a list endpoint needs pagination or a query needs an index to stay fast. Postgres can produce thousands of rows in one statement with generate_series, and deterministic expressions such as g % 10 give you a fixed mix of statuses that is the same on every machine. Fake data libraries such as Faker are useful for realistic names and addresses, and pinning the seed value keeps the output reproducible.

Can you use a production dump as seed data?

You can, but restoring a pg_dump of production copies customer emails, addresses and payment details onto every laptop that loads it, often without the access controls production has. If a realistic data shape matters, dump staging instead, or scrub the production copy by replacing personal columns before anyone downloads it, and treat the scrub script as code that gets reviewed when a new personal column appears.

Dumps also age badly as the schema moves on, since a dump taken before last week's migration fails to restore into this week's schema or needs the old migrations replayed first. Seeds written against the current schema do not have that problem.

How do you reset a local database to a clean state?

Drop the database, recreate it, apply the migrations and run the seed again, and put those steps behind one command so nobody does them by hand. A reset you trust makes it cheap to try a destructive migration locally, since getting back to a known state takes seconds.

With Docker Compose this usually means removing the volume and restarting the container. Tools that manage the local database for you often expose a reset command that does the same thing.

How does Encore seed a local database?

Encore

Encore brings infrastructure from code, so the database a service declares is the one encore run starts locally, creates and migrates before the service code runs, which means a seed called at startup always sees the current schema. The pattern below follows the approach in the test data docs, written here as a TypeScript service.

Application code passes through Encore and infrastructure guardrails to resources provisioned in your own AWS or GCP account.
Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

The migration creates both tables, with the unique keys the seed relies on:

-- billing/migrations/1_create_tables.up.sql CREATE TABLE customers ( id BIGSERIAL PRIMARY KEY, email TEXT NOT NULL UNIQUE, name TEXT NOT NULL, plan TEXT NOT NULL ); CREATE TABLE invoices ( id BIGSERIAL PRIMARY KEY, number TEXT NOT NULL UNIQUE, customer_id BIGINT NOT NULL REFERENCES customers (id), amount_cents BIGINT NOT NULL CHECK (amount_cents >= 0), status TEXT NOT NULL, due_date DATE NOT NULL );

The billing directory becomes a service through its encore.service.ts file:

// billing/encore.service.ts import { Service } from "encore.dev/service"; export default new Service("billing");

The database is declared in its own file so the seed and the endpoints can share it, using the SQL database API:

// billing/db.ts import { SQLDatabase } from "encore.dev/storage/sqldb"; // encore run starts Postgres locally and applies ./migrations before the service starts. export const db = new SQLDatabase("billing", { migrations: "./migrations", });

The seed checks the environment with the metadata API before it touches anything, inserts three named customers, and generates 500 invoices for pagination:

// billing/seed.ts import { appMeta } from "encore.dev"; import { db } from "./db"; // Runs only on a developer machine, never in tests or any deployed environment. export function shouldSeed(): boolean { const env = appMeta().environment; return env.cloud === "local" && env.type !== "test"; } // Fixed keys and ON CONFLICT DO NOTHING make every run after the first a no-op. export async function seed(): Promise<void> { await db.exec` INSERT INTO customers (email, name, plan) VALUES ('active@example.com', 'Active Customer', 'pro'), ('trial@example.com', 'Trial Customer', 'trial'), ('pastdue@example.com', 'Past Due Customer', 'pro') ON CONFLICT (email) DO NOTHING `; await db.exec` INSERT INTO invoices (number, customer_id, amount_cents, status, due_date) SELECT 'SEED-PASTDUE-1', c.id, 4900, 'overdue', CURRENT_DATE - 14 FROM customers c WHERE c.email = 'pastdue@example.com' ON CONFLICT (number) DO NOTHING `; // 500 invoices with a fixed mix of statuses, the same on every machine. await db.exec` INSERT INTO invoices (number, customer_id, amount_cents, status, due_date) SELECT 'SEED-' || g, c.id, 1000 + (g * 37) % 90000, CASE WHEN g % 10 = 0 THEN 'overdue' ELSE 'paid' END, CURRENT_DATE - g FROM generate_series(1, 500) AS g CROSS JOIN customers c WHERE c.email = 'active@example.com' ON CONFLICT (number) DO NOTHING `; }

The service file starts the seed when the module loads and logs a failure instead of crashing the app:

// billing/billing.ts import { api } from "encore.dev/api"; import log from "encore.dev/log"; import { db } from "./db"; import { seed, shouldSeed } from "./seed"; if (shouldSeed()) { seed().catch((err) => log.error(err, "seeding the billing database failed")); } interface Invoice { number: string; amountCents: number; status: string; } interface ListParams { status: string; } export const listInvoices = api( { expose: true, method: "GET", path: "/invoices/:status" }, async ({ status }: ListParams): Promise<{ invoices: Invoice[] }> => { const invoices: Invoice[] = []; const rows = db.query<{ number: string; amount_cents: number; status: string }>` SELECT number, amount_cents, status FROM invoices WHERE status = ${status} ORDER BY due_date DESC LIMIT 50 `; for await (const row of rows) { invoices.push({ number: row.number, amountCents: row.amount_cents, status: row.status }); } return { invoices }; }, );

encore test runs with the environment type test, so the seed stays out of the test databases and each test can set up exactly the rows it needs. When you want a clean slate, encore db reset billing resets that database (see the CLI reference), and the next encore run applies the migrations and seeds it again. For a look at the data, encore db shell billing opens a psql session with read-only permissions by default.

A coding agent working in this repo can add a column, change the seed in the same diff, and run the app to see the new data, since the database, its migrations and its seed all live in the code it is already editing.

Best fit: Teams that want every developer, and every agent session, to start from the same migrated and seeded database with one command.

Frequently asked questions

What is database seeding?

Database seeding is loading a known set of rows into a database after its schema has been created, so the app has users, orders or products to work with. In local development the seed gives every developer the same starting data, and in tests it gives each test a predictable state.

Should seed data live in migrations?

No. Migrations run in every environment, including production, so seed rows placed in a migration end up in production too. Keep reference data that production needs, such as a list of currencies, in migrations, and keep development data in a separate seed that only runs locally and in test or preview environments.

Should I seed my local database with production data?

No, not as a default. A production dump copies customer personal data onto every laptop that restores it. Use hand-written fixtures for the cases you test against, generated rows for volume, and a sanitized dump only when you need the shape of real data and have scrubbed it first.

How do I seed a local database with Encore?

Write an idempotent seed function that inserts fixed rows with ON CONFLICT DO NOTHING, and call it when the service starts only if appMeta().environment.cloud is local and the environment type is not test. encore run starts Postgres locally and applies the migrations, so the seed runs against the current schema, and encore db reset gives you a clean database to seed again.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders