Skip to content

feat: Collect OTEL metrics in AWS Lambda - #4166

Merged
jsumners-nr merged 7 commits into
newrelic:mainfrom
jsumners-nr:issue-4126
Jul 27, 2026
Merged

feat: Collect OTEL metrics in AWS Lambda#4166
jsumners-nr merged 7 commits into
newrelic:mainfrom
jsumners-nr:issue-4126

Conversation

@jsumners-nr

@jsumners-nr jsumners-nr commented Jul 22, 2026

Copy link
Copy Markdown
Contributor

See newrelic/newrelic-node-examples#379.

We should probably just ship this as "prep for an upcoming feature" instead of keeping a stale branch around. The agent is going to do the right thing, but the data won't get shipped until the extension is updated (possibly in a future quarter).


Summary

Adds collection of OpenTelemetry metrics in the AWS Lambda (serverless) environment. In serverless mode the periodic exporter is effectively disabled and metrics are instead flushed on demand during the agent's synchronous harvest: SetupMetrics.flushToString() collects and serializes the metrics to a base64 OTLP protobuf payload, which ServerlessCollector attaches to the flushed payload as otlp_payload.

Closes #4126.

Changes

  • SetupMetrics: in serverless mode, use a never-firing export interval, finalize the exporter eagerly (no started-event wait), and expose flushToString().
  • NRProxyingSerializer / NROTLPMetricExporter: cache the last serialization (lastSerialization / serializedData) so the harvest can retrieve the encoded payload after an export; awsLambdaMode forces caching independent of audit logging.
  • ServerlessCollector.flushPayloadSync: pull OTEL metrics via agent.otel.metrics.flushToString() when present and include them as otlp_payload; made internal flush helpers private.
  • Agent: internal otel API accessor (attached by lib/otel/setup.js).

Testing

  • Fixed an audit-logging regression found while writing coverage: NRProxyingSerializer compared the auditEnabled function reference to true instead of calling it.
  • Repaired existing tests broken by the refactor (private flush helpers; serverless-mode branch in the metrics index mock).
  • Added coverage for the serialization cache/purge + awsLambdaMode, the serializedData getter, the serverless no-started-listener path, flushToString (in its own file — it registers a process-global meter provider and reaches the network, nock-stubbed), and ServerlessCollector attaching otlp_payload.
  • Affected unit suites: 172 tests passing; lint clean.

🤖 Generated with Claude Code

jsumners-nr and others added 2 commits July 22, 2026 15:09
Add coverage for the serverless OTEL metrics path introduced on this
branch and fix an audit-logging regression it surfaced.

- Fix `NRProxyingSerializer` audit guard: `auditEnabled === true` compared
  the function reference (always false); call it instead. Caught by the
  existing "logs when serializing" test.
- Repair broken tests the private-field/serverless refactor left red:
  rewrite `#flushPayloadSync` to assert on real flushed output rather than
  monkeypatching the now-private `#doFlush`, and give the metrics index
  mock agent a `serverlessMode` so both constructor branches are reachable.
- Add coverage for `lastSerialization` caching/purge and `awsLambdaMode`,
  the `serializedData` getter, the serverless no-`started`-listener path,
  `flushToString` (isolated file: global meter provider + network), and
  `ServerlessCollector` attaching `otlp_payload` from `flushToString`.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This object has a few methods it only uses internally. I found it difficult to determine which methods actually needed to be exposed for the agent to work correctly. So I updated the internal only methods to be private. This makes it clear which methods are meant to be the public API and which are meant to be private.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As a consequence of making the API clearer, tests needed to be updated such that they monkey patch the underlying filesystem methods instead of replacing methods directly on the collector.

assert.equal(flushed, true)
})

await t.test('includes OTEL metrics as otlp_payload when the metrics API is present', async (t) => {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a new test that verifies the collector attaches the serialized protobuf data correctly.

Add debug logs distinguishing the standard (defer to agent connect) and
serverless (finalize eagerly) OTEL metrics bootstrap paths, and cover them
in the metrics setup tests via a capturing logger.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@codecov

codecov Bot commented Jul 22, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 97.44%. Comparing base (3b440f3) to head (c2e5200).
⚠️ Report is 3 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #4166      +/-   ##
==========================================
- Coverage   97.51%   97.44%   -0.08%     
==========================================
  Files         517      520       +3     
  Lines       62593    62778     +185     
  Branches        1        1              
==========================================
+ Hits        61039    61175     +136     
- Misses       1554     1603      +49     
Flag Coverage Δ
integration-tests-cjs-22.x 73.64% <57.39%> (-0.03%) ⬇️
integration-tests-cjs-24.x 74.23% <67.45%> (-0.01%) ⬇️
integration-tests-cjs-26.x 74.23% <67.45%> (-0.01%) ⬇️
integration-tests-esm-22.x 54.55% <28.00%> (+0.01%) ⬆️
integration-tests-esm-24.x 55.85% <28.00%> (+0.01%) ⬆️
integration-tests-esm-26.x 55.85% <28.00%> (+0.01%) ⬆️
unit-tests-22.x 89.19% <99.40%> (+0.07%) ⬆️
unit-tests-24.x 89.13% <99.40%> (+0.07%) ⬆️
unit-tests-26.x 89.14% <99.40%> (+0.08%) ⬆️
versioned-tests-22.x 97.44% <100.00%> (-0.08%) ⬇️
versioned-tests-24.x 97.44% <100.00%> (-0.08%) ⬇️
versioned-tests-26.x 97.44% <100.00%> (-0.08%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

jsumners-nr and others added 4 commits July 23, 2026 09:15
Follow the refactor to an in-memory capturing exporter:

- Fix flushToString to read `lastSerialization` (NRCapturingExporter's
  accessor); it was still reading the removed `serializedData` getter and
  returning undefined.
- Add nr-capturing-exporter unit tests: serialize + SUCCESS callback, audit
  log, cache purge-on-read, and forceFlush/shutdown no-ops.
- Drop the now-obsolete network stubbing from the flushToString test (the
  capturing exporter does no network I/O) and assert serverless bootstrap
  emits `otelMetricsBootstrapped` synchronously.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

@bizob2828 bizob2828 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A few comments/questions. I assumed you verified this with real lambdas?

// be fully synchronous here. That API is _both_ callback and promise
// based. So we have to finalize our export out-of-band when the metrics
// API is available (i.e. OTEL + OTEL Metrics have been enabled).
this._agent.otel.metrics.flushToString().then((serializedMetrics) => {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what happens if this fails? There's no catch handler so the agent may produce an unhandledRejection

@bizob2828 bizob2828 Jul 27, 2026

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also are we certain this is actually going to work? this happens right before the lambda shutdown, feels like there's a chance of data loss because the promise may not have resolved

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's not really possible for it to fail.

The promise comes from the .collect method on the metrics reader object. That method is just compiling a JSON object of all the data that has been buffered.

The callback comes from the .export method. Since we supply our own exporter that only deals with the in-memory data, there's nothing for the callback to fail on.

Regarding shutdown, I'm open to suggestions. The OTEL API requires the codes as I have written it. Our code expects fully synchronous operations. So I can't await the promise but I have to use the promise. 🤷‍♂️

return
}

if (this._agent.otel?.metrics?.flushToString) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Feels weird to be checking if there's a property on otel.metrics. What if there's some idea of enabled flags for all these otel apis?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Example please?

Comment thread lib/otel/metrics/index.js
// proxy so that we can manually collect metrics when the agent performs
// a harvest during serverless mode execution.
logger.debug('Finalizing OTEL metrics in serverless mode.')
proxyExporter.exporter = new NRCapturingExporter({ logger })

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

since we do not do a round trip with collector it's missing the entity_guid and any other otlp_resource_attibutes. Is the extension aware they will need to decorate metrics with those attributes?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's a question for the team implementing the extension. To my knowledge, it already does this.

Comment thread lib/otel/metrics/index.js
async flushToString() {
const { resourceMetrics: collectedMetrics } = await this.#metricReader.collect()
await new Promise((resolve) => {
this.#metricExporter.exporter.export(collectedMetrics, () => {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can you provide a comment explaining this. so we collect the metrics, then call export but return what was last serialized? What happens if the export fails, could it return what was last collected on warm lambda invocations?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What suggestion do you have for the jsdoc block? I think it already provides the explanation.

There isn't any failure case possibility here that I am aware of. As explained above, all of this is happening on in-memory data. The only failure case I know of for .export is it not being able to ship the collected data to a remote HTTP endpoint. We are avoiding that completely.

Comment thread lib/otel/metrics/index.js
const generateProxyAgentFactory = require('./generate-proxy-agent-factory.js')

// See https://developer.mozilla.org/en-US/docs/Web/API/Window/setTimeout#maximum_delay_value
const MAXIMUM_TIMEOUT_TIME = ((2 ^ 32) / 2) - 1

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do you have to provide an export interval? Doesn't this just create a timer that will never resolve and thus hang the process?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, we have to provide an interval. Otherwise we have to write our own metrics reader. The only actual implementation upstream provides is the periodic reader (https://open-telemetry.github.io/opentelemetry-js/classes/_opentelemetry_sdk-node.metrics.PeriodicExportingMetricReader.html).

The timer will not keep the process alive:

https://github.com/open-telemetry/opentelemetry-js/blob/3f9756ab3fb15aec3ac420f255cdbe70d3d280a8/packages/sdk-metrics/src/export/PeriodicExportingMetricReader.ts#L246-L257

@jsumners-nr

Copy link
Copy Markdown
Contributor Author

A few comments/questions. I assumed you verified this with real lambdas?

I verified this with AWS's Docker based Lambda environment.

@bizob2828 bizob2828 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We talked, I'm ok with this code, if there is an issue we can always address later. especially since this isn't 100% wired up with the lambda extension and this feature isn't GA

@jsumners-nr
jsumners-nr merged commit 204c166 into newrelic:main Jul 27, 2026
56 of 57 checks passed
@github-project-automation github-project-automation Bot moved this from Needs PR Review to Done: Issues recently completed in Node.js Engineering Board Jul 27, 2026
@jsumners-nr
jsumners-nr deleted the issue-4126 branch July 27, 2026 17:21
@github-actions github-actions Bot mentioned this pull request Jul 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done: Issues recently completed

Development

Successfully merging this pull request may close these issues.

Enable collection of OTEL metrics from AWS Lambda

3 participants