---
title: Rollback
description: The three ways back (ECS automatic, rollback.yml, Terraform revert), what each restores and what it does not, and how long each takes.
sidebar:
  icon: undo-2
---

:::danger[Every deploy and every rollback erases all saved documents]
The app still stores documents in in-memory SQLite (`server/app/internal/db.py`). A new task starts with the two seed patents, so replacing tasks loses every save, whether the release goes forward or back. "Zero downtime" holds for requests and does not hold for data until the app moves to the Aurora cluster that Task 1 created. There are no database migrations today, so nothing in this page restores data.
:::

## Three paths

**Automatic (ECS)**

**Trigger.** During a deploy, ECS rolls back by itself in three cases. The deployment circuit breaker fires when new tasks keep failing to start or failing health checks (`/healthz`, every 15 s, 3 failures). The rollback alarm `<name>-alb-target-5xx-ratio` fires when target 5xx exceed 5% of requests in 3 consecutive 1-minute periods; it counts only minutes with 20 or more requests. The rollback alarm `<name>-suggestion-failure-ratio` (Task 3) fires when more than 7.2% of AI suggestion requests fail in a 5-minute period with 10 or more requests.

**Restores.** The server, to the task definition of the last `COMPLETED` deployment. The client needs nothing: a deploy publishes it only after the server passes every check.

**Does not restore.** Data. It also misses a broken suggestions path when too few users send suggestions during the rollout (see below).

**Pipeline result.** Red. ECS ends "stable" on the old revision, so `verify-deployment.sh` fails the job unless the primary deployment runs the revision this run registered with `rolloutState` `COMPLETED`, and it prints `rolloutStateReason`.

**Time (estimate).** At least 3 minutes for the alarm to fire, or 3 failed task starts for the circuit breaker, then one task start and health check cycle on the old revision.

**Manual (rollback.yml)**

**Trigger.** A person runs `rollback.yml` on `main` with `environment`, `reason` (required) and, optionally, `sha`. In prod, a required reviewer approves the job.

**Restores.** The image and the client bundle of one earlier, successful release, together. The client goes first.

**Does not restore.** Configuration: the task definition keeps the newest settings from Terraform, with the old image. Data. A bad configuration change is reverted through Terraform (the third tab), not through `rollback.yml`.

**Afterwards.** Deploys to that environment stay frozen until someone runs `unfreeze.yml`, because `main` still contains the bad commit.

**Time (estimate).** About **10 to 15 minutes after approval**, summed from the parts in the table below. Not measured yet; measure it in staging.

**Infrastructure (Terraform)**

**Trigger.** A revert commit under `infrastructure/` goes through a PR (plan in the job summary) and is merged. `terraform.yml` then plans and applies it for dev, staging and prod in turn.

**Restores.** Terraform-managed configuration: alarms, scaling, networking, IAM, environment variables in the task definition.

**Does not restore.** The running tasks. Terraform registers a new task definition revision, but the service ignores `task_definition` (`lifecycle.ignore_changes`), so the change reaches the tasks only with the next release. Run `deploy.yml` on `main` after the apply. It also cannot bring back destroyed data.

**Time (estimate).** One PR review, plus plan and apply for each environment, plus one release.

## What the alarms can and cannot see

The WebSocket handler catches every exception and keeps the socket open, so a broken suggestions path (an OpenAI error, a schema change, a bad prompt) produces no HTTP 5xx and passes the health check. Task 3 closes most of that gap: every suggestion request now counts under an `outcome`, and `<name>-suggestion-failure-ratio` is a deployment alarm next to the 5xx alarm. See [The implemented example](/alerting-example).

Two limits remain:

- **It needs suggestion traffic.** The alarm counts only 5-minute periods with 10 or more suggestion requests. `generate-traffic.sh` sends document reads, not suggestions, so in a quiet dev or staging account the alarm has no data during the rollout. There, and in any quiet prod window, the smoke test is the check.
- **It is not verified in AWS.** The metric, the alarm math and the rollback have run only locally and in reading. See [Limits and next steps](/observability-limits#not-verified-against-a-live-account).

The WebSocket path is also covered by `scripts/ci/smoke.py`, which runs after every release in every environment. It opens `wss://<domain>/ws` through CloudFront, sends one claim, and fails unless a valid suggestions response with the same `request_id` arrives within 60 s. It makes one real OpenAI call per release. Tested locally against a stub server: a working AI passes, and an AI that raises fails with a timeout.

If the smoke test fails, the job fails and the new server stays live (the new client has not been published). Use `rollback.yml`: its default target is the release before.

An OpenAI outage during a release also trips the suggestion alarm and rolls the release back. The rollback is harmless, but it does not fix anything.

:::note[An alarm with no traffic]
`treat_missing_data` is `notBreaching`, and the alarm expression returns 0 below 20 requests a minute. A quiet dev or staging minute counts as healthy, so the alarm cannot fire there. While the job waits for the rollout, `generate-traffic.sh` sends one request a second (`GET /api/document/1`) through CloudFront, so ECS has data to judge. That is 60 a minute, and the WAF limit is 2,000 per 5 minutes per IP. The job log shows the count for each status code.
:::

## rollback.yml in detail

```mermaid
flowchart LR
  in["inputs: environment, sha?, reason"] --> resolve["resolve<br/>GitHub records only<br/>no AWS, no approval"]
  resolve -->|rejects bad SHA here| stop([stop, nothing changed])
  resolve --> release["release (_release.yml)<br/>group deploy-env, cancel-in-progress"]
  release --> supersede["supersede<br/>mark replaced releases inactive"]
```

**Which release is the target**

Never "task definition revision minus one". Terraform registers revisions too, and its first one points at the tag `bootstrap`, which does not exist.

`resolve-rollback-target.sh` reads the newest 50 release records for the environment.

- **`sha` given:** it must have a record whose latest status is `success` in this environment. Any other SHA is rejected before anything changes, and before the release job joins the deploy group, where it would cancel a running deploy.
- **`sha` empty:** the newest `success` release whose SHA differs from the newest record of any result. That newest record is the last release that changed the environment.

Tested against fixtures. Good then bad gives the good one. Good then a failed smoke test gives the good one. A SHA marked `inactive`, an unknown SHA, a short SHA, no records, or only one release are all rejected.

**The target must still exist**

Before any change, `check-release-artifacts.sh` checks the image digest in that account's ECR and `releases/<sha>/index.html` in the site bucket.

- **S3:** bundles under `releases/` are never overwritten or deleted. The bucket's lifecycle rule expires only noncurrent versions after 90 days, so bundles stay.
- **ECR: this can delete a rollback target.** The lifecycle policy (`modules/service/ecr.tf`) keeps the newest 30 images of any tag, by push time, in each account. It does not know which images are good releases. In dev, where every merge pushes an image, 30 pushes may be one or two weeks. In prod an image is pushed only when a prod release starts. A target older than the 30 newest pushes is gone, and the rollback stops at this check. Raising the count, or keeping images by a `release-` tag prefix, is a Terraform change for later.

**Freeze after a rollback**

After a rollback, `main` still contains the bad commit, and the next merge would ship it again. The rollback job sets an SSM parameter, `/patent-<env>/deploy/freeze`, with the SHA, reason, actor and run, as its first change. Every deploy checks it first and stops with that message. Run `unfreeze.yml` once the fix or a revert is on `main`.

A freeze in dev also blocks staging and prod, because each stage needs the one before it.

**A rollback never waits behind the bad deploy**

Deploys use the concurrency group `deploy-<env>` with `cancel-in-progress: false`. `rollback.yml` joins the same group with `cancel-in-progress: true`. It cancels a running or pending deploy at whatever step it reached, including a prod deploy that waits for approval. Because of that, a rollback always sets both client and server.

**An alarm that is already in ALARM**

The ECS documentation: "If an alarm is in the `ALARM` state at the beginning of a deployment, Amazon ECS will not monitor alarms for the duration of that deployment." During an incident the alarm is usually in `ALARM`, so `rollback.yml` does not rely on it. It relies on the circuit breaker, on `verify-deployment.sh` and on the smoke test.

**Code rollback, not configuration rollback**

`register-task-definition.sh` takes the newest active revision of the family and changes only the image. A rollback therefore keeps today's CPU, memory, environment and secrets, with the old code. If a configuration change caused the incident, revert it in Terraform (third tab above).

## Time, part by part

| Part | Value | Source |
|---|---|---|
| Approval wait (prod) | As long as a reviewer takes | `prod` Environment |
| Job start, checkout, credentials, freeze, checks | about 1 to 2 min | estimate |
| Client publish and CloudFront invalidation wait | about 1 to 5 min | estimate |
| Fargate task start and image pull | about 1 to 2 min | estimate |
| New task healthy | at least 2 × 15 s = 30 s | `modules/service/alb.tf` |
| Old task drain | 60 s deregistration delay, plus up to 120 s `stopTimeout` | `modules/service/main.tf` |
| ECS alarm bake time | default, "less than 5 minutes" | ECS documentation |
| Smoke test | up to 60 s | `scripts/ci/smoke.py` |
| **Total after approval** | **about 10 to 15 minutes, estimate** | sum of the above |

## Rules the pipeline cannot enforce

:::warning[Two artifacts, one release]
The server and the client roll back together, but open browser tabs keep running the old JavaScript until reload. Rule: **the API of release N must accept the client of release N−1.** Remove or change a field in two releases: first stop using it in the client, then remove it from the server. Code review enforces this; the pipeline cannot.
:::

:::info[Database changes, later]
When the app moves to Aurora, use expand-and-contract. Release 1 adds the new column or table and the code that writes both shapes. Release 2 switches reads. Release 3 removes the old shape. Then every rollback lands on code that understands the schema. There are no migrations today, so this is a rule for later, not a control that exists.
:::
