# Production guide

Where to run a project in production: Cloudflare Workers with Neon in São Paulo by default, a Node server or Google Cloud when a project needs it, with costs, backups, a restore drill and monitoring.

This page is for the person who takes a project built on the template to production. [Deployment and rollback](/docs/deploy) explains the workflows that ship a Worker; this page explains where the pieces run, what they cost, how the data is backed up and how a server outside Cloudflare is watched.

<Callout title="Prices on this page">
Every price was read on **2026-11-27** from the page linked next to it, in US dollars unless marked €. Providers change prices: read the linked page again before you quote a figure to a client. The usage estimates are for an app with 6,000 to 10,000 active users a month.
</Callout>

## The default: Cloudflare Workers and Neon [#the-default-cloudflare-workers-and-neon]

Production runs as one Cloudflare Worker (web, API, cron) with a Neon Postgres database reached through Hyperdrive. Nothing else is needed to start.

### Neon in São Paulo [#neon-in-são-paulo]

For a Brazilian project, create the Neon project in **AWS São Paulo, `aws-sa-east-1`**. Neon lists it as a region and states that "You cannot change the region for an existing project" ([regions](https://neon.com/docs/introduction/regions)). Choosing another region later means a new project and a dump and restore, so decide before the first real user signs up.

| Neon plan                                       | Launch                    | Scale                          |
| ----------------------------------------------- | ------------------------- | ------------------------------ |
| Compute, per CU-hour                            | $0.106                    | $0.222                         |
| Storage, per GB-month                           | $0.35                     | $0.35                          |
| Restore window (history), default and maximum   | 1 day, up to 7 days       | 1 day, up to 30 days           |
| History (instant restore), per GB-month         | $0.20                     | $0.20                          |
| Scale to zero                                   | after 5 minutes, can be disabled | from 1 minute to always on |
| Monthly minimum                                 | none                      | none                           |

Sources, read 2026-11-27: [pricing](https://neon.com/pricing) (updated 2026-11-04), [plans](https://neon.com/docs/introduction/plans), [scale to zero](https://neon.com/docs/introduction/scale-to-zero).

Start on **Launch** and raise its restore window from the default 1 day to 7 days in the project settings. Move to **Scale** when the project holds health data in volume, signs an availability contract, or needs to go back more than 7 days.

### The cron keeps the database awake [#the-cron-keeps-the-database-awake]

The Worker's cron runs the job tick every minute (`"crons": ["* * * * *"]` in `apps/web/wrangler.jsonc`, [scheduled jobs](/docs/features/scheduled-jobs)), and every tick queries the database. Neon suspends a compute after 5 idle minutes, which never happens, so production pays for its smallest compute size all month: 730 hours × 0.25 CU × $0.106 = **$19.35**, or **$38.69** at 0.5 CU. Previews have no cron for this reason ([deploy](/docs/deploy#pull-request-previews)). Keep the tick: imports, webhooks, push, billing and cleanup depend on it. Set the autoscaling minimum to 0.25 CU and let Neon add compute at peaks.

### Hyperdrive [#hyperdrive]

On Workers Paid, Hyperdrive queries are unlimited and pooling has no extra charge ([Hyperdrive pricing](https://developers.cloudflare.com/hyperdrive/platform/pricing/), read 2026-11-27). Query caching stays off because of row-level security; [deploy](/docs/deploy#configuration-and-secrets) explains the check.

## Worker placement [#worker-placement]

A request runs several queries one after the other, so the Worker should run next to the database, not next to the visitor. Cloudflare's [placement](https://developers.cloudflare.com/workers/configuration/placement/) takes a cloud region hint and runs the Worker in the data center with the lowest latency to it. The options are mutually exclusive:

```jsonc
// apps/web/wrangler.jsonc
"placement": { "region": "aws:sa-east-1" } // Neon aws-sa-east-1 (São Paulo)
// or { "mode": "smart" }: Cloudflare chooses from the traffic it sees
```

Region hints use `aws:<region>`, `gcp:<region>` or `azure:<region>` (Cloudflare changelog, [22 January 2026](https://developers.cloudflare.com/changelog/2026-01-22-explicit-placement-hints/)). What the docs say about scope, read 2026-11-27:

- "Placement only affects the execution of fetch event handlers." Static assets are still served from the location nearest to the visitor.
- The page does not mention the `scheduled` handler, so do not count on the cron tick running near the database. A tick is a few queries a minute; it does not need to.
- PR previews copy `placement` from `apps/web/wrangler.jsonc` ([`preview-config.mjs`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/scripts/preview-config.mjs)), so they run next to the same database region.

The template ships `aws:us-east-2` (Ohio), the region of its own database. Every project sets its own with `pnpm setup`:

```sh
pnpm run setup --placement aws:sa-east-1   # Neon São Paulo
pnpm run setup --placement smart           # database location unknown
```

Setup writes `placement` into `apps/web/wrangler.jsonc` and keeps it in `.project-setup.json` for reruns. Without `--placement`, the interactive wizard asks; with `--create-hyperdrive --hyperdrive-db-url <Neon URL>` it takes the region from the Neon host (`ep-….sa-east-1.aws.neon.tech` → `aws:sa-east-1`). With `--yes` and no value it leaves the file unchanged and prints a warning. The local `DATABASE_URL` is never used for this, because it usually points at a development database somewhere else.

## Cost per month [#cost-per-month]

Estimates for 6,000 to 10,000 active users: 5 to 10 million requests a month, a database under 10 GB, and backups in R2.

| Item | Estimate | How | Source, read 2026-11-27 |
| --- | --- | --- | --- |
| Cloudflare Workers Paid | $5–15 | $5 minimum; 10 million requests and 30 million CPU ms included, then $0.30 per million requests and $0.02 per million CPU ms. At 15 ms of CPU per render, 10 million renders cost about $7 ([observability](/docs/architecture/observability#workers-logs-and-sampling)). | [Workers pricing](https://developers.cloudflare.com/workers/platform/pricing/) |
| Workers Logs | $0 | 20 million events a month included until 30 November 2026, then 50 GB of ingestion and 10 GB-month of storage included. | [Workers pricing](https://developers.cloudflare.com/workers/platform/pricing/), [Observability pricing](https://developers.cloudflare.com/observability/pricing/) |
| R2 (uploads and backups) | $0–1 | 10 GB-month, 1 million Class A and 10 million Class B operations free; then $0.015 per GB-month, $4.50 and $0.36 per million operations; no egress fee. | [R2 pricing](https://developers.cloudflare.com/r2/pricing/) |
| Neon Launch, São Paulo | $25–45 | 0.25–0.5 CU all month ($19.35–38.69), 10 GB storage ($3.50), a few GB of 7-day history ($0.20 per GB-month). | [Neon pricing](https://neon.com/pricing) |
| **Default total** | **$30–60** | | |
| VPS for tools (tracker, monitor, staging) | €0 on an existing server, €8.99 (Hetzner CX33, 8 GB) or €30.49–35.99 (CPX32, 8 GB) | Prices excluding VAT, EU locations. The cost-optimised and regular lines showed "currently unavailable" on 2026-11-27; Hetzner raised prices for new orders from 15 June 2026. | [Hetzner cost-optimised](https://www.hetzner.com/cloud/cost-optimized/), [regular](https://www.hetzner.com/cloud/regular-performance/), [price notice](https://www.hetzner.com/pressroom/standardization-and-price-adjustment-of-our-server-products/) |
| Node server in São Paulo (instead of Workers) | 30 a month | Vultr `vc2-2c-4gb` (2 vCPU, 4 GB) in `sao`; the API shows the São Paulo price without a currency (Vultr bills in US dollars). | [Vultr plans API](https://api.vultr.com/v2/plans?type=vc2) |
| Google Cloud (alternative) | about $135 + storage | Cloud Run, 1 vCPU and 512 MiB always on: 2,628,000 s × ($0.0000216 + 0.5 × $0.0000024) ≈ $60. Cloud SQL Enterprise, 1 vCPU and 3.75 GiB: 730 h × ($0.062 + 3.75 × $0.0105) ≈ $74. Storage, backups, network and Cloud Scheduler are not included. | [Cloud Run pricing](https://cloud.google.com/run/pricing) (Tier 2), [Cloud SQL pricing](https://cloud.google.com/sql/pricing), both for São Paulo (`southamerica-east1`) |

## Run on a Node server instead [#run-on-a-node-server-instead]

`DEPLOY_TARGET=node` builds the same app as a plain Node server with Nitro ([architecture](/docs/architecture)). Use it when a client cannot use Cloudflare or a VPS is already paid for. Put the server in the same region as the database: Hetzner has no location in South America ([locations](https://docs.hetzner.com/cloud/general/locations/)), so for Neon São Paulo pick a provider with a São Paulo region.

```sh
VITE_SITE_URL=https://app.example.com pnpm --filter web build:node
PORT=3000 node apps/web/.output/server/index.mjs   # reads NITRO_PORT or PORT
```

The server reads its configuration from the process environment, with the same names as `apps/web/.env` ([environments](/docs/development/environments)). Keep them in a file only the service user can read and load it with systemd's `EnvironmentFile=` or the container's env file. Put Cloudflare (a Tunnel, or a proxied DNS record) in front for TLS and the edge cache.

What exists only on Cloudflare, and what takes its place:

| On Cloudflare | On Node |
| --- | --- |
| Hyperdrive (`HYPERDRIVE`, `HYPERDRIVE_CACHED`) | `DATABASE_URL` directly; use Neon's pooled (`-pooler`) host. The `cloudflare:workers` shim leaves the bindings empty and `packages/db` falls back. |
| Cron Trigger | A system timer running `pnpm jobs:run --once --production` every minute ([below](#scheduled-jobs-on-node)). |
| Rate Limiting binding (`WEB_VITALS_RATE_LIMITER`) | None: without the binding, `POST /api/events/web-vitals` does not limit. Sign-in has its own limit in the database ([`rate-limit-storage.ts`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/packages/auth/src/rate-limit-storage.ts)). Any new public write endpoint needs a database limit before it ships on Node. |
| Email binding (`send_email`) | The Cloudflare Email REST API (`CLOUDFLARE_ACCOUNT_ID`, `CLOUDFLARE_EMAIL_API_TOKEN`) or `RESEND_API_KEY` ([`transports.ts`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/packages/email/src/transports.ts)). |
| R2 | Unchanged: storage speaks the S3 API with the `STORAGE_*` credentials ([`direct-s3.ts`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/packages/storage/src/direct-s3.ts)). |
| Workers Logs and traces (`workersTracer`) | Journal or container logs shipped to OpenObserve ([below](#monitoring-a-vps)); Effect spans are not exported; errors go to the self-hosted tracker. |
| Worker placement | The server's own location. |
| Version rollback (`wrangler rollback`) | Keep the previous build or image and switch back to it. A rollback still does not undo migrations. |

### Scheduled jobs on Node [#scheduled-jobs-on-node]

`pnpm jobs:run --once` refuses any database that is not local, so a workstation cannot tick production by accident ([`jobs-database.mjs`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/scripts/jobs-database.mjs)). On a Node server, `--production` is the scheduler:

- It reads only its own process environment. `apps/web/.env` is not loaded, so `DATABASE_URL` must come from the service's environment.
- It runs the Worker's scheduled tick: one `jobs.tick` line per run, one `jobs.step_failed` line per failed job ([scheduled jobs](/docs/features/scheduled-jobs)), exit code 1 when the tick fails.
- It runs from a checkout of the same commit as the web build, with dependencies installed (`pnpm install --frozen-lockfile`): `tsx` runs the TypeScript sources.

A systemd timer starts it every minute. The tick's 25-second deadline ends it well before the next start, and systemd does not start a `oneshot` service again while it is still running.

```ini
# /etc/systemd/system/app-jobs.service
[Unit]
Description=Scheduled jobs tick
After=network-online.target

[Service]
Type=oneshot
User=app
WorkingDirectory=/srv/app
EnvironmentFile=/etc/app/production.env
ExecStart=/usr/bin/pnpm jobs:run --once --production
# Heartbeat for the monitor; runs only when the tick succeeded.
ExecStartPost=/usr/bin/curl -fsS -m 10 https://status.example.com/api/push/<token>
TimeoutStartSec=55
```

```ini
# /etc/systemd/system/app-jobs.timer
[Unit]
Description=Scheduled jobs every minute

[Timer]
OnCalendar=*-*-* *:*:00
AccuracySec=1s

[Install]
WantedBy=timers.target
```

Enable it with `systemctl enable --now app-jobs.timer`. Run **one** scheduler per database: if a Worker for the same database still exists, remove its cron (`"triggers": { "crons": [] }`) before you enable the timer.

## Google Cloud as the alternative [#google-cloud-as-the-alternative]

Use Google Cloud only when a client requires it. The Node build runs in a container on **Cloud Run** with **Cloud SQL for PostgreSQL** 16 or newer, both in `southamerica-east1` (São Paulo, a Tier 2 region for Cloud Run, per [Cloud Run locations](https://docs.cloud.google.com/run/docs/locations)). Everything in the [Node table](#run-on-a-node-server-instead) applies. The cron becomes Cloud Scheduler starting a Cloud Run job that runs `pnpm jobs:run --once --production`. Cloud SQL connects with its own role, so run `db:apply-pending` there and follow [the restore runbook](/docs/development/runbooks#database-restored-or-moved-to-another-host) for `app_tenant`. The estimate is in the [cost table](#cost-per-month).

## Backups and restore [#backups-and-restore]

Three layers, each for a different failure.

1. **Neon history** brings the database back to a point in time inside the restore window (7 days on Launch, once raised). This is the first tool for a bad migration or a mistaken delete.
2. **A daily `pg_dump` to a separate R2 bucket** covers losing the Neon project or the account.
3. **A monthly restore drill** proves the dumps can be restored.

A Worker rollback does not reverse migrations or restore deleted rows ([deploy](/docs/deploy#migrations-and-rollback)).

### Daily dump to R2 [#daily-dump-to-r2]

Dump with a dedicated read-only role. `pg_dump` turns row security off and stops with an error on any table that row-level security would filter ([pg_dump](https://www.postgresql.org/docs/current/app-pgdump.html)), so the role needs `BYPASSRLS`. Only a superuser or a role with `BYPASSRLS` can give that attribute ([CREATE ROLE](https://www.postgresql.org/docs/current/sql-createrole.html)). Neon lists `BYPASSRLS` among the attributes of `neon_superuser` in projects created after 15 August 2023, and the project's owner role is a member of it ([Neon roles](https://neon.com/docs/manage/roles)). Create the role with SQL as the owner, not in the Neon Console: roles created there or through the API also get `neon_superuser` ([database access](https://neon.com/docs/manage/database-access)).

```sql
CREATE ROLE backup_reader LOGIN BYPASSRLS PASSWORD '<generated>';
GRANT CONNECT ON DATABASE neondb TO backup_reader;
GRANT USAGE ON SCHEMA public, app TO backup_reader;
GRANT SELECT ON ALL TABLES IN SCHEMA public, app TO backup_reader;
GRANT SELECT ON ALL SEQUENCES IN SCHEMA public, app TO backup_reader;
ALTER DEFAULT PRIVILEGES IN SCHEMA public, app GRANT SELECT ON TABLES TO backup_reader;
ALTER DEFAULT PRIVILEGES IN SCHEMA public, app GRANT SELECT ON SEQUENCES TO backup_reader;
```

Do not add `backup_reader` to `app.session_roles`: it never acts as a tenant. If Neon refuses `BYPASSRLS` for the new role, the fallback is to dump as the owner role, which owns the tables and is not filtered; the backup job then holds credentials that can write, so keep them in that job only.

Run the dump once a day from the VPS timer or a scheduled CI job. Use the direct host, not the pooled one, and a `pg_dump` with the same major version as the server ([Neon pg_dump guide](https://neon.com/docs/manage/backup-pg-dump)):

```sh
file="neon-$(date -u +%Y-%m-%dT%H%MZ).dump"
pg_dump -Fc --file "$file" "$BACKUP_DATABASE_URL"
aws s3 cp "$file" "s3://$BACKUP_BUCKET/$file" \
  --endpoint-url "https://$R2_ACCOUNT_ID.r2.cloudflarestorage.com"
rm "$file"
```

Keep the backups away from the app's own resources: a bucket of its own, an R2 API token that can write only to it, and credentials the Worker never sees. Set an [object lifecycle rule](https://developers.cloudflare.com/r2/buckets/object-lifecycles/) to delete dumps after the retention you promise (for example 35 days). A dump holds every user's personal data: keep it on encrypted storage and delete local copies after use. Send a heartbeat to the monitor after a successful upload, so a backup that stops running raises an alert.

### Restore drill [#restore-drill]

Once a month, restore the newest dump into a throwaway local PostgreSQL and check it:

```sh
aws s3 cp "s3://$BACKUP_BUCKET/<newest>.dump" ./backup.dump \
  --endpoint-url "https://$R2_ACCOUNT_ID.r2.cloudflarestorage.com"
node scripts/restore-drill.mjs ./backup.dump
rm ./backup.dump
```

[`restore-drill.mjs`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/scripts/restore-drill.mjs) starts a temporary cluster through `scripts/test-local-postgres.mjs` (it needs `initdb`, `pg_ctl`, `psql` and a `pg_restore` at least as new as the dump), restores the dump with `--no-owner --no-privileges`, runs `db:verify-rls`, counts the rows of every table and removes the cluster. The production roles do not exist locally, so `db:verify-rls` reports the missing tenant grants and `--repair` restores them from `rls-baseline.mjs`, the same step `db:apply-pending` runs after a real restore ([runbook](/docs/development/runbooks#database-restored-or-moved-to-another-host)). The drill only connects to the cluster it started.

```text
Restore drill: local-test.dump (custom, from PostgreSQL 17.10 (Homebrew))
  dump created         2026-11-27 12:49:37 CET
  newest row           2026-11-27T11:49:37Z (0.0 h ago)
  local cluster ready  2.4 s
  restore              0.1 s
  db:verify-rls        1.0 s  repaired
  row counts           0.1 s  45 tables, 266 rows
  total                3.9 s
  outcome              passed
```

That run restored a dump of a seeded local test database; the rows per table follow the summary. "dump created" is the dumping machine's clock as `pg_restore --list` prints it. The data's age comes from the newest `created_at` or `updated_at` of any table, read as UTC like the app writes it. The last line is one JSON record (`"event":"restore_drill"`, outcome, restore time, data age, tables, rows) to post in the alert channel. The exit code is 1 when the restore fails, row-level security cannot be verified or the dump has no table. Write down the restore time and the age of the newest row each month, and treat a failed drill as an incident ([runbooks](/docs/development/runbooks#after-an-incident)).

To recover for real, prefer a Neon branch from history. From a dump: create the database in the same region, `pg_restore --no-owner --no-privileges`, then `pnpm --filter @template-cloudflare/db db:apply-pending` against it.

## Monitoring a VPS [#monitoring-a-vps]

Cloudflare watches the Worker. A VPS (the error tracker, a monitor, a Node deployment) needs its own checks.

- **Uptime Kuma** in Docker (`louislam/uptime-kuma:2`; 2.5.12 was the latest stable release on 2026-11-27, [releases](https://github.com/louislam/uptime-kuma/releases)) checks production every minute: the home page, and `POST /api/rpc/healthCheck` with body `{"json":null}` expecting `OK`. Push monitors receive the heartbeats of the job timer and the daily backup. Expose its dashboard through a Cloudflare Tunnel behind Cloudflare Access.
- **An external check** watches the VPS itself, because a monitor cannot report its own outage. UptimeRobot's free plan has 50 monitors at a 5-minute interval and its terms allow commercial use ([pricing](https://uptimerobot.com/pricing/), [terms](https://uptimerobot.com/terms/)); Healthchecks.io's free plan watches 20 jobs ([pricing](https://healthchecks.io/pricing/)). Point it at Uptime Kuma's own status URL.
- **OpenObserve** receives the server's logs and metrics. The [OpenObserve Collector](https://openobserve.ai/docs/integration/system/linux/) installs an OpenTelemetry Collector service that sends journald, syslog and host metrics. OpenObserve documents no Docker log collection, so set Docker's `journald` log driver and the collector's journald input picks the containers up. Add an OpenObserve alert on disk usage: a full disk stops the tracker, the monitor and the backups at once.

## Error tracker [#error-tracker]

The self-hosted error tracker (Rustrak, with GlitchTip as the fallback) runs on the VPS with `docker compose`, from `deploy/error-tracker/compose.yml`, which comes with the error-reporting package. It is published through a Cloudflare Tunnel with no open port, its dashboard is behind Cloudflare Access, and its telemetry is off (`RUSTRAK_TELEMETRY=off`). Back up its database only if the error history matters to the project. Alerts come from the tracker's own rules. How the app reports errors is described in [observability](/docs/architecture/observability).

## Decisions per project [#decisions-per-project]

| Decision | Default |
| --- | --- |
| Database region | `aws-sa-east-1` for Brazilian projects, with `pnpm setup --placement aws:sa-east-1` |
| Neon plan | Launch with a 7-day restore window; Scale for health data in volume or an availability contract |
| Where it runs | Cloudflare Workers; Node or Google Cloud only when a client requires it |
| VPS monitoring | Uptime Kuma plus one free external check, logs and metrics to OpenObserve |

## Key files [#key-files]

- [`scripts/restore-drill.mjs`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/scripts/restore-drill.mjs)
- [`scripts/jobs-database.mjs`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/scripts/jobs-database.mjs)
- [`packages/api/scripts/jobs-run.mjs`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/packages/api/scripts/jobs-run.mjs)
- [`packages/project-setup-cli/src/placement.mjs`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/packages/project-setup-cli/src/placement.mjs)
- [`apps/web/wrangler.jsonc`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/apps/web/wrangler.jsonc)
- [`apps/web/vite.config.ts`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/apps/web/vite.config.ts)
