---
title: 'Building a software factory on Neon'
description: 'We use software factories every day on our team now. Here''s how to set up yours'
excerpt: >-
  A software factory is an agent pipeline that takes requests from Slack,
  GitHub issues or alerts through fixed stages (plan, build, verify, ship) and
  turns each one into a PR that an engineer reviews and merges...
date: '2026-12-02T09:00:00'
category: product
categories:
  - product
authors:
  - russ-dias
cover:
  image: https://cdn.neonapi.io/public/images/pages/blog/building-a-software-factory-on-neon/cover.jpg
  alt: Our software factory runs on Neon
isFeatured: false
seo:
  title: 'Building a software factory on Neon - Neon'
  description: 'We use software factories every day on our team now. Here''s how to set up yours'
  keywords: []
  noindex: false
  ogTitle: 'Building a software factory on Neon - Neon'
  ogDescription: 'We use software factories every day on our team now. Here''s how to set up yours'
  image: null
---

<video autoPlay muted loop playsInline width="708" height="398" aria-label="A software factory turns Slack requests into pull requests that engineers review and approve">
<source src="https://cdn.neonapi.io/public/images/pages/blog/building-a-software-factory-on-neon/software-factory.webm" type="video/webm" />
<source src="https://cdn.neonapi.io/public/images/pages/blog/building-a-software-factory-on-neon/software-factory.mp4" type="video/mp4" />
</video>

A software factory is an agent pipeline that takes requests from Slack, GitHub issues or alerts through fixed stages (plan, build, verify, ship) and turns each one into a PR that an engineer reviews and merges. We run several at Neon, for our docs, our CLI, SDKs and MCP server, and UI changes. Each one keeps its state in Postgres and gives every request its own branch of the production database.

Here's what the workflow looks like on a regular day:

1. A teammate asks for a change in a Slack thread
2. An agent reads the code and posts a plan back in the thread, where anyone can adjust it or stop it
3. Another agent builds the change, opens a PR, and gets CI green
4. An engineer reviews and merges

## TL;DR: how the software factory uses Neon

- **Two Neon projects:**
  - Orchestrator state: the orchestrator's own Postgres database, with one row per request in `work_items` and every decision in an append-only `events` table. You can [branch](https://neon.com/docs/introduction/branching) this project to test a new version of the orchestrator against past requests.
  - Your app: production lives here, set as a [protected branch](https://neon.com/docs/guides/protected-branches). Only the deploy pipeline can write to it.
- **A branch per request:** when a plan is approved, the orchestrator creates a [branch](https://neon.com/docs/introduction/branching) of production for that request. It's a copy-on-write clone with real data, ready in seconds, with its own password. The build agent gets only that branch's connection string.
- **Expiration:** every request's branch [expires](https://neon.com/docs/guides/branch-expiration) after 7 days unless it's extended, so abandoned work cleans itself up.
- **Scale to zero:** a branch waiting on review [uses no compute](https://neon.com/docs/introduction/scale-to-zero).
- **Checkpoints:** before a risky step (migration, backfill, retry), the orchestrator records the time. If the step fails, it [restores the branch](https://neon.com/docs/postgres/backup-restore/branch-restore) to that moment. The failed state is kept on a side branch so you can inspect it.
- **Review:** the PR preview runs on the request's branch, and the orchestrator posts a [schema diff](https://neon.com/docs/guides/schema-diff) between production and the branch next to the code diff.
- **Read-only agents:** planning agents connect through the [Neon MCP Server](https://neon.com/docs/ai/neon-mcp-server) in read-only mode, with a limited Postgres role.
- **Snapshots:** just before a migration runs on production, the orchestrator takes a [snapshot](https://neon.com/docs/ai/ai-database-versioning) of production as a last-resort rollback point.
- **Cleanup:** when a request closes, the orchestrator deletes its branch and any side branches.
- **AI Gateway:** each request's agents call models through [Neon AI Gateway](https://neon.com/docs/ai-gateway/overview), using a credential tied to the request's branch. The [consumption API](https://neon.com/docs/guides/consumption-metrics) then shows token usage per request.
- **Neon API:** the orchestrator makes all these calls (create, restore, diff, delete) through the [Neon API](https://neon.com/docs/reference/api).

## What is a software factory?

We call this pipeline a software factory because it works like a production line:

- Requests go in one end and PRs come out the other
- Every request goes through the same steps in the same order, and several are on the line at once
- No single agent carries a request from start to finish
- Each stage has its own job, and the request moves on when that job is done

![The software factory floor: requests from Slack threads, GitHub issues and alerts move through six stages: intake, plan, build, verify, ship and measure](https://cdn.neonapi.io/public/images/pages/blog/building-a-software-factory-on-neon/software-factory-stages.png)

Every request goes through the same six stages:

- Intake. A request arrives from Slack, an issue, or an alert, and is accepted, declined, or sent back with a question.
- Plan. An agent posts a plan in the thread.
- Build. An agent writes the code, migration and tests, and opens a PR.
- Verify. CI runs, a second agent critiques the PR, and an engineer reviews it.
- Ship. The PR merges and deploys.
- Measure. Someone checks the change worked, and the request closes.

People stay in charge at two points, the plan and the review, and they answer in the thread where the request started. Approving moves the request on, anyone can stop it, and any other reply sends it back to build with the new instructions.

## How a software factory is built

Our factory has four parts:

1. **Requests** come in via Slack threads, GitHub issues, and alerts. Approvals come back in the same thread
2. **The orchestrator**: this is plain code that runs on a schedule, picks up the next request, decides what happens to it, and starts an agent (more about it down below). It keeps its own state (every request and every decision) in Postgres, in a [Neon project](https://neon.com/docs/manage/projects) of its own
3. **The agents:** each one runs in a sandbox and works on one request. Its model calls go through [Neon AI Gateway](https://neon.com/docs/ai-gateway/overview), so we can see what each request cost
4. **The app's database**: a second Neon project holds production. Every request gets its own branch, a copy of production that agents can change freely. Only our deploy pipeline can touch production itself

![How our software factory is built: the orchestrator picks up requests, starts an agent per request and keeps state in one Neon project, while each request gets its own branch of production in the app's Neon project](https://cdn.neonapi.io/public/images/pages/blog/building-a-software-factory-on-neon/software-factory-architecture.png)

### The orchestrator code runs the factory, agents do the work

Agents are good at doing the work inside a stage, but not so good at keeping track of the whole process, so we keep that (and a few hard rules) in plain code outside the agents.

This is the orchestrator. It runs on a schedule, checks where each request is, decides the next step, and starts an agent to do it. The rules it enforces:

- Limits: it caps how many requests run at once, how many times a stage can be retried, and how much each request can spend. A prompt that says "don't spend too much" isn't a limit.
- A kill switch: anyone can pull it, and the orchestrator checks it before every PR comment, deploy, or message.
- A decision log: every decision is recorded along with what it was based on, so you can trace a strange one instead of digging through chat logs.
- Expirations: database copies, snapshots, and credentials all expire. If something gets left behind, the expiration cleans it up.

The orchestrator can be a small loop or a workflow framework. A hand-written loop is a `tick()` function on a schedule. Each tick takes a Postgres advisory lock so ticks take turns, claims one request (if fewer than the cap are running), logs the decision, and starts an agent session. If you'd rather use a framework, [Mastra](https://mastra.ai/docs/workflows/suspend-and-resume) workflows can suspend until someone approves, and `@mastra/pg` keeps their state in Postgres. [Inngest](https://neon.com/guides/durable-workflow-on-neon-functions) has durable steps that can wait for an approval too. Either way, code decides the next step, not a model.

Everything the orchestrator does in Neon (creating branches, restoring checkpoints, diffing schemas, cleaning up) goes through the [Neon API](https://neon.com/docs/reference/api). Branch creates and restores finish asynchronously, so the orchestrator polls the branch or retries the first connection before an agent connects. The prompt at the end of this post has your coding agent write a starter version, for example with the [Neon serverless driver](https://neon.com/docs/serverless/serverless-driver).

### The database is actually the hard part

For the factory to work, each stage needs something from its environment:

- "Build" needs a place where an agent can change things without touching production or getting in the way of the other requests in progress
- "Verify" needs a way to show the reviewer exactly what changed.
- "Retries" need a way to undo a failed step and try again from a clean state.
- "Abandoned requests" need their leftovers cleaned up, even when nobody remembers to do it.

For code, git already covers all four. Each request gets its own git branch, the PR shows the diff, a bad commit gets reverted, and stale branches get deleted. That's why agents can open PRs safely today.

Most requests also touch data. Take the "show the last-active date on the projects page" example from above:

- The build agent has to add a column and backfill it
- It has to test the page against real projects, not an empty table
- The reviewer has to click through a preview that has data in it

The software factory needs data that works like code: a copy per request, a diff, an undo, and cleanup. [Neon branches](https://neon.com/docs/introduction/branching) give you all four, plus scale to zero, so a request waiting on review costs nothing. The TL;DR at the top lists each feature, and the next section shows where each one comes in.

## A detailed view: how a request moves through Neon

![The life of one request's branch: create branch, connect, checkpoint, restore on failure, schema diff, snapshot production and delete](https://cdn.neonapi.io/public/images/pages/blog/building-a-software-factory-on-neon/request-branch-lifecycle.png)

### A request comes in: a row in Postgres

The first thing the orchestrator does with a new request is write it down. It has to know where every request is and why, even after a crash or a redeploy, and an agent's context window can't hold that. So each request is a row in a `work_items` table in the orchestrator's own Postgres database, and every decision about it is a row in `events`:

```
create table work_items (
  id            text primary key,
  request       text not null,
  stage         text not null default 'intake',  -- intake, plan, build, verify, ship, measure, done, stopped
  branch_id     text,                            -- the request's branch in your app's project
  checkpoint_at timestamptz,                     -- the last point it's safe to roll back to
  attempts      int not null default 0,          -- attempts at the current stage
  waiting_on    text,                            -- set while a person needs to act (plan_approval, review), null otherwise
  claimed_until timestamptz,
  created_at    timestamptz not null default now(),
  updated_at    timestamptz not null default now()
);

create table events (                            -- append-only: every decision, with its inputs
  id        bigserial primary key,
  work_item text not null references work_items(id),
  kind      text not null,                       -- request_received, pr_opened, shipped, ...
  body      jsonb not null default '{}',
  at        timestamptz not null default now()
);
```

Several workers can share the queue if each one claims a request in a single statement. `for update skip locked` stops two workers from taking the same request, and the lease in `claimed_until` frees a request whose worker died:

```
update work_items
set claimed_until = now() + interval '30 minutes', attempts = attempts + 1, updated_at = now()
where id = (
  select id from work_items
  where stage not in ('done', 'stopped')
    and waiting_on is null
    and attempts < 3
    and (claimed_until is null or claimed_until < now())
  order by updated_at
  for update skip locked
  limit 1
)
returning *;
```

When a step succeeds, the request moves to its next stage and `attempts` resets to 0. A request that runs out of attempts, or that someone stops, moves to `stopped` for a person to look at. When the orchestrator posts a plan or opens a PR, it sets `waiting_on` and releases the claim, and the reply in the thread clears it. A request waiting on a person isn't claimed again, so it doesn't use up its attempts. The orchestrator renews `claimed_until` during long sessions, and its Postgres role can insert into `events` but not update or delete it.

Because this state is in Neon, you can branch the factory itself: run a new version of the orchestrator against a branch with last week's requests, and compare its decisions with the ones in `events`.

### Build starts: a branch of production

Once someone approves the plan, the orchestrator creates a [branch](https://neon.com/docs/introduction/branching) of the app's database for the request, so the build agent has real data to work against. Two settings make this safe:

- Protect production: make it a [protected branch](https://neon.com/docs/guides/protected-branches), which needs a paid plan. Branches of a protected branch get their own Postgres passwords. Otherwise a request's branch has a connection string that works on production too, and protecting production later doesn't change passwords on existing branches.
- Expire every request's branch: give each one an [expiration](https://neon.com/docs/guides/branch-expiration), so abandoned work disappears even if cleanup never runs.

Each command below also needs `--project-id` with your app's project ID, left out to keep them short. `--no-secrets` keeps the connection string out of the output:

```
# On macOS, use: date -u -v+7d +%Y-%m-%dT%H:%M:%SZ
neon branches create \
  --name work/req-42 \
  --parent production \
  --no-secrets \
  --expires-at "$(date -u -d '+7 days' +%Y-%m-%dT%H:%M:%SZ)"
```

Store the branch ID on the request's row. Get the connection string with `neon connection-string work/req-42` and pass it to the agent's sandbox as an environment variable, so it never appears in a prompt. Extend long-running requests with `neon branches set-expiration`.

### Before risky steps: a checkpoint

During build, the agent may run a migration, a backfill, or a retry. Before each one, the orchestrator saves the time as `checkpoint_at`. If the step goes wrong, it [restores the branch](https://neon.com/docs/postgres/backup-restore/branch-restore) to that moment instead of asking the agent to clean up after itself. The checkpoint has to fall inside your project's history window, which is 1 day by default on paid plans. Pass the time in RFC 3339 format, like `2026-11-24T14:05:00Z`:

```
neon branches restore work/req-42 "^self@$CHECKPOINT_AT" \
  --preserve-under-name req-42-before-restore
```

`--preserve-under-name` keeps the failed state on a side branch, which you can inspect with `neon branches add-compute req-42-before-restore`. The side branch becomes the request branch's parent, so it can't expire: when the request closes, delete the request's branch, then the side branch. To start the build over, restore from production with `neon branches restore work/req-42 production`. Don't reset from the parent after a restore, because the parent is now the side branch.

### Review: a preview and a schema diff

When the PR is open, the request waits for a person. Reviews are where a factory stalls, so each PR comes with two things that make it quick to read:

- A preview on real data: the PR's preview deployment points at the request's branch, so the reviewer clicks through the change on real data. Keep previews behind your team's login.
- A schema diff: if the PR carries a migration, the orchestrator posts the [schema diff](https://neon.com/docs/guides/schema-diff) between production and the request's branch next to the code diff:

```
neon branches schema-diff production work/req-42 --database neondb --no-color
```

While it waits, the request's compute [scales to zero](https://neon.com/docs/introduction/scale-to-zero), so a queue of waiting requests doesn't mean a fleet of running databases.

Agents never write to production. Planning agents read it through the [Neon MCP Server](https://neon.com/docs/ai/neon-mcp-server) in read-only mode, scoped to the app's project, as a Postgres role that can read only what the plan needs:

```
https://mcp.neon.tech/mcp?readonly=true&projectId=<app-project-id>&roleName=planner
```

Create that role with SQL and grant it only the tables it needs. Roles created in the Console or API can read all data, so pinning one of those doesn't limit anything. Build agents get their own request's branch. Only the deploy pipeline can write to production.

### Ship: a snapshot, then cleanup

Once the PR is approved, shipping is the normal deploy. Just before a migration runs on production, the orchestrator takes a [snapshot](https://neon.com/docs/ai/ai-database-versioning) so a bad migration has a known-good point to return to:

```
neon snapshots create --branch production --name before-req-42 \
  --expires-at "$(date -u -d '+14 days' +%Y-%m-%dT%H:%M:%SZ)"
```

Restoring a snapshot discards every later write, so it's the last resort behind a forward fix. Once the change is live, the orchestrator deletes the request's branch and its side branches, and revokes the request's AI Gateway credential.

### Afterward: measuring the factory

By the time a request closes, the `events` table holds its whole history: when it arrived, when the PR opened, when it shipped. Across all requests, that tells you how long work takes and where it gets stuck. Start with the time from request to PR:

```
-- Median hours from request to first PR, for requests in the last 7 days.
with firsts as (
  select work_item,
         min(at) filter (where kind = 'request_received') as requested_at,
         min(at) filter (where kind = 'pr_opened') as pr_at
  from events
  group by work_item
)
select percentile_cont(0.5) within group (
         order by extract(epoch from pr_at - requested_at) / 3600
       ) as median_hours_to_pr
from firsts
where pr_at is not null
  and requested_at > now() - interval '7 days';
```

The same table gives the share of requests that ship, how often a person stepped in, and how many agent sessions failed. The last two show where to spend your time next.

For model usage per request, route its agents through [Neon AI Gateway](https://neon.com/docs/ai-gateway/overview). A gateway credential issued on the request's branch works only on that branch, so the [consumption API](https://neon.com/docs/guides/consumption-metrics) reports each request's model tokens separately. Create the credential through the API with an `expires_at` that matches the request's branch. AI Gateway needs prepaid credits and a project in one of its [supported regions](https://neon.com/docs/ai-gateway/overview).

## Build your own software factory

You don't need all of this on day one. Start with three pieces:

- A `work_items` table
- A branch with an expiration for every request
- A preview on the request's branch for every review

Then add checkpoints, schema diffs, snapshots and measurement as the queue grows.

To have your coding agent build it, first install the Neon skills:

```
neon skills -s neon -s neon-postgres
```

Then paste this prompt:

```
Set up the skeleton of a software factory (an agent pipeline that turns requests into PRs) in this repo, using Neon.
Docs: https://neon.com/docs/guides/branch-expiration.md
Restore: https://neon.com/docs/postgres/backup-restore/branch-restore.md
Schema diff: https://neon.com/docs/guides/schema-diff.md

1. Orchestrator database. Create a Neon project for the orchestrator, separate from the app.
   Add a migration with two tables: work_items (id, request, stage, branch_id, checkpoint_at,
   attempts, waiting_on, claimed_until, created_at, updated_at) and an append-only events table
   (work_item, kind, body jsonb, at). Stages: intake, plan, build, verify, ship, measure, done, stopped.
2. Orchestrator. Write a tick() function that takes a Postgres advisory lock (so ticks take
   turns and the caps hold) and, in the same transaction, claims one work item with
   UPDATE ... WHERE id = (SELECT ... FOR UPDATE SKIP LOCKED LIMIT 1) RETURNING *, enforces
   configurable caps in code (active items, attempts per stage), records every decision in
   events with its inputs, and calls a stub startAgentSession(item, step). Each claim counts an
   attempt, and items that run out of attempts move to stopped. Skip items with waiting_on set.
   Set it when posting a plan or opening a PR, and clear it when a person replies.
3. Neon helpers, using the Neon API with NEON_API_KEY and NEON_PROJECT_ID from the environment:
   createWorkBranch (a branch named work/<requestId> with a read_write compute and expires_at
   7 days out), restoreToCheckpoint (restore the branch to its own history with
   preserve_under_name set), schemaDiff (call compare_schema against production and return the diff), and
   closeWorkItem (delete the work branch, then the side branches its restores left behind).
4. Never print connection strings or tokens, and never put them in prompts or logs. Pass them
   to sandboxes as environment variables only. A sandbox gets its work branch's connection
   string and nothing else; the Neon API key stays in the orchestrator.
5. Add a README section that describes the stages and the caps.

Don't touch the production branch, and stop if it isn't a protected branch. Ask me for the
app's project ID and its production branch name before you create anything.
```
