feat(sqs): publish AWS/SQS queue metrics to CloudWatch (#6280)

* feat(sqs): publish AWS/SQS queue metrics to CloudWatch

Every active queue now reports the AWS/SQS metrics once a minute on the
QueueName dimension: the depth gauges, ApproximateAgeOfOldestMessage, the
send, receive, delete and empty-receive counters, SentMessageSize, and for
FIFO queues the in-flight groups and deduplicated sends. The samples follow
what SQS sends on AWS, so alarms, GetMetricData and GetMetricStatistics see
queue metrics without PutMetricData.

The CloudWatch metric store is now journaled under persistent mode, as the
CloudWatch Logs event store is, since it takes a write per metric per active
queue every minute.

Closes #6275

* fix(sqs): stamp queue metrics with the minute that ended

The publisher now ticks just after each minute boundary and stamps its
samples with the minute that ended, so a call counts in the minute it was
made instead of the minute of a startup-relative tick. A queue whose write
fails no longer stops the others, and the log names it. A queue deleted and
created again between the snapshot and the lookup is skipped instead of
reporting the old queue's depth under the new one.

* fix(sqs): bound AWS/SQS metric history and finish the tick on shutdown

The publisher now drops AWS/SQS datapoints older than the 15 days AWS keeps
one-minute data, once an hour, so the history it generates for an active
queue stays bounded. On shutdown it stops before the storage flush and waits
for a running tick, so the last minute is not written after the store closed.

* test(sqs): keep the scheduled metrics tick out of the test run

The acceptance test publishes its own ticks, but the scheduled one could
still stamp the test queue's depth into a complete period newer than them,
since a tick stamps the minute that just ended. floci.services.sqs.
cloudwatch-metrics-enabled now turns the tick off, and the test
configuration does, as it does for the S3 lifecycle sweep. It also lets a
user opt out of the AWS/SQS metric volume.

* test(sqs): build the metrics test's queue service with SqsServiceFactory
This commit is contained in:
Mario Toffia authored and GitHub committed 2026-10-23 06:57:51 -04:00
1 parent 151cf30476
commit ba353021e1
18 files changed
+893 -48

No files matched your search

@@ -0,0 +1,80 @@
package com.floci.test;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.services.cloudwatch.CloudWatchClient;
import software.amazon.awssdk.services.cloudwatch.model.Datapoint;
import software.amazon.awssdk.services.cloudwatch.model.Dimension;
import software.amazon.awssdk.services.cloudwatch.model.DimensionFilter;
import software.amazon.awssdk.services.cloudwatch.model.Metric;
import software.amazon.awssdk.services.cloudwatch.model.MetricDataResult;
import software.amazon.awssdk.services.cloudwatch.model.StandardUnit;
import software.amazon.awssdk.services.cloudwatch.model.Statistic;
import software.amazon.awssdk.services.sqs.SqsClient;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
@DisplayName("SQS - AWS/SQS CloudWatch metrics")
class SqsQueueMetricsTest {
private static final String NAMESPACE = "AWS/SQS";
private static final List<String> STANDARD_QUEUE_METRICS = List.of("ApproximateNumberOfMessagesVisible",
"ApproximateNumberOfMessagesNotVisible", "ApproximateNumberOfMessagesDelayed",
"ApproximateAgeOfOldestMessage", "NumberOfMessagesSent", "NumberOfMessagesReceived",
"NumberOfMessagesDeleted", "NumberOfEmptyReceives", "SentMessageSize");
@Test
@DisplayName("A queue's depth and sends reach AWS/SQS without PutMetricData")
void queueMetricsArePublishedUnderAwsSqs() throws InterruptedException {
try (SqsClient sqs = TestFixtures.sqsClient(); CloudWatchClient cloudWatch = TestFixtures.cloudWatchClient()) {
String queueName = TestFixtures.uniqueName("sdk-sqs-metrics");
String queueUrl = sqs.createQueue(request -> request.queueName(queueName)).queueUrl();
try {
sqs.sendMessage(request -> request.queueUrl(queueUrl).messageBody("held"));
Dimension queue = Dimension.builder().name("QueueName").value(queueName).build();
Instant start = Instant.now().minus(Duration.ofMinutes(5));
// SQS publishes once a minute. On AWS a newly active queue can take up to 15 minutes,
// and ListMetrics can trail the statistics by as long.
TestFixtures.await(() -> visibleMaximum(cloudWatch, queue, start).contains(1.0)
&& sent(cloudWatch, queue, start).stream().mapToDouble(Datapoint::sum).sum() == 1.0
&& listed(cloudWatch, queueName).containsAll(STANDARD_QUEUE_METRICS),
queueName, "the AWS/SQS metrics of one sent message",
Duration.ofMinutes(TestFixtures.isRealAws() ? 20 : 3).toNanos(),
TestFixtures.isRealAws() ? 30_000 : 1_000);
assertThat(sent(cloudWatch, queue, start)).extracting(Datapoint::unit)
.containsOnly(StandardUnit.COUNT);
} finally {
sqs.deleteQueue(request -> request.queueUrl(queueUrl));
}
}
}
private static List<Double> visibleMaximum(CloudWatchClient cloudWatch, Dimension queue, Instant start) {
List<MetricDataResult> results = cloudWatch.getMetricData(request -> request
.startTime(start).endTime(Instant.now().plus(Duration.ofMinutes(1)))
.metricDataQueries(query -> query.id("visible").metricStat(stat -> stat
.metric(metric -> metric.namespace(NAMESPACE)
.metricName("ApproximateNumberOfMessagesVisible").dimensions(queue))
.period(60).stat("Maximum")))).metricDataResults();
return results.isEmpty() ? List.of() : results.get(0).values();
}
private static List<Datapoint> sent(CloudWatchClient cloudWatch, Dimension queue, Instant start) {
return cloudWatch.getMetricStatistics(request -> request.namespace(NAMESPACE)
.metricName("NumberOfMessagesSent").dimensions(queue).startTime(start)
.endTime(Instant.now().plus(Duration.ofMinutes(1))).period(60).statistics(Statistic.SUM))
.datapoints();
}
private static List<String> listed(CloudWatchClient cloudWatch, String queueName) {
return cloudWatch.listMetrics(request -> request.namespace(NAMESPACE)
.dimensions(DimensionFilter.builder().name("QueueName").value(queueName).build()))
.metrics().stream().map(Metric::metricName).toList();
}
}