diff --git a/cmd/consumer/main.go b/cmd/consumer/main.go index 0f780450c..b80c1a97a 100644 --- a/cmd/consumer/main.go +++ b/cmd/consumer/main.go @@ -3,6 +3,7 @@ package main import ( "context" "github.com/warmbly/warmbly/internal/app/cloudlink" + "github.com/warmbly/warmbly/internal/app/consumermetrics" emailverifyapp "github.com/warmbly/warmbly/internal/app/emailverify" "github.com/warmbly/warmbly/internal/app/mailpush" "github.com/warmbly/warmbly/internal/app/slackapp" @@ -775,6 +776,19 @@ func main() { newConsumerAgent().Run(ctx) }() + // The consumer's ECS service scales on this; unset on every other deployment. + if name := consumermetrics.Name(); name != "" { + if diagnostics, ok := consumerBus.(eventbus.Diagnostics); ok { + go func() { + if err := consumermetrics.Run(ctx, diagnostics, name); err != nil { + log.Printf("Warning: worker event backlog metric disabled: %v", err) + } + }() + } else { + log.Printf("Warning: worker event backlog metric disabled: the %s bus reports no backlog", consumerBus.Name()) + } + } + log.Println("Consumer started, listening on", kafka.TopicWorkerEvents) jobsService.Start(ctx) diff --git a/deploy/terraform/aws/runtime/README.md b/deploy/terraform/aws/runtime/README.md index 31021c37e..b5b76dfb4 100644 --- a/deploy/terraform/aws/runtime/README.md +++ b/deploy/terraform/aws/runtime/README.md @@ -26,7 +26,10 @@ service runs the default or the `-kafka` image. Service revision and desired count are deployment operations; Terraform ignores those two fields after service creation, and its task definition outputs describe prepared revisions, not necessarily running ones. Start new services at zero and use explicit counts -when activating them. +when activating them. Once a service is running, `autoscaling` (in +`autoscaling.tf`) moves each listed service between its bounds: the consumer +on its worker-event backlog, other listed services on CPU. A service left out +of the map keeps its count. `.github/workflows/deploy-aws.yml` selects the image and preserves the live managed attachment-download setting unless Terraform explicitly supplies its environment diff --git a/deploy/terraform/aws/runtime/autoscaling.tf b/deploy/terraform/aws/runtime/autoscaling.tf new file mode 100644 index 000000000..917e67d55 --- /dev/null +++ b/deploy/terraform/aws/runtime/autoscaling.tf @@ -0,0 +1,176 @@ +# Task scaling. Desired count stays out of Terraform's hands (aws_ecs_service ignores it), so these +# bounds and policies are what move it. A service left out keeps the count it was given by hand. +variable "autoscaling" { + description = "Task count bounds by service. The consumer scales on its worker-event backlog, every other service on average CPU at cpu percent" + type = map(object({ + min = number + max = number + cpu = optional(number, 60) + })) + default = { + consumer = { min = 1, max = 6 } + } + validation { + condition = alltrue([for name, scaling in var.autoscaling : + contains(["backend", "consumer", "forms", "tracking"], name) && + scaling.min >= 1 && scaling.min <= scaling.max && scaling.max <= 20 && + floor(scaling.min) == scaling.min && floor(scaling.max) == scaling.max && + scaling.cpu >= 20 && scaling.cpu <= 90 + ]) + error_message = "Scale backend, consumer, forms or tracking between integer bounds 1 <= min <= max <= 20 at a cpu target of 20-90%. Realtime tracks presence per task, so it keeps a fixed count." + } +} + +variable "consumer_backlog_scale_out" { + description = "Worker events waiting, held for two minutes, that add a consumer task; ten times this adds two" + type = number + default = 1000 + validation { + condition = var.consumer_backlog_scale_out >= 1 + error_message = "consumer_backlog_scale_out is at least one event." + } +} + +variable "consumer_quiet_minutes" { + description = "Minutes with no worker event waiting before one consumer task is removed" + type = number + default = 30 + validation { + condition = var.consumer_quiet_minutes >= 10 && var.consumer_quiet_minutes % 5 == 0 + error_message = "consumer_quiet_minutes is a multiple of 5, at least 10." + } +} + +locals { + autoscaling = { for name, scaling in var.autoscaling : name => scaling if contains(keys(var.services), name) } + cpu_scaling = { for name, scaling in local.autoscaling : name => scaling if name != "consumer" } + backlog_scaling = contains(keys(local.autoscaling), "consumer") + # The contract with internal/app/consumermetrics. + consumer_metric = { + namespace = "Warmbly/Consumer" + name = "WorkerEventBacklog" + dimensions = { Consumer = var.name } + } +} + +resource "aws_appautoscaling_target" "service" { + for_each = local.autoscaling + service_namespace = "ecs" + scalable_dimension = "ecs:service:DesiredCount" + resource_id = "service/${split("/", local.foundation.cluster_arn)[1]}/${aws_ecs_service.service[each.key].name}" + min_capacity = each.value.min + max_capacity = each.value.max +} + +resource "aws_appautoscaling_policy" "cpu" { + for_each = local.cpu_scaling + name = "cpu" + policy_type = "TargetTrackingScaling" + service_namespace = aws_appautoscaling_target.service[each.key].service_namespace + scalable_dimension = aws_appautoscaling_target.service[each.key].scalable_dimension + resource_id = aws_appautoscaling_target.service[each.key].resource_id + target_tracking_scaling_policy_configuration { + target_value = each.value.cpu + scale_out_cooldown = 60 + scale_in_cooldown = 300 + predefined_metric_specification { + predefined_metric_type = "ECSServiceAverageCPUUtilization" + } + } +} + +# Every consumer task shares one durable, so the backlog is the fleet's, and a waiting event means every lane is full. +resource "aws_appautoscaling_policy" "consumer_scale_out" { + count = local.backlog_scaling ? 1 : 0 + name = "backlog-scale-out" + policy_type = "StepScaling" + service_namespace = aws_appautoscaling_target.service["consumer"].service_namespace + scalable_dimension = aws_appautoscaling_target.service["consumer"].scalable_dimension + resource_id = aws_appautoscaling_target.service["consumer"].resource_id + step_scaling_policy_configuration { + adjustment_type = "ChangeInCapacity" + cooldown = 180 + metric_aggregation_type = "Maximum" + step_adjustment { + metric_interval_lower_bound = 0 + metric_interval_upper_bound = var.consumer_backlog_scale_out * 9 + scaling_adjustment = 1 + } + step_adjustment { + metric_interval_lower_bound = var.consumer_backlog_scale_out * 9 + scaling_adjustment = 2 + } + } +} + +resource "aws_appautoscaling_policy" "consumer_scale_in" { + count = local.backlog_scaling ? 1 : 0 + name = "quiet-scale-in" + policy_type = "StepScaling" + service_namespace = aws_appautoscaling_target.service["consumer"].service_namespace + scalable_dimension = aws_appautoscaling_target.service["consumer"].scalable_dimension + resource_id = aws_appautoscaling_target.service["consumer"].resource_id + step_scaling_policy_configuration { + adjustment_type = "ChangeInCapacity" + cooldown = var.consumer_quiet_minutes * 60 + metric_aggregation_type = "Maximum" + step_adjustment { + metric_interval_upper_bound = 0 + scaling_adjustment = -1 + } + } +} + +# Missing data never counts: no publisher means no scaling either way. +resource "aws_cloudwatch_metric_alarm" "consumer_backlog" { + count = local.backlog_scaling ? 1 : 0 + alarm_name = "${var.name}-consumer-backlog" + alarm_description = "Worker events waited for a free consumer lane for two minutes; adds consumer tasks" + namespace = local.consumer_metric.namespace + metric_name = local.consumer_metric.name + dimensions = local.consumer_metric.dimensions + statistic = "Maximum" + period = 60 + evaluation_periods = 2 + datapoints_to_alarm = 2 + comparison_operator = "GreaterThanOrEqualToThreshold" + threshold = var.consumer_backlog_scale_out + treat_missing_data = "notBreaching" + alarm_actions = [aws_appautoscaling_policy.consumer_scale_out[0].arn] +} + +resource "aws_cloudwatch_metric_alarm" "consumer_quiet" { + count = local.backlog_scaling ? 1 : 0 + alarm_name = "${var.name}-consumer-quiet" + alarm_description = "No worker event waited for ${var.consumer_quiet_minutes} minutes; removes one consumer task" + namespace = local.consumer_metric.namespace + metric_name = local.consumer_metric.name + dimensions = local.consumer_metric.dimensions + statistic = "Maximum" + period = 300 + evaluation_periods = var.consumer_quiet_minutes / 5 + datapoints_to_alarm = var.consumer_quiet_minutes / 5 + comparison_operator = "LessThanThreshold" + threshold = 1 + treat_missing_data = "notBreaching" + alarm_actions = [aws_appautoscaling_policy.consumer_scale_in[0].arn] +} + +data "aws_iam_policy_document" "consumer_metrics" { + count = local.backlog_scaling ? 1 : 0 + statement { + actions = ["cloudwatch:PutMetricData"] + resources = ["*"] + condition { + test = "StringEquals" + variable = "cloudwatch:namespace" + values = [local.consumer_metric.namespace] + } + } +} +resource "aws_iam_role_policy" "consumer_metrics" { + count = local.backlog_scaling ? 1 : 0 + name = "publish-backlog" + role = aws_iam_role.application["consumer"].id + policy = data.aws_iam_policy_document.consumer_metrics[0].json +} diff --git a/deploy/terraform/aws/runtime/main.tf b/deploy/terraform/aws/runtime/main.tf index a7f02ef0f..11b02b8cf 100644 --- a/deploy/terraform/aws/runtime/main.tf +++ b/deploy/terraform/aws/runtime/main.tf @@ -149,7 +149,8 @@ locals { ) } service_environment = { - for name, service in var.services : name => merge(service.environment, name == "backend" ? { DB_MIGRATIONS_ON_START = "false" } : {}, local.tls_environment[name]) + for name, service in var.services : name => merge(service.environment, name == "backend" ? { DB_MIGRATIONS_ON_START = "false" } : {}, local.tls_environment[name], + name == "consumer" && local.backlog_scaling ? { CONSUMER_METRICS_CLOUDWATCH = local.consumer_metric.dimensions.Consumer } : {}) } parameter_secrets = { for name, service in var.services : name => [ diff --git a/deploy/terraform/aws/runtime/tests/target_tls.tftest.hcl b/deploy/terraform/aws/runtime/tests/target_tls.tftest.hcl index 9315837f1..03fdb4923 100644 --- a/deploy/terraform/aws/runtime/tests/target_tls.tftest.hcl +++ b/deploy/terraform/aws/runtime/tests/target_tls.tftest.hcl @@ -23,6 +23,9 @@ mock_provider "aws" { mock_resource "aws_cloudwatch_log_group" { defaults = { arn = "arn:aws:logs:us-east-1:123456789012:log-group:mock" } } + mock_resource "aws_appautoscaling_policy" { + defaults = { arn = "arn:aws:autoscaling:us-east-1:123456789012:scalingPolicy:mock" } + } mock_data "aws_caller_identity" { defaults = { account_id = "123456789012" } } @@ -354,3 +357,50 @@ run "evidence_writer_refuses_other_accounts" { } expect_failures = [aws_iam_role.tls_recovery_evidence] } + +run "consumer_scales_on_its_backlog_by_default" { + command = apply + assert { + condition = keys(aws_appautoscaling_target.service) == ["consumer"] && aws_appautoscaling_target.service["consumer"].min_capacity == 1 && aws_appautoscaling_target.service["consumer"].max_capacity == 6 + error_message = "Only the consumer scales by default, between one and six tasks." + } + assert { + condition = aws_appautoscaling_target.service["consumer"].resource_id == "service/warmbly-production/warmbly-production-consumer" && length(aws_appautoscaling_policy.cpu) == 0 + error_message = "The consumer's target names its ECS service and has no CPU policy." + } + assert { + condition = (aws_cloudwatch_metric_alarm.consumer_backlog[0].threshold == 1000 && aws_cloudwatch_metric_alarm.consumer_backlog[0].treat_missing_data == "notBreaching" && + aws_cloudwatch_metric_alarm.consumer_quiet[0].evaluation_periods * aws_cloudwatch_metric_alarm.consumer_quiet[0].period == 1800 && aws_cloudwatch_metric_alarm.consumer_quiet[0].treat_missing_data == "notBreaching") + error_message = "A sustained backlog adds tasks, half an hour quiet removes one, and missing data does neither." + } + assert { + condition = contains(jsondecode(aws_ecs_task_definition.service["consumer"].container_definitions)[0].environment, { name = "CONSUMER_METRICS_CLOUDWATCH", value = "warmbly-production" }) && length(aws_iam_role_policy.consumer_metrics) == 1 + error_message = "The consumer publishes the backlog its alarms read, and its role may publish it." + } +} + +run "listed_services_scale_on_cpu" { + command = apply + variables { + autoscaling = { + backend = { min = 2, max = 4 } + tracking = { min = 1, max = 3, cpu = 70 } + } + } + assert { + condition = aws_appautoscaling_policy.cpu["backend"].target_tracking_scaling_policy_configuration[0].target_value == 60 && aws_appautoscaling_policy.cpu["tracking"].target_tracking_scaling_policy_configuration[0].target_value == 70 + error_message = "Each listed service tracks its CPU target." + } + assert { + condition = length(aws_cloudwatch_metric_alarm.consumer_backlog) == 0 && length(aws_iam_role_policy.consumer_metrics) == 0 && !contains([for env in jsondecode(aws_ecs_task_definition.service["consumer"].container_definitions)[0].environment : env.name], "CONSUMER_METRICS_CLOUDWATCH") + error_message = "A consumer left out keeps its count and publishes nothing." + } +} + +run "realtime_keeps_a_fixed_count" { + command = plan + variables { + autoscaling = { realtime = { min = 1, max = 2 } } + } + expect_failures = [var.autoscaling] +} diff --git a/docs/content/docs/development/aws-fargate.mdx b/docs/content/docs/development/aws-fargate.mdx index 06688aa0e..b7c3fa3ea 100644 --- a/docs/content/docs/development/aws-fargate.mdx +++ b/docs/content/docs/development/aws-fargate.mdx @@ -119,6 +119,33 @@ outbound IP changes, and preserve each worker ID throughout the move. The same root can instead run an autoscaling fleet with no public IPv4 address on any worker; see [AWS worker fleet](/development/aws-workers/). +## Scale tasks + +Terraform sets each service's task count once and then leaves it alone, so the +runtime root's `autoscaling` map is what moves it afterwards. A service that is +not listed keeps the count it was given by hand. + +- The consumer is listed by default, between one and six tasks. Every consumer + task reads one shared queue, so the root scales it on that queue's backlog: + worker events still waiting for a free lane. A backlog of + `consumer_backlog_scale_out` events (default `1000`) held for two minutes adds + a task, and ten times that adds two. After `consumer_quiet_minutes` (default + `30`) with nothing waiting, one task is removed. The consumer publishes the + backlog every minute through `CONSUMER_METRICS_CLOUDWATCH`, which the root + sets along with permission to publish it. A missing metric neither adds nor + removes tasks, and a consumer image from before the publisher (including one + restored by a rollback) publishes nothing, so after a deploy or rollback check + that `WorkerEventBacklog` still has fresh data points. A task keeps each mailbox's events in order among the ones it + took; with more than one task, two events for one mailbox can be handled at + the same time by different tasks. +- `backend`, `tracking` and `forms` scale on average CPU when listed, at `cpu` + percent (default `60`). Set `min` to the count each one runs today. +- `realtime` keeps a fixed count. Presence is tracked inside each task, so + members connected to different tasks would not see each other. + +To hold a service at one count, suspend its scaling activities in Application +Auto Scaling, or remove it from `autoscaling`. + ## Prepare configuration Use the deployment README to bootstrap encrypted, versioned Terraform state and diff --git a/docs/content/docs/development/configuration.mdx b/docs/content/docs/development/configuration.mdx index ecfab10c1..d7fde5c11 100644 --- a/docs/content/docs/development/configuration.mdx +++ b/docs/content/docs/development/configuration.mdx @@ -389,6 +389,7 @@ The attachment download proxy works with filesystem and S3-compatible stores and | `CODEC_READ_BOTH` | Migration setting for Go services: read JSON and Confluent-framed Avro while writing only `CODEC_PROVIDER`. Requires Kafka builds and the old Schema Registry until all retained Avro has drained | `false` | yes | | `EVENTBUS_HANDLER_TIMEOUT` | How long one handler may take before the delivery is abandoned. A subscription that needs longer carries its own budget, never shorter than this one: a worker's command subscription runs under 195s, because a send is given 120s (the SMTP client's 90s conversation plus the checks before it) and then records its result. On NATS the ack wait is the subscription's budget plus 5s | `30s` | yes | | `CONSUMER_EVENT_CONCURRENCY` | How many mailboxes' worker events one consumer handles at once, from `1` to `64`, on both Kafka and NATS. Each mailbox's events stay in order, and on NATS a slow mailbox holds only its own lane. Unset, it follows the consumer's database pool (`DB_MAX_CONNS`), so raising the pool raises it too. Invalid values use the default | one per pooled database connection, at most `64` | yes | +| `CONSUMER_METRICS_CLOUDWATCH` | Read by the consumer: the name it publishes the `Warmbly/Consumer` metric `WorkerEventBacklog` under (dimension `Consumer`) every minute, the worker events no consumer has taken yet, which the [AWS consumer scaling](/development/aws-fargate/#scale-tasks) reads. The AWS runtime root sets it when the consumer scales. Uses the AWS default credential chain, so the consumer's role needs `cloudwatch:PutMetricData`. Leave it unset on any other deployment | unset | yes | | `PUBSUB_ENABLED` | `false` uses the Redis bridge for realtime fanout, `true` uses Google Pub/Sub | `false` | yes | | `GCP_PROJECT_ID` | Project when `PUBSUB_ENABLED=true` | unset | yes | diff --git a/internal/app/consumermetrics/consumermetrics.go b/internal/app/consumermetrics/consumermetrics.go new file mode 100644 index 000000000..d0113d71b --- /dev/null +++ b/internal/app/consumermetrics/consumermetrics.go @@ -0,0 +1,84 @@ +// Package consumermetrics publishes the worker-event backlog to CloudWatch, +// the signal the consumer's ECS service scales on. +// Optional: a deployment that does not set CONSUMER_METRICS_CLOUDWATCH runs none of it. +package consumermetrics + +import ( + "context" + "fmt" + "os" + "strings" + "time" + + "github.com/aws/aws-sdk-go-v2/aws" + awsconfig "github.com/aws/aws-sdk-go-v2/config" + "github.com/aws/aws-sdk-go-v2/service/cloudwatch" + "github.com/aws/aws-sdk-go-v2/service/cloudwatch/types" + "github.com/rs/zerolog/log" + "github.com/warmbly/warmbly/internal/infrastructure/eventbus" + "github.com/warmbly/warmbly/internal/infrastructure/kafka" +) + +// Namespace and BacklogMetric are the contract with the scaling alarms in deploy/terraform/aws/runtime. +const ( + Namespace = "Warmbly/Consumer" + // BacklogMetric is worker events published and not yet taken by any consumer task. + BacklogMetric = "WorkerEventBacklog" + interval = time.Minute +) + +// Name is CONSUMER_METRICS_CLOUDWATCH, the Consumer dimension; empty publishes nothing. +func Name() string { + return strings.TrimSpace(os.Getenv("CONSUMER_METRICS_CLOUDWATCH")) +} + +// Backlog reads the consumer group's backlog off the bus; false when the bus cannot say. +func Backlog(ctx context.Context, bus eventbus.Diagnostics) (int64, bool) { + out := bus.Diagnose(ctx, time.Now(), []eventbus.DiagnosticScope{{ID: "worker_events", Group: "consumer-group", Topics: []string{kafka.TopicWorkerEvents}}}) + for _, m := range out.Metrics { + // NATS reports undelivered messages, Kafka the committed lag. + if (m.ID == "pending" || m.ID == "committed_lag") && m.Count != nil { + return *m.Count, true + } + } + return 0, false +} + +// Run publishes the backlog every minute until ctx ends. An unknown backlog +// publishes nothing, which neither grows nor shrinks the service. +func Run(ctx context.Context, bus eventbus.Diagnostics, name string) error { + cfg, err := awsconfig.LoadDefaultConfig(ctx) + if err != nil { + return fmt.Errorf("consumer metrics: aws config: %w", err) + } + client := cloudwatch.NewFromConfig(cfg) + dimension := []types.Dimension{{Name: aws.String("Consumer"), Value: aws.String(name)}} + ticker := time.NewTicker(interval) + defer ticker.Stop() + publish := func() { + // A stalled read or request must not hold back the next minute's sample. + ctx, cancel := context.WithTimeout(ctx, interval) + defer cancel() + backlog, ok := Backlog(ctx, bus) + if !ok { + log.Warn().Msg("worker event backlog unknown; not published") + return + } + if _, err := client.PutMetricData(ctx, &cloudwatch.PutMetricDataInput{ + Namespace: aws.String(Namespace), + MetricData: []types.MetricDatum{{ + MetricName: aws.String(BacklogMetric), Dimensions: dimension, Unit: types.StandardUnitCount, Value: aws.Float64(float64(backlog)), + }}, + }); err != nil { + log.Warn().Err(err).Msg("worker event backlog not published") + } + } + for { + publish() + select { + case <-ctx.Done(): + return nil + case <-ticker.C: + } + } +} diff --git a/internal/app/consumermetrics/consumermetrics_test.go b/internal/app/consumermetrics/consumermetrics_test.go new file mode 100644 index 000000000..91b837a83 --- /dev/null +++ b/internal/app/consumermetrics/consumermetrics_test.go @@ -0,0 +1,40 @@ +package consumermetrics + +import ( + "context" + "testing" + "time" + + "github.com/warmbly/warmbly/internal/infrastructure/eventbus" + "github.com/warmbly/warmbly/internal/models" +) + +type diagnostics []models.MonitoringMetric + +func (d diagnostics) Diagnose(context.Context, time.Time, []eventbus.DiagnosticScope) models.MonitoringSource { + return models.MonitoringSource{Metrics: d} +} + +func count(n int64) *int64 { return &n } + +func TestBacklogReadsEachBusesUndeliveredCount(t *testing.T) { + cases := map[string]struct { + metrics diagnostics + want int64 + known bool + }{ + "nats": {diagnostics{{ID: "ack_pending", Count: count(800)}, {ID: "pending", Count: count(1234)}}, 1234, true}, + "kafka": {diagnostics{{ID: "committed_lag", Count: count(56)}, {ID: "members", Count: count(2)}}, 56, true}, + "idle": {diagnostics{{ID: "pending", Count: count(0)}}, 0, true}, + "unavailable": {diagnostics{{ID: "broker_queue"}}, 0, false}, + "no count": {diagnostics{{ID: "pending"}}, 0, false}, + } + for name, tc := range cases { + t.Run(name, func(t *testing.T) { + got, known := Backlog(context.Background(), tc.metrics) + if got != tc.want || known != tc.known { + t.Fatalf("Backlog = %d, %v; want %d, %v", got, known, tc.want, tc.known) + } + }) + } +}