Skip to content

feat(infra): production infrastructure in AWS CDK and the deploy workflow #415

Closed

Description

@allisonmahmood

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=production host refuses to start without the Neon Object Storage settings. Today a missing PATCHY_S3_BUCKET falls 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 Clerk pk_test_/sk_test_ keys (packages/auth/src/Session.ts:69). Staging and the tier 2 spike keep their dev or fake keys.
  • Deep health check. A route outside /api (for example /healthz/deep) that queries the platform database and returns the running PATCHY_DEPLOYMENT_REVISION. The uptime check uses it, so anyone can see which build is live without AWS access. /healthz stays shallow for the load balancer and ECS, so a database blip doesn't make ECS replace every host. Today /healthz always 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 production environment. 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.dkr and logs interface 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 CDK stickinessCookieName only takes effect with stickinessCookieDuration), a 90 s deregistration delay, and a /healthz health 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, stopTimeout 120, 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, and iam:PassRole for 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 FargateTaskDefinition always creates one, so use CfnTaskDefinition or remove TaskRoleArn with an override.
    • Its own execution role, with ECR pull and logs only.
  • Security groups: ALB, host, exec-bootstrap, exec-sealed and endpoints, with the rules in docs/OPERATIONS.md plus 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.
  • Host configuration:
    • NODE_ENV=production and PATCHY_ENVIRONMENT=<environment>;
    • PATCHY_PUBLIC_BASE_URL and CLERK_AUTHORIZED_PARTIES set to https://cloud.patchyhq.com;
    • PATCHY_TRUST_PROXY set to the VPC range;
    • PATCHY_LIMITS_JSON with execution.fleet.budget 15 (spares stay at the default 2);
    • PATCHY_DEPLOYMENT_REVISION set to the git sha;
    • the ECS_* and EXECUTION_* 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.com feeds 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.fromStack and 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 on workflow_dispatch only, gated by a GitHub production environment that Allison approves. A concurrency group keeps it to one deploy at a time, and nobody deploys from a laptop. Steps:
    1. build the reproducible server image (the server-image.yml steps);
    2. assume the deploy role through OIDC;
    3. deploy the base stack;
    4. push the image to ECR with crane, tagged with the git sha;
    5. 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;
    6. run the fleet promote step;
    7. confirm the service's primary deployment is on the new task definition.
  • Fleet promote entrypoint. Add node dist/fleet.js promote <revision> to the image. It stages and promotes a revision, replacing the spike's inline node -e script, 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: add apps/infra to 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

  1. added
    ready-for-agent
    area:ci
    on Sep 28, 2026
  2. allisonmahmood commented on Sep 28, 2026

    @allisonmahmood
    OwnerAuthor

    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/subscriptions POSTs 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.

  3. allisonmahmood commented on Oct 2, 2026

    @allisonmahmood
    OwnerAuthor

    The production certificate exists. Take it as a stack parameter rather than creating one in CDK.

    • ACM arn:aws:acm:us-east-1:614817375332:certificate/a51290c1-7852-42ca-accb-9b046655883d, for cloud.patchyhq.com, issued 2026-10-02, DNS-validated.
    • patchyhq.com is 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.
    • Keep the validation CNAME _ff5cf91f425958c826329c38a02daf21.cloud.patchyhq.com in Vercel. ACM renews the certificate automatically only while it is attached to the load balancer and that record still resolves.
    • The zone's CAA records now allow amazon.com.
  4. allisonmahmood commented on Oct 4, 2026

    @allisonmahmood
    OwnerAuthor

    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

    • Every feat(infra): production infrastructure in AWS CDK and the deploy workflow #415 resource and setting was expressible, and our typecheck and Effect lint rules applied to it.
    • 52 resources in 43 s; a no-op deploy in 7 s.
    • A host rollout that could not start was rolled back by the ECS circuit breaker; Alchemy failed within a second of ECS marking it failed, the load balancer kept serving the old version, and the next good deploy converged. An update killed mid-wait resumed on rerun.
    • The image push (crane, no Docker) ran inside the deploy.
    • A Neon project, a never-suspending branch, a private bucket and an S3 credential written straight into Secrets Manager, from one program; a put and get with only those credentials worked.

    What failed, live

    • Two deploys at once on S3 state both exited 0 and left state mixing the two runs, which destroy could not remove.
    • A deploy killed right after creating a VPC left an orphan that destroy never found.
    • With the state gone, the plan was to create all 54 resources again: no recovery from tags.
    • Reusing a logical id across resource types silently dropped the ECS service, with no error.
    • Load balancer and target-group attribute drift was neither detected nor repaired; the drift check also flags untouched resources.
    • Secret values, including Neon's S3 key, sit in Alchemy's state in plain text.
    • No offline plan; the CI security-group snapshot works only through Alchemy's test harness and an @internal field.
    • The GitHub OIDC provider resource adopts an existing provider by URL and deletes it on destroy.
    • About 300 extra lockfile packages. Neon's default-branch compute is not configurable, and there is no Postgres role resource.

    Carry into #415, whatever the tool

    • The interface endpoints' private DNS covers the whole VPC, so the endpoint security group must admit the hosts as well as exec tasks. Found live: once DNS propagated, new host tasks could not reach CloudWatch Logs, and the same would hit ECR.
    • Decide whether the previous exec task-definition revision stays runnable during a rollout; CloudFormation deregisters a replaced definition unless it is retained.
    • Declare the GitHub OIDC provider in exactly one stack, and serialise deploys with a workflow concurrency group.
    • Secrets a person fills in are declared without a value, and a later deploy must not overwrite them.

    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.

  5. added
    area:server
    area:docs
    on Oct 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area:ciarea:docsarea:serverready-for-agent

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions