Repository navigation
Description
Part of #384. Implements the production half of spec §18. Written, not applied: #416 deploys it.
Decision: AWS CDK
On 2026-10-04 we compared CDK with Alchemy v2 by building this stack in Alchemy and running it live, then destroying it (findings). Alchemy fit the shape and was fast. But it reproduced failure modes a two-person team should not own at launch: concurrent deploys corrupting state, orphans after an interrupted create, invisible attribute drift, and silently dropped resources. Those are filed upstream as alchemy-run/alchemy#1965–#1969. With CDK, CloudFormation holds the state, refuses overlapping updates, carries on if the CLI dies and rolls back a failed update. Moving to Alchemy later is #518.
What to build
Three PRs, in order. Each is one concern.
1. Server: refuse unsafe production config, add a deep health check
- Refuse bad configuration at startup.
- Every
NODE_ENV=productionhost refuses to start without the Neon Object Storage settings. Today a missingPATCHY_S3_BUCKETfalls back to the container's disk (apps/server/src/Server.ts:86), and those files are lost on the next deploy. - Every production host refuses a non-HTTPS
PATCHY_PUBLIC_BASE_URL. - When
PATCHY_ENVIRONMENT=production, refuse Clerkpk_test_/sk_test_keys (packages/auth/src/Session.ts:69). Staging and the tier 2 spike keep their dev or fake keys.
- Every
- Deep health check. A route outside
/api(for example/healthz/deep) that queries the platform database and returns the runningPATCHY_DEPLOYMENT_REVISION. The uptime check uses it, so anyone can see which build is live without AWS access./healthzstays shallow for the load balancer and ECS, so a database blip doesn't make ECS replace every host. Today/healthzalways answers ok (packages/serving/src/Pages.ts:282).
2. The CDK app, apps/infra
Two stacks per environment. The environment name is a parameter, so a staging stack later is one command.
Base stack:
- the ECR repository: immutable tags, with a lifecycle policy that keeps enough images to roll back;
- the GitHub OIDC provider, plus a deploy role trusted only for this repo's
productionenvironment. The provider is one per AWS account: declare it here and nowhere else; - the AWS Budgets forecast alert at $300/month, emailing Allison and Srikar.
It is separate from the app stack because the image has to be in ECR before the host service can start.
App stack:
- Network.
- Two public subnets hold the ALB and the hosts (public IPs, no NAT gateway).
- The private subnet(s) for exec tasks have
ecr.api,ecr.dkrandlogsinterface endpoints and an S3 gateway endpoint, and no Secrets Manager endpoint. - The endpoint security group admits HTTPS from the hosts as well as from exec tasks. Private DNS on an interface endpoint applies to the whole VPC, so once it propagates the hosts reach ECR and CloudWatch Logs through the endpoints too. This failed a live rollout in the prototype: new host tasks could not create their log streams.
InterfaceVpcEndpoint's default (open: true, the VPC range) covers it; if the rules are tightened, keep the host rule.
- Load balancer.
- HTTPS on 443 with the existing certificate passed in as a parameter (ARN in the comment below), and 80 redirecting to 443.
- HTTP/2 on, idle timeout 3,600 s.
- The target group uses application-cookie stickiness on
patchy_stream_affinity(in CDKstickinessCookieNameonly takes effect withstickinessCookieDuration), a 90 s deregistration delay, and a/healthzhealth check.
- Host service.
- Two tasks at 0.5 vCPU / 2 GB, rolling update at 100 % minimum / 200 % maximum.
- Deployment circuit breaker with
rollback: true. CDK's default is no rollback. - Container user 1000,
stopTimeout120, ports 8080 and 8789, and secrets injected from one host JSON secret by key. - The host task role carries the fleet policy in
docs/OPERATIONS.md: ECS actions scoped to this cluster and the exec task-definition family, tag on create, andiam:PassRolefor the exec execution role only.
- Exec task definition, no service.
- The fleet controller launches every exec task.
- 0.5 vCPU / 2 GB, user 0, the spike's capability drops, port 8788.
- No task role. CDK's
FargateTaskDefinitionalways creates one, so useCfnTaskDefinitionor removeTaskRoleArnwith an override. - Its own execution role, with ECR pull and logs only.
- Security groups: ALB, host,
exec-bootstrap,exec-sealedand endpoints, with the rules indocs/OPERATIONS.mdplus the endpoint rule above. - Secrets.
- One host JSON secret declared without values: Clerk keys, the Neon URLs, the
PATCHY_S3_*settings, the credential keyring and the PostHog key. A person fills it in during chore(infra): the first deploy of Patchy to AWS #416, and deploys never overwrite it. - The fleet management secret is generated once by CloudFormation (
GenerateSecretString) and stays constant across releases, so a release is one deploy. Rotating it is a deliberate operation with a runbook (below), not part of every deploy. Exec tasks keep receiving it from the host at launch, never from the task definition.
- One host JSON secret declared without values: Clerk keys, the Neon URLs, the
- Host configuration:
NODE_ENV=productionandPATCHY_ENVIRONMENT=<environment>;PATCHY_PUBLIC_BASE_URLandCLERK_AUTHORIZED_PARTIESset tohttps://cloud.patchyhq.com;PATCHY_TRUST_PROXYset to the VPC range;PATCHY_LIMITS_JSONwithexecution.fleet.budget15 (spares stay at the default 2);PATCHY_DEPLOYMENT_REVISIONset to the git sha;- the
ECS_*andEXECUTION_*settings from the stack.
- Observability. Host and exec log groups with retention. A Route 53 HTTPS health check on the deep health path of
cloud.patchyhq.comfeeds a CloudWatch alarm, which goes to an SNS topic with email subscriptions for Allison and Srikar. Email only: US SMS needs a registered sender number. - This repo is public. Account ids, email addresses and similar come from CDK context or workflow variables, never literals in the tree.
- Snapshot test. A vitest test synthesises the stack with
Template.fromStackand snapshots every security group and rule. It does no AWS lookups, so synth runs offline in CI.
3. The deploy workflow and docs
.github/workflows/deploy.yml. It runs onworkflow_dispatchonly, gated by a GitHubproductionenvironment that Allison approves. Aconcurrencygroup keeps it to one deploy at a time, and nobody deploys from a laptop. Steps:- build the reproducible server image (the
server-image.ymlsteps); - assume the deploy role through OIDC;
- deploy the base stack;
- push the image to ECR with
crane, tagged with the git sha; - deploy the app stack, pinned to the image digest. CloudFormation waits for ECS to settle; a bad host trips the circuit breaker and the stack update fails and rolls back;
- run the fleet promote step;
- confirm the service's primary deployment is on the new task definition.
- build the reproducible server image (the
- Fleet promote entrypoint. Add
node dist/fleet.js promote <revision>to the image. It stages and promotes a revision, replacing the spike's inlinenode -escript, and the workflow runs it as a one-off ECS task with the host task definition.- Promote only after ECS settles. Promoting earlier leaves a staged revision with no hosts if the rollout fails.
- Between the old hosts draining and the promote step, nothing replenishes spares; the existing spares cover that window.
- Rollback. Run the workflow on the previous sha. The build is reproducible, so it produces the same image, and the promote step stages and promotes the old revision. Migrations do not roll back: each release must work against the schema the next one leaves.
- Docs.
docs/OPERATIONS.md: deploy, rollback and restore sections. Restore covers the platform database, company databases and the content store from Neon history, plus the rule to keep retired credential keys for the backup window (packages/integrations/src/CredentialKeys.ts:132). Add a runbook for rotating the management secret when there is a reason (a suspected compromise, someone with access leaving, or on a calendar): deploy with the previous secret, revision and exec task definition supplied, promote and drain, then run a sealing deploy without them, as the spike's rollout/seal sequence does. Name the host log group in "Finding a request in CloudWatch".- ADR-0012: the production topology.
README.md: addapps/infrato the layout.
Launch additions
The items Allison accepted on 2026-10-02 (decision page) are folded into the sections above: the configuration refusals, PATCHY_TRUST_PROXY, stickiness, fleet budget 15 with two spares, the $300 budget alert, circuit-breaker rollback with a documented manual rollback, the uptime alert with a deep check, two hosts, the environment-name parameter, and the deploy, rollback and restore docs.
Done when
cdk synth is green in CI without AWS credentials, the snapshot test pins the security-group rules, the workflow and docs are in place, and nothing has been deployed.
Surfaces
apps/server, packages/auth, packages/serving, apps/infra (new), .github/workflows, docs/OPERATIONS.md, ADR-0012, README.md's layout.
Out for launch
A CloudWatch alarm matrix, dashboards, a second AZ for exec tasks, a WAF, a separate production account, SMS alerts, and Neon in code (#492 stays manual).
Activity
allisonmahmood commentedon Sep 28, 2026
Deployment dependency from #426: configure the host ALB target group for application-cookie stickiness (
stickiness.enabled=true,stickiness.type=app_cookie,stickiness.app_cookie.cookie_name=patchy_stream_affinity) in CDK. The SSE connection and/api/runtime/subscriptionsPOSTs must reach the same replica because its subscription registry is process-local. Postgres wakes propagate data changes, not control requests; round-robin POSTs cause generation refusals/reconnect loops. Keep the server-issued cookie and cover these target-group attributes in the synthesized infrastructure checks. ADR-0010 records the routing contract.docs(domain): reconcile the tier 2 map (#454)
allisonmahmood commentedon Oct 2, 2026
The production certificate exists. Take it as a stack parameter rather than creating one in CDK.
arn:aws:acm:us-east-1:614817375332:certificate/a51290c1-7852-42ca-accb-9b046655883d, forcloud.patchyhq.com, issued 2026-10-02, DNS-validated.patchyhq.comis on Vercel DNS, not Route 53, so CDK can't validate a certificate of its own without a deploy that hangs on a manual DNS step._ff5cf91f425958c826329c38a02daf21.cloud.patchyhq.comin Vercel. ACM renews the certificate automatically only while it is attached to the load balancer and that record still resolves.amazon.com.feat(server): a request wide event for every route (#488)
allisonmahmood commentedon Oct 4, 2026
Prototype: #415 in Alchemy (2026-10-04)
Question. Should #415's stack use Alchemy v2 (TypeScript on Effect 4, the same Effect as this repo) instead of AWS CDK?
Answer: CDK for launch. The prototype wrote #415's whole stack in Alchemy with stand-in containers, deployed it to the Patchy AWS account and destroyed it. Alchemy handled the shape and was fast, but the live runs reproduced every failure mode we worried about and found two more, and each one would be ours to clean up by hand. CloudFormation keeps the stack's state, refuses overlapping updates, carries on if the CLI dies, and attempts a rollback on failure; CDK rejects duplicate construct ids within a scope.
What worked
What failed, live
destroycould not remove.destroynever found.@internalfield.Carry into #415, whatever the tool
Everything deployed was destroyed and the Neon API key it used was revoked. The code stays off GitHub, since this repo is public.
Prototyped by Claude Opus 5.5 via Claude Code; reviewed at each step by GPT 6.1 Sol via codex.
feat(infra): the deploy workflow, the fleet promote entrypoint and pr…
feat(infra): the deploy workflow, the fleet promote entrypoint and pr…
feat(infra): the deploy workflow, the fleet promote entrypoint and pr…
feat(infra): the deploy workflow, the fleet promote entrypoint and pr…
feat(infra): the deploy workflow, the fleet promote entrypoint and pr…
feat(infra): the deploy workflow, the fleet promote entrypoint and pr…
feat(server): production hosts refuse unsafe config and expose a deep…
feat(infra): production stacks in AWS CDK
feat(infra): the deploy workflow, the fleet promote entrypoint and pr…
feat(infra): production stacks in AWS CDK (#520)
feat(infra): the deploy workflow, the fleet promote entrypoint and pr…