Skip to content

Conversation

@phipag
Copy link
Contributor

@phipag phipag commented Nov 14, 2025

Summary

This PR makes the Metrics utility thread-safe for scenarios when used as a singleton in a Lambda handler that uses multi-threading while modifying dimensions or other metadata from within threads.

Changes

The main change is the introduction of a RequestScopedMetricsProxy. This class lazily initializes the corresponding metrics backend on the first invocation of e.g. .addMetric(...) using a ConcurrentHashMap<String, Metrics> keyed by X-Ray trace ID. This ensures that concurrent usages of Metrics are isolated per Lambda invocation (not per thread), and metrics added in child threads are correctly flushed.

This is the same approach we use in log buffering. See for example:

this.buffer = new KeyBuffer<>(maxBytes, event -> event.getMessage().getFormattedMessage().length(),
this::logOverflowWarning);

LambdaHandlerProcessor.getXrayTraceId().ifPresentOrElse(
traceId -> {
if (shouldBuffer(event.getLevel())) {
bufferEvent(traceId, event);
} else {
callAppenders(event);
}
// Flush buffer on error logs if configured
if (flushOnErrorLog && event.getLevel().isMoreSpecificThan(Level.WARN)) {
flushBuffer(traceId);
}
},

Issue number: #2289


By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.

Disclaimer: We value your time and bandwidth. As such, any pull requests created on non-triaged issues might not be successful.

@sonarqubecloud
Copy link

@phipag phipag merged commit 3ed0e0d into main Nov 17, 2025
22 checks passed
@phipag phipag deleted the phipag/issue2289 branch November 17, 2025 09:56
@github-project-automation github-project-automation bot moved this from Pending review to Coming soon in Powertools for AWS Lambda (Java) Nov 17, 2025
@phipag phipag linked an issue Nov 17, 2025 that may be closed by this pull request
2 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

Status: Coming soon

Development

Successfully merging this pull request may close these issues.

Maintenance: Thread-safety for Metrics Utility

2 participants