Skip to content

Commit 3889b86

Browse files
faangbaitclaude
andcommitted
feat(infra): autoscale services and verify backups and rollouts
Add CPU target tracking for web and api (2 to 6 tasks). scale.sh moves the autoscaling floor and ceiling so stop.sh stays stopped. Deploy now waits for services-stable and fails when the PRIMARY deployment is not the revision it registered, so a circuit-breaker rollback fails the run. Add backup-db.sh and restore-db.sh (pg_restore via SSM into a scratch database by default), host s3:GetObject on dumps, and an alarm when no pg_dump lands for 26 hours. Add saved Logs Insights queries, more dashboard widgets, an infra runbook, and requirement scores. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent a4f3151 commit 3889b86

18 files changed

Lines changed: 466 additions & 23 deletions

File tree

‎.github/workflows/deploy.yml‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,11 +100,34 @@ jobs:
100100
arn=$(aws ecs register-task-definition --cli-input-json "$new" --query 'taskDefinition.taskDefinitionArn' --output text)
101101
aws ecs update-service --cluster "$cluster" --service "$name" --task-definition "$arn" \
102102
--query 'service.deployments[0].id' --output text
103+
echo "$name $arn" >> "$RUNNER_TEMP/rolled"
103104
}
104105
106+
: > "$RUNNER_TEMP/rolled"
105107
while IFS= read -r name; do
106108
[ -n "$name" ] || continue
107109
roll "$name"
108110
done <<EOF
109111
$COMPONENTS
110112
EOF
113+
114+
# A failed revision trips the circuit breaker, which rolls back and also
115+
# ends stable. So after the wait, the PRIMARY deployment must be the
116+
# revision this run registered, with rollout COMPLETED.
117+
- name: Wait for rollout
118+
if: steps.ecr.outputs.skip != 'true'
119+
run: |
120+
set -euo pipefail
121+
services=$(cut -d' ' -f1 "$RUNNER_TEMP/rolled" | xargs)
122+
[ -n "$services" ] || exit 0
123+
# shellcheck disable=SC2086
124+
aws ecs wait services-stable --cluster "$cluster" --services $services
125+
while read -r name want; do
126+
read -r got state <<<"$(aws ecs describe-services --cluster "$cluster" --services "$name" \
127+
--query 'services[0].deployments[?status==`PRIMARY`] | [0].[taskDefinition,rolloutState]' --output text)"
128+
echo "$name primary=$got rollout=$state"
129+
if [ "$got" != "$want" ] || [ "$state" != COMPLETED ]; then
130+
echo "::error::$name did not roll to $want"
131+
exit 1
132+
fi
133+
done < "$RUNNER_TEMP/rolled"

‎infra/README.md‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,25 @@
11
# infra/
2+
3+
Terraform for every cell in `var.cells` (today: `node-3tier`, env `prod`, `us-east-1`).
4+
State: S3 backend in `versions.tf`. Apply: the `Cell apply` workflow, or `terraform apply` here.
5+
6+
## Runtime scripts
7+
8+
All take the cell name. `AWS_REGION` and `ENVIRONMENT` override `us-east-1` and `prod`.
9+
10+
| Script | Does |
11+
| --- | --- |
12+
| `scripts/start.sh <cell>` | `web` and `api` to 2 tasks, autoscaling floor 2, ceiling 6. |
13+
| `scripts/stop.sh <cell>` | `web` and `api` to 0 tasks, floor and ceiling 0. |
14+
| `scripts/scale.sh <cell> <web\|api\|all> <n>` | Desired count and floor to `n`. Ceiling `MAX_COUNT` (6) or `n` if higher. |
15+
| `scripts/backup-db.sh <cell>` | `pg_dump` to S3 now, then an AWS Backup job for the data volume. |
16+
| `scripts/restore-db.sh <cell> [stamp\|latest] [db]` | `pg_restore` a dump on the host via SSM. Default target is the scratch DB `<db>_restore`. Over the live DB needs `RESTORE_LIVE=yes`. |
17+
18+
The next apply resets the autoscaling floor and ceiling to the cell config (`runtime.desired_count`, `runtime.max_count`).
19+
20+
## Where to look
21+
22+
- Dashboard: CloudWatch `<cell>-<env>-runtime`.
23+
- Logs: CloudWatch `/<cell>-<env>/{web,api,db}`. Saved Logs Insights queries `<cell>-<env>/*`. ALB access logs in S3 `<cell>-<env>-alb-*`.
24+
- Alarms publish to SNS `<cell>-<env>` (email subscription).
25+
- Backups: vault `<cell>-<env>-db` (daily 05:00 UTC), dumps in `<cell>-<env>-db-dumps-*` (nightly 03:30 UTC). Alarm `<cell>-<env>-pg-dump-missing` fires after 26 hours without a dump.

‎infra/main.tf‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,8 @@ module "runtime" {
125125
db_instance_id = module.database[each.key].instance_id
126126
repositories = each.value.runtime.repositories
127127
desired_count = each.value.runtime.desired_count
128+
max_count = each.value.runtime.max_count
129+
cpu_target_percent = each.value.runtime.cpu_target_percent
128130
cpu = each.value.runtime.cpu
129131
memory = each.value.runtime.memory
130132
image_tag = each.value.runtime.image_tag

‎infra/modules/database/main.tf‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,13 @@ data "aws_iam_policy_document" "db" {
169169
resources = ["${aws_s3_bucket.dumps.arn}/pg_dump/*"]
170170
}
171171

172+
# infra/scripts/restore-db.sh pulls a dump back onto the host.
173+
statement {
174+
sid = "ReadDumps"
175+
actions = ["s3:GetObject"]
176+
resources = ["${aws_s3_bucket.dumps.arn}/pg_dump/*"]
177+
}
178+
172179
statement {
173180
sid = "ListDumps"
174181
actions = ["s3:ListBucket"]

‎infra/modules/database/monitoring.tf‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,41 @@ resource "aws_cloudwatch_metric_alarm" "memory" {
126126
tags = var.tags
127127
}
128128

129+
# pg-backup.sh logs "dump uploaded" after both files reach S3, and the
130+
# CloudWatch agent ships that line. No such line for 26 hours means the timer,
131+
# the dump, or the upload failed.
132+
resource "aws_cloudwatch_log_metric_filter" "pg_dump_uploaded" {
133+
name = "${var.name}-pg-dump-uploaded"
134+
log_group_name = var.log_group_name
135+
pattern = "\"dump uploaded\""
136+
137+
metric_transformation {
138+
name = "PgDumpUploaded"
139+
namespace = "${var.project}/Database"
140+
value = "1"
141+
}
142+
}
143+
144+
resource "aws_cloudwatch_metric_alarm" "pg_dump_missing" {
145+
alarm_name = "${var.name}-pg-dump-missing"
146+
alarm_description = "No nightly pg_dump reached S3 in 26 hours"
147+
namespace = "${var.project}/Database"
148+
metric_name = "PgDumpUploaded"
149+
statistic = "Sum"
150+
comparison_operator = "LessThanThreshold"
151+
threshold = 1
152+
period = 3600
153+
evaluation_periods = 26
154+
treat_missing_data = "breaching"
155+
156+
alarm_actions = [var.alert_topic_arn]
157+
ok_actions = [var.alert_topic_arn]
158+
159+
depends_on = [aws_cloudwatch_log_metric_filter.pg_dump_uploaded]
160+
161+
tags = var.tags
162+
}
163+
129164
# Postgres ERROR/FATAL/PANIC lines, from the centralized log group.
130165
resource "aws_cloudwatch_log_metric_filter" "pg_errors" {
131166
name = "${var.name}-postgres-errors"

‎infra/modules/logging/queries.tf‎

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
# Saved CloudWatch Logs Insights queries, listed under "Saved queries" in the
2+
# console. The runtime and database modules already require the web, api and
3+
# db groups, so this indexes them directly.
4+
5+
locals {
6+
group = { for k, g in aws_cloudwatch_log_group.tier : k => g.name }
7+
8+
queries = {
9+
errors-all-tiers = {
10+
groups = values(local.group)
11+
query = <<-EOT
12+
fields @timestamp, @log, @logStream, @message
13+
| filter @message like /(?i)(error|fatal|panic|exception|unhandled)/
14+
| sort @timestamp desc
15+
| limit 200
16+
EOT
17+
}
18+
19+
# morgan "dev" lines from the web tier: GET / 200 971.433 ms - 257
20+
web-requests = {
21+
groups = [local.group["web"]]
22+
query = <<-EOT
23+
parse @message /(?<method>GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS) (?<path>\S+) \S*?(?<status>[1-5]\d\d).*?(?<ms>[\d.]+) ms/
24+
| filter ispresent(status)
25+
| stats count(*) as requests, avg(ms) as avg_ms, pct(ms, 95) as p95_ms by path, status
26+
| sort requests desc
27+
EOT
28+
}
29+
30+
api-errors = {
31+
groups = [local.group["api"]]
32+
query = <<-EOT
33+
fields @timestamp, @logStream, @message
34+
| filter @message like /(?i)error/
35+
| sort @timestamp desc
36+
| limit 200
37+
EOT
38+
}
39+
40+
# log_min_duration_statement = 500 writes "duration: N ms" for slow SQL.
41+
postgres-slow-and-errors = {
42+
groups = [local.group["db"]]
43+
query = <<-EOT
44+
fields @timestamp, @logStream, @message
45+
| filter @message like /duration:|ERROR:|FATAL:|PANIC:/
46+
| sort @timestamp desc
47+
| limit 200
48+
EOT
49+
}
50+
51+
backups = {
52+
groups = [local.group["db"]]
53+
query = <<-EOT
54+
fields @timestamp, @message
55+
| filter @logStream like /pg-backup/
56+
| sort @timestamp desc
57+
| limit 50
58+
EOT
59+
}
60+
}
61+
}
62+
63+
resource "aws_cloudwatch_query_definition" "this" {
64+
for_each = local.queries
65+
66+
name = "${var.name}/${each.key}"
67+
log_group_names = each.value.groups
68+
query_string = each.value.query
69+
}
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# Target tracking on average service CPU. Terraform owns the floor and the
2+
# ceiling. infra/scripts/scale.sh moves both for start, stop, and manual scale;
3+
# the next apply puts them back to desired_count and max_count.
4+
5+
resource "aws_appautoscaling_target" "service" {
6+
for_each = {
7+
web = aws_ecs_service.web.name
8+
api = aws_ecs_service.api.name
9+
}
10+
11+
service_namespace = "ecs"
12+
resource_id = "service/${aws_ecs_cluster.this.name}/${each.value}"
13+
scalable_dimension = "ecs:service:DesiredCount"
14+
min_capacity = var.desired_count
15+
max_capacity = var.max_count
16+
17+
tags = var.tags
18+
}
19+
20+
resource "aws_appautoscaling_policy" "cpu" {
21+
for_each = aws_appautoscaling_target.service
22+
23+
name = "${var.name}-${each.key}-cpu"
24+
policy_type = "TargetTrackingScaling"
25+
service_namespace = each.value.service_namespace
26+
resource_id = each.value.resource_id
27+
scalable_dimension = each.value.scalable_dimension
28+
29+
target_tracking_scaling_policy_configuration {
30+
target_value = var.cpu_target_percent
31+
scale_out_cooldown = 60
32+
scale_in_cooldown = 300
33+
34+
predefined_metric_specification {
35+
predefined_metric_type = "ECSServiceAverageCPUUtilization"
36+
}
37+
}
38+
}

‎infra/modules/runtime/monitoring.tf‎

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,73 @@ resource "aws_cloudwatch_dashboard" "runtime" {
143143
]
144144
}
145145
},
146+
{
147+
type = "metric"
148+
width = 12
149+
height = 6
150+
properties = {
151+
title = "Postgres memory and disk used (%)"
152+
region = local.region
153+
view = "timeSeries"
154+
period = 300
155+
yAxis = { left = { min = 0, max = 100 } }
156+
metrics = [
157+
["CWAgent", "mem_used_percent", "InstanceId", var.db_instance_id, { stat = "Average", label = "memory" }],
158+
[{ expression = "SEARCH('{CWAgent,InstanceId,fstype,path} MetricName=\"disk_used_percent\" InstanceId=\"${var.db_instance_id}\"', 'Maximum', 300)", id = "disk", label = "disk" }],
159+
]
160+
}
161+
},
162+
{
163+
type = "metric"
164+
width = 12
165+
height = 6
166+
properties = {
167+
title = "Response time by tier (p90)"
168+
region = local.region
169+
view = "timeSeries"
170+
period = 60
171+
stat = "p90"
172+
metrics = [
173+
["AWS/ApplicationELB", "TargetResponseTime", "LoadBalancer", aws_lb.this.arn_suffix, "TargetGroup", aws_lb_target_group.web.arn_suffix, { label = "web" }],
174+
["...", aws_lb_target_group.api.arn_suffix, { label = "api" }],
175+
]
176+
}
177+
},
178+
{
179+
type = "metric"
180+
width = 12
181+
height = 6
182+
properties = {
183+
title = "Healthy targets and running tasks"
184+
region = local.region
185+
view = "timeSeries"
186+
period = 60
187+
stat = "Minimum"
188+
metrics = [
189+
["AWS/ApplicationELB", "HealthyHostCount", "LoadBalancer", aws_lb.this.arn_suffix, "TargetGroup", aws_lb_target_group.web.arn_suffix, { label = "web healthy" }],
190+
["...", aws_lb_target_group.api.arn_suffix, { label = "api healthy" }],
191+
["ECS/ContainerInsights", "RunningTaskCount", "ClusterName", aws_ecs_cluster.this.name, "ServiceName", aws_ecs_service.web.name, { label = "web running" }],
192+
["...", aws_ecs_service.api.name, { label = "api running" }],
193+
]
194+
}
195+
},
196+
{
197+
type = "metric"
198+
width = 12
199+
height = 6
200+
properties = {
201+
title = "Errors by source"
202+
region = local.region
203+
view = "timeSeries"
204+
period = 300
205+
stat = "Sum"
206+
metrics = [
207+
["AWS/ApplicationELB", "HTTPCode_ELB_5XX_Count", "LoadBalancer", aws_lb.this.arn_suffix, { label = "ALB 5xx" }],
208+
[".", "HTTPCode_Target_4XX_Count", ".", ".", { label = "target 4xx" }],
209+
["${var.project}/Database", "PostgresErrors", { label = "Postgres errors" }],
210+
]
211+
}
212+
},
146213
]
147214
})
148215
}

‎infra/modules/runtime/variables.tf‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,25 @@ variable "desired_count" {
115115
}
116116
}
117117

118+
variable "max_count" {
119+
description = "Autoscaling ceiling, tasks per service."
120+
type = number
121+
default = 6
122+
nullable = false
123+
124+
validation {
125+
condition = var.max_count >= var.desired_count
126+
error_message = "max_count must be at least desired_count."
127+
}
128+
}
129+
130+
variable "cpu_target_percent" {
131+
description = "Average service CPU that target tracking holds."
132+
type = number
133+
default = 60
134+
nullable = false
135+
}
136+
118137
variable "cpu" {
119138
description = "Fargate CPU units for each task."
120139
type = number

‎infra/scripts/backup-db.sh‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
#!/bin/sh
2+
# Usage: backup-db.sh <cell>
3+
# On-demand backup, e.g. before a risky change. Runs the nightly pg_dump now
4+
# (pg-backup.service on the host, via SSM), then starts an AWS Backup job for
5+
# the Postgres data volume in the cell's vault. Prints the backup job ID.
6+
set -eu
7+
8+
cell=${1:?cell name, e.g. node-3tier}
9+
. "$(dirname "$0")/db-host.sh"
10+
11+
run_on_db "pg_dump now" 'set -eu
12+
systemctl start pg-backup.service
13+
tail -n 2 /var/log/pg-backup.log'
14+
15+
account=$(aws sts get-caller-identity --query Account --output text)
16+
volume=$(aws ec2 describe-volumes --region "$region" \
17+
--filters "Name=tag:Name,Values=${name}-postgres-data" \
18+
--query 'Volumes[0].VolumeId' --output text)
19+
role=$(aws iam get-role --role-name "${name}-backup" --query Role.Arn --output text)
20+
21+
aws backup start-backup-job --region "$region" \
22+
--backup-vault-name "${name}-db" \
23+
--resource-arn "arn:aws:ec2:${region}:${account}:volume/${volume}" \
24+
--iam-role-arn "$role" \
25+
--lifecycle "DeleteAfterDays=${RETENTION_DAYS:-35}" \
26+
--query BackupJobId --output text

0 commit comments

Comments
 (0)