Synchronous publication of AWS Lambda metrics High

AWS Lambda metrics are published synchronously. To improve efficiency, write the results to a log.

Detector ID
java/sync-metric-publish@v1.0
Category
Common Weakness Enumeration (CWE) external icon

Noncompliant example

1public class SyncMetricPublishNoncompliant  implements RequestHandler<ScheduledEvent, Void> {
2
3    AmazonCloudWatch cloudwatch;
4
5    public SyncMetricPublishNoncompliant() {
6        cloudwatch = AmazonCloudWatchClientBuilder.standard().withRegion(Regions.US_WEST_2.toString()).build();
7    }
8
9    @Override
10    public Void handleRequest(ScheduledEvent scheduledEvent, Context context) {
11        final long startTime = System.currentTimeMillis();
12        doSomething(scheduledEvent, context);
13        final long endTime = System.currentTimeMillis();
14        final long timeElapsed = endTime - startTime;
15        PutMetricDataRequest putMetricDataRequest = new PutMetricDataRequest();
16        MetricDatum metricDatum = new MetricDatum().withMetricName("TIME_ELAPSED")
17                .withUnit(StandardUnit.Milliseconds).withValue((double) timeElapsed);
18        putMetricDataRequest.withNamespace("EXAMPLE_NAMESPACE").withMetricData(metricDatum);
19        // Noncompliant: uses CloudWatch to synchronically publish metrics from inside a Lambda.
20        cloudwatch.putMetricData(putMetricDataRequest);
21        return null;
22    }
23
24    private void doSomething(ScheduledEvent scheduledEvent, Context context) {
25        // Placeholder for code.
26    }
27}

Compliant example

1public class SyncMetricPublishCompliant implements RequestHandler<ScheduledEvent, Void> {
2
3    public SyncMetricPublishCompliant() {
4        // Initialize class members here.
5    }
6
7    @Override
8    public Void handleRequest(ScheduledEvent scheduledEvent, Context context) {
9        LambdaLogger logger = context.getLogger();
10        final long startTime = System.currentTimeMillis();
11        doSomething(scheduledEvent, context);
12        final long endTime = System.currentTimeMillis();
13        final long timeElapsed = endTime - startTime;
14        MetricDatum metricDatum = new MetricDatum().withMetricName("TIME_ELAPSED")
15                .withUnit(StandardUnit.Milliseconds).withValue((double) timeElapsed);
16        // Compliant: logs the metrics for further postprocessing outside the Lambda.
17        logger.log("Metrics: " + metricDatum);
18        return null;
19    }
20
21    private void doSomething(ScheduledEvent scheduledEvent, Context context) {
22        // Placeholder for code.
23    }
24}