# Deploy on AWS (/docs/self-host/aws)



A production layout on managed AWS services. Nothing here is AWS-specific in the application; it
is the same images from [Deploy each app separately](/docs/self-host/individual-apps), wired to
managed backing services.

<Figure src="/diagrams/aws-deployment.svg" alt="Deployment diagram: ALB, ECS Fargate services, RDS and ElastiCache on AWS" />

| Piece         | AWS service                           | Notes                                                  |
| ------------- | ------------------------------------- | ------------------------------------------------------ |
| Database      | RDS for PostgreSQL 17 (Multi-AZ)      | Optional read replica via `DATABASE_READ_REPLICA_URL`. |
| Cache         | ElastiCache for Redis (or Valkey)     | Rate limits and caches. No persistence needed.         |
| API           | ECS Fargate service                   | Stateless; scale on CPU or request count.              |
| Worker        | ECS Fargate service, same image       | No load balancer. `bun src/worker.ts`.                 |
| Console       | ECS Fargate service                   | Static nginx. Or S3 + CloudFront, see below.           |
| Migrations    | One-off ECS task                      | `prisma migrate deploy`, run before each deploy.       |
| Images        | ECR                                   | One repository per image.                              |
| Secrets       | Secrets Manager / SSM Parameter Store | Injected into task definitions.                        |
| Execution log | S3 (optional)                         | `HTTP_LOG_S3_*` archives cold HTTP logs.               |

## 1. Network [#1-network]

* A VPC with public subnets for the ALB and **private subnets** for ECS, RDS and ElastiCache, in at
  least two AZs.
* Tasks in private subnets need egress for webhooks, connectors, email and AI providers: a NAT
  gateway, plus VPC endpoints for ECR, S3, CloudWatch Logs and Secrets Manager to cut NAT traffic.
* Security groups, each allowing only the one before it:
  `alb` → `api`/`web` (3000 / 80), `api`/`worker` → `rds` (5432), `api`/`worker` → `redis` (6379).

## 2. Data stores [#2-data-stores]

**RDS.** PostgreSQL 17, Multi-AZ, encrypted, automated backups on. Create the `decision_control`
database and a dedicated user, and build the URL:

```text
postgresql://decision:<password>@<rds-endpoint>:5432/decision_control?schema=public
```

Executions are the audit trail, so size storage for them and keep `EXECUTION_RETENTION_DAYS=0`
unless you have a retention policy.

**ElastiCache.** A small Redis replication group is enough. Use
`redis://<primary-endpoint>:6379` (or `rediss://` with in-transit encryption) as `REDIS_URL`.

## 3. Images [#3-images]

Build from the repository root and push to ECR:

```bash
AWS_ACCOUNT=123456789012; REGION=us-east-1
REGISTRY=$AWS_ACCOUNT.dkr.ecr.$REGION.amazonaws.com

aws ecr get-login-password --region $REGION \
  | docker login --username AWS --password-stdin $REGISTRY

docker build -f apps/api/Dockerfile -t $REGISTRY/decision-control-api:$TAG .
docker build -f apps/web/Dockerfile -t $REGISTRY/decision-control-web:$TAG \
  --build-arg VITE_DOCS_URL=https://docs.example.com .

docker push $REGISTRY/decision-control-api:$TAG
docker push $REGISTRY/decision-control-web:$TAG
```

Build for the architecture you run on: add `--platform linux/arm64` for Graviton (cheaper) or
`linux/amd64` otherwise, and set `runtimePlatform` in the task definition to match.

## 4. Secrets and configuration [#4-secrets-and-configuration]

Store the secrets in Secrets Manager and reference them from the task definition (`secrets`), not
as plain `environment` entries:

```bash
aws secretsmanager create-secret --name decision-control/prod --secret-string "$(jq -n \
  --arg pw "$(openssl rand -hex 24)" \
  --arg pepper "$(openssl rand -hex 32)" \
  --arg enc "$(openssl rand -base64 32)" \
  --arg wh "$(openssl rand -hex 32)" \
  '{POSTGRES_PASSWORD:$pw, API_KEY_PEPPER:$pepper, CREDENTIALS_ENCRYPTION_KEY:$enc, WEBHOOK_SIGNING_SECRET:$wh}')"
```

Back up `CREDENTIALS_ENCRYPTION_KEY` and `API_KEY_PEPPER` separately: losing them makes stored
credentials and API keys unrecoverable. Environment shared by the API, worker and migration task:

| Variable                                                                 | Value                                                                           |
| ------------------------------------------------------------------------ | ------------------------------------------------------------------------------- |
| `NODE_ENV`                                                               | `production`                                                                    |
| `DATABASE_URL`                                                           | The RDS URL above (from Secrets Manager).                                       |
| `REDIS_URL`, `RATE_LIMIT_STORE`                                          | ElastiCache URL, `redis`.                                                       |
| `WEB_ORIGIN`                                                             | `https://decisions.example.com` — the public URL of the ALB.                    |
| `API_KEY_PEPPER`, `CREDENTIALS_ENCRYPTION_KEY`, `WEBHOOK_SIGNING_SECRET` | From Secrets Manager.                                                           |
| `TRUST_PROXY`, `TRUST_PROXY_HOPS`                                        | `true`, `1` — the ALB is the only proxy in front of the API (API service only). |
| `WORKER_ENABLED`                                                         | `false` on the API service, since the worker runs separately.                   |
| `SHUTDOWN_DRAIN_MS`                                                      | `5000`                                                                          |

The rest is in [Configuration](/docs/self-host/configuration).

## 5. Route `/api` at the load balancer [#5-route-api-at-the-load-balancer]

The console's nginx proxies `/api` by resolving `API_UPSTREAM` through Docker's DNS
(`127.0.0.11`), which does not exist on Fargate. Do not use that proxy on AWS: let the ALB split
traffic on the same hostname, which keeps the browser on one origin (first-party cookie, no CORS).

1. Create an HTTPS listener (443) with an ACM certificate; redirect 80 → 443.
2. Target group `api`: type **IP**, protocol HTTP, port `3000`, health check `GET /readyz`.
3. Target group `web`: type **IP**, HTTP, port `80`, health check `GET /nginx-health`.
4. Listener rules: path `/api/*` and `/healthz` → `api`; default → `web`.
5. Set the target groups' deregistration delay to \~30 s, so in-flight requests drain.
6. Point `decisions.example.com` at the ALB with a Route 53 alias record.

Set the ALB idle timeout above your slowest execution if you run long `ai` or `api-call` nodes
(the default 60 s matches the console's own proxy timeout).

## 6. ECS task definitions [#6-ecs-task-definitions]

One cluster, three services plus a one-off task, all from the same two images.

| Task      | Image | Command                            | CPU / memory       | Count                | Load balancer      |
| --------- | ----- | ---------------------------------- | ------------------ | -------------------- | ------------------ |
| `api`     | api   | image default (`bun src/index.ts`) | 0.5 vCPU / 1 GB+   | 2+                   | target group `api` |
| `worker`  | api   | `bun src/worker.ts`                | 0.5 vCPU / 1 GB    | 1+                   | none               |
| `web`     | web   | image default                      | 0.25 vCPU / 0.5 GB | 2+                   | target group `web` |
| `migrate` | api   | `bunx --bun prisma migrate deploy` | 0.5 vCPU / 1 GB    | run once per release | none               |

Details that matter:

* `stopTimeout: 40` on `api` and `worker`, matching the 40 s drain in the compose file.
* `worker`: disable the container health check; it serves no HTTP. Add `METRICS_PORT=9464` only if
  you scrape it.
* `api`: the health check is the one baked into the image (`/healthz`); the ALB uses `/readyz`.
* Send logs to CloudWatch (`awslogs` driver). The application logs JSON to stdout.
* The execution role needs `secretsmanager:GetSecretValue` for the secret and ECR pull rights; the
  task role needs `s3:PutObject` / `GetObject` on the bucket only if you set `HTTP_LOG_S3_BUCKET`
  (leave the access keys empty and the SDK uses the task role).
* Console tasks need no `API_UPSTREAM`, because the ALB sends `/api` straight to the API.

## 7. Deploy and release [#7-deploy-and-release]

```bash
# Run migrations to completion first.
TASK=$(aws ecs run-task --cluster dc --launch-type FARGATE --task-definition decision-control-migrate \
  --network-configuration "awsvpcConfiguration={subnets=[subnet-a,subnet-b],securityGroups=[sg-api],assignPublicIp=DISABLED}" \
  --query 'tasks[0].taskArn' --output text)
aws ecs wait tasks-stopped --cluster dc --tasks $TASK
aws ecs describe-tasks --cluster dc --tasks $TASK \
  --query 'tasks[0].containers[0].exitCode'   # must be 0

# Then roll the services.
for s in api worker web; do aws ecs update-service --cluster dc --service $s --force-new-deployment; done
```

Use the ECS rolling-update deployment with minimum healthy 100% and maximum 200%, so new tasks pass
`/readyz` before old ones drain. Migrations are written to be applied before the new code starts;
keep them backward compatible with the previous release for the overlap. Better: wire this into
your pipeline (CodePipeline, GitHub Actions) so the migration task is a gate before the service
update.

Then open `https://decisions.example.com` and create the first account — see
[Docker](/docs/self-host/docker#first-account). Consider
[`REGISTRATION_MODE`](/docs/self-host/configuration) before you expose the URL.

## 8. Docs and landing [#8-docs-and-landing]

Both are static, so they do not need ECS:

* **S3 + CloudFront.** Build the app (`bun run --filter @decision-control/docs build`, output in
  `apps/docs/.output/public`; landing in `apps/landing/dist`), `aws s3 sync` it to a private
  bucket, and serve it through CloudFront with Origin Access Control. For docs, map unknown paths
  to `/_shell.html` with a 200 response (custom error response) so client-side routes work; for
  the console, map them to `/index.html`.
* **Or** run the `docs` / `landing` images as small Fargate services behind the same ALB, with
  host-based rules (`docs.example.com`, `example.com`).

The console can be served from S3 + CloudFront the same way, if you front both `/api/*` (to the
ALB) and the static origin from a single CloudFront distribution, which keeps one origin.

## Operations [#operations]

* **Monitoring.** The API exposes `/metrics` (protect with `METRICS_TOKEN`). Scrape it with
  Amazon Managed Prometheus or the CloudWatch agent, and alert on the rules in `monitoring/`.
  See [Observability](/docs/operate/observability).
* **Scaling.** Target-tracking on API CPU; the worker scales by adding tasks, since outbox rows are
  claimed with `FOR UPDATE SKIP LOCKED`.
* **Backups.** RDS automated backups and snapshots cover everything stateful; Redis holds only
  caches. Test a restore.
* **Key rotation.** See [Secrets](/docs/self-host/docker#secrets); run `bun run credentials:rotate`
  as a one-off ECS task using the api image.
* **Security.** Keep ECS, RDS and ElastiCache private, restrict the ALB with AWS WAF, and read
  [Secure deployment](/docs/operate/secure-deployment).
