fix(cloudwatch): bound the datapoints Floci publishes itself (#9348)

The CloudWatch metric store has no size bound, and since SQS publishes AWS/SQS
metrics for every active queue each minute it grows with no PutMetricData call,
until a persisted cwmetrics.json no longer fits the heap on load.

floci.services.cloudwatchmetrics.max-stored-datapoints (default 100000) now caps
the datapoints kept per account in each namespace a MinuteMetricsPublisher
writes (AWS/SQS, AWS/Redshift). After each tick the publisher drops the oldest
over the ceiling, down to nine tenths of it, through the metric key index;
other namespaces are never cut, and 0 or less turns the ceiling off.
This commit is contained in:
Tal Efraim authored and GitHub committed 2026-11-24 11:20:34 -04:00
1 parent cb573492ca
commit c40b11fe9a
16 files changed
+328 -17

No files matched your search

@@ -2554,6 +2554,17 @@ public interface EmulatorConfig {
interface CloudWatchMetricsServiceConfig {
@WithDefault("true")
boolean enabled();
/**
* Upper bound on the datapoints kept per account in each namespace a service publishes by
* itself, such as AWS/SQS. Every datapoint is its own entry in a store that is held in memory
* and written out whole, and those services add some for each resource every minute, so
* without a bound the store outgrows the heap long before the 15 days AWS keeps one-minute
* data. Oldest datapoints are dropped first once exceeded; 0 or less keeps them all. Other
* namespaces, where only a client's PutMetricData writes, are never cut back.
*/
@WithDefault("100000")
int maxStoredDatapoints();
}
interface PaymentCryptographyServiceConfig {
@@ -254,6 +254,32 @@ public class CloudWatchMetricsService implements Resettable {
deleteInEveryAccount(metricStore, d -> namespace.equals(d.getNamespace()) && d.getTimestamp() < cutoffSeconds);
}
/**
* Drops the oldest {@code namespace} datapoints of every account holding more than {@code ceiling} of
* them, down to nine tenths of it so that the next calls find nothing to sort. A service that writes
* its own metrics each minute calls it: that history grows without a request, and would outgrow the
* heap well inside the 15 days it is kept for. Counting reads the key index, so nothing is dropped
* before storage has loaded.
*/
public void deleteOldestMetricData(String namespace, int ceiling) {
if (!metricKeys.isBuilt()) {
return;
}
// Index first, as in deleteMetricDataBefore.
Map<String, Set<String>> oldestByAccount = metricKeys.removeOldest(namespace, ceiling, ceiling - ceiling / 10);
if (oldestByAccount.isEmpty()) {
return;
}
if (metricStore instanceof AccountAwareStorageBackend<MetricDatum> aware) {
aware.deleteAllAtomicallyForAccounts(oldestByAccount);
} else {
oldestByAccount.values().forEach(metricStore::deleteAllAtomically);
}
oldestByAccount.forEach((account, oldest) -> LOG.debugv(
"Dropped the {0} oldest {1} datapoint(s) of account {2} to stay within the ceiling of {3}",
oldest.size(), namespace, account, ceiling));
}
private static <V> void deleteInEveryAccount(StorageBackend<String, V> store, Predicate<V> expired) {
if (store instanceof AccountAwareStorageBackend<V> aware) {
aware.deleteAllAccountsMatching(expired);
@@ -1,9 +1,13 @@
package io.floci.aws.services.cloudwatch.metrics;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.NavigableSet;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListSet;
@@ -56,13 +60,56 @@ final class MetricKeyIndex {
String cutoff = timestampSegment(cutoffSeconds);
for (Map<String, NavigableSet<String>> endingsBySeries : endingsBySeriesByAccount.values()) {
endingsBySeries.forEach((series, endings) -> {
if (series.startsWith(namespaceSegment, series.indexOf("::"))) {
if (isInNamespace(series, namespaceSegment)) {
endings.headSet(cutoff).clear();
}
});
}
}
/**
* In every account holding more than {@code ceiling} keys of {@code namespace}, removes the oldest of
* them across its series until {@code keep} are left. Returns the removed keys by account.
*/
Map<String, Set<String>> removeOldest(String namespace, int ceiling, int keep) {
String namespaceSegment = "::" + namespace + "::";
Map<String, Set<String>> removedByAccount = new HashMap<>();
endingsBySeriesByAccount.forEach((account, endingsBySeries) -> {
List<String> namespaceSeries = new ArrayList<>();
long held = 0;
for (Map.Entry<String, NavigableSet<String>> endings : endingsBySeries.entrySet()) {
if (isInNamespace(endings.getKey(), namespaceSegment)) {
namespaceSeries.add(endings.getKey());
held += endings.getValue().size();
}
}
if (held <= ceiling) {
return;
}
List<SeriesEnding> oldestFirst = new ArrayList<>();
for (String series : namespaceSeries) {
for (String ending : endingsBySeries.get(series)) {
oldestFirst.add(new SeriesEnding(series, ending));
}
}
oldestFirst.sort(Comparator.comparing(SeriesEnding::ending).thenComparing(SeriesEnding::series));
Set<String> removed = new HashSet<>();
for (SeriesEnding oldest : oldestFirst.subList(0, Math.max(0, oldestFirst.size() - keep))) {
endingsBySeries.get(oldest.series()).remove(oldest.ending());
removed.add(oldest.series() + oldest.ending());
}
removedByAccount.put(account, removed);
});
return removedByAccount;
}
private static boolean isInNamespace(String series, String namespaceSegment) {
return series.startsWith(namespaceSegment, series.indexOf("::"));
}
/** One key split as the index holds it; an ending starts with its timestamp, so endings sort by time. */
private record SeriesEnding(String series, String ending) {}
/** The account's keys of {@code series} stamped in {@code [fromSeconds, toSeconds)}, oldest first. */
List<String> keysBetween(String account, String series, long fromSeconds, long toSeconds) {
Map<String, NavigableSet<String>> endingsBySeries = endingsBySeriesByAccount.get(account);
@@ -16,7 +16,8 @@ import java.util.concurrent.TimeUnit;
* Shared scheduling, minute claims and retention for service-generated CloudWatch metrics. A tick
* runs just after each minute boundary and stamps its samples with the minute that ended, so a call
* lands in the minute it was made, as on AWS. Once an hour it drops the namespace's datapoints older
* than the 15 days AWS keeps one-minute data, so the generated history stays bounded.
* than the 15 days AWS keeps one-minute data, and every minute the oldest of an account's beyond the
* ceiling it was given, so the generated history stays bounded. A ceiling of 0 or less keeps them all.
*/
public abstract class MinuteMetricsPublisher<T> {
@@ -28,23 +29,27 @@ public abstract class MinuteMetricsPublisher<T> {
private final CloudWatchMetricsService metricsService;
private final String namespace;
private final boolean enabled;
private final int maxStoredDatapoints;
private final Clock clock;
private final ScheduledExecutorService scheduler;
private long lastAttemptedMinute = Long.MIN_VALUE;
protected MinuteMetricsPublisher(CloudWatchMetricsService metricsService, String namespace, boolean enabled) {
this(metricsService, namespace, enabled, Clock.systemUTC(), Executors.newSingleThreadScheduledExecutor(task -> {
Thread thread = new Thread(task, namespace + "-metrics-publisher");
thread.setDaemon(true);
return thread;
}));
protected MinuteMetricsPublisher(CloudWatchMetricsService metricsService, String namespace, boolean enabled,
int maxStoredDatapoints) {
this(metricsService, namespace, enabled, maxStoredDatapoints, Clock.systemUTC(),
Executors.newSingleThreadScheduledExecutor(task -> {
Thread thread = new Thread(task, namespace + "-metrics-publisher");
thread.setDaemon(true);
return thread;
}));
}
protected MinuteMetricsPublisher(CloudWatchMetricsService metricsService, String namespace, boolean enabled,
Clock clock, ScheduledExecutorService scheduler) {
int maxStoredDatapoints, Clock clock, ScheduledExecutorService scheduler) {
this.metricsService = metricsService;
this.namespace = namespace;
this.enabled = enabled;
this.maxStoredDatapoints = maxStoredDatapoints;
this.clock = clock;
this.scheduler = scheduler;
}
@@ -108,6 +113,14 @@ public abstract class MinuteMetricsPublisher<T> {
namespace, RETENTION);
}
}
if (maxStoredDatapoints > 0) {
try {
metricsService.deleteOldestMetricData(namespace, maxStoredDatapoints);
} catch (RuntimeException e) {
LOG.warnv(e, "Dropping the oldest {0} datapoints over the ceiling of {1} failed; the next minute"
+ " tries again", namespace, maxStoredDatapoints);
}
}
}
/** Reading half a minute back absorbs drift of the fixed-rate schedule away from the boundary. */
@@ -28,12 +28,14 @@ public class RedshiftMetricsPublisher {
@Inject
public RedshiftMetricsPublisher(RedshiftService redshiftService, CloudWatchMetricsService metricsService,
Instance<RedshiftMetricCollector> collectors, EmulatorConfig config) {
this(redshiftService, metricsService, collectors, isEnabled(config));
this(redshiftService, metricsService, collectors, isEnabled(config),
config.services().cloudwatchmetrics().maxStoredDatapoints());
}
RedshiftMetricsPublisher(RedshiftService redshiftService, CloudWatchMetricsService metricsService,
Iterable<RedshiftMetricCollector> collectors, boolean enabled) {
this.publisher = new MinuteMetricsPublisher<>(metricsService, NAMESPACE, enabled) {
Iterable<RedshiftMetricCollector> collectors, boolean enabled,
int maxStoredDatapoints) {
this.publisher = new MinuteMetricsPublisher<>(metricsService, NAMESPACE, enabled, maxStoredDatapoints) {
@Override
protected List<RedshiftMetricTarget> collectTargets(Instant now) {
return redshiftService.availableMetricTargets();
@@ -34,7 +34,8 @@ public class SqsMetricsPublisher {
public SqsMetricsPublisher(SqsService sqsService, CloudWatchMetricsService metricsService, EmulatorConfig config) {
boolean enabled = config.services().sqs().enabled() && config.services().sqs().cloudwatchMetricsEnabled()
&& config.services().cloudwatchmetrics().enabled();
this.publisher = new MinuteMetricsPublisher<>(metricsService, NAMESPACE, enabled) {
this.publisher = new MinuteMetricsPublisher<>(metricsService, NAMESPACE, enabled,
config.services().cloudwatchmetrics().maxStoredDatapoints()) {
@Override
protected List<SqsService.QueueMetrics> collectTargets(Instant now) {
return sqsService.collectQueueMetrics(now);