apm-agent-nodejs icon indicating copy to clipboard operation
apm-agent-nodejs copied to clipboard

Lambda support appears to be broken in v2.x

Open watson opened this issue 7 years ago • 47 comments

See https://discuss.elastic.co/t/apm-server-transport-error-error-write-after-end/165484 for details

watson avatar Jan 24 '19 22:01 watson

@Qard let's timebox some investigation on this and see if we get to an easy fix.

alvarolobato avatar Feb 05 '19 16:02 alvarolobato

Related to https://github.com/elastic/apm-agent-nodejs/issues/798

alvarolobato avatar Feb 05 '19 16:02 alvarolobato

Has there been any progress on this issue? I can submit our workaround as a PR for this but I'm not sure thats its the best long term solution

davebond avatar Feb 28 '19 15:02 davebond

I was unable to reproduce it in my initial testing. I did do some restructuring recently to support async/await style though, which has not yet been released. That might impact it.

Qard avatar Feb 28 '19 18:02 Qard

Unfortunately it is still an issue, from my poking around the cause is:

  • Client connects transport to APM and functions for the first lambda execution
  • Lambda is "frozen", during which the socket is interrupted
  • On next lambda invoke, event loop kicks back in and transport throws an ECONNRESET
  • Client attempts to write transaction data to the socket which is now closed due to the error state, resulting in the write after end issue

Our workaround is to track this error state and ensure that the transport is open before sending any transactions: https://github.com/status200/apm-agent-nodejs/commit/629cd9fb1e8bbfd3b6089c42791bf58dcadfee5d

Though it seems like a larger restructure to track the lifecycle and state of the transport would be more appropriate as this could also be an issue for clients running long enough to encounter network hiccups.

davebond avatar Feb 28 '19 19:02 davebond

I'm able to reproduce the ECONNRESET, but the client just reconnects and seems to send the new transaction just fine. I'm not getting the write after end error at all.

Are you able to provide a code example that can reproduce the write after end?

Qard avatar Mar 02 '19 04:03 Qard

For what it is worth, I got it working by editing the code from the docs. I have node8.10 on Lambda.

What the docs show and caused "APM Server transport error: Error: write after end":

exports.handler = apm.lambda(function handler (payload, context, callback) {
  callback(null, `Hello, ${payload.name}!`)
})

What worked for me:

exports.handler = apm.lambda(async (payload, context, callback) => {
  callback(null, `Hello, ${payload.name}!`)
})

HuddleHouse avatar Mar 08 '19 19:03 HuddleHouse

Sorry for the delay, @HuddleHouse is correct, the example from the docs still produces the issue.

There are two methods I can see which stop this:

// Pass promise to lambda
exports.handler = apm.lambda(async (payload, context, callback) => {
  callback(null, `Hello, ${payload.name}!`)
})

// callbackWaitsForEmptyEventLoop
exports.handler = apm.lambda(function handler (payload, context, callback) {
  context.callbackWaitsForEmptyEventLoop = false;
  callback(null, `Hello, ${payload.name}!`)
})

Both of these depend on Lambda's handling of the event loop it seems and I wouldn't like to count on this behaviour staying consistent over time.

davebond avatar Mar 08 '19 20:03 davebond

I still get this error when using the latest apm in a lambda. I start apm like this:

exports.handler = apm.lambda(async (event, context, callback) => {
	...
	callback(null, `Successfully processed ${items} events`);
}

2019-04-15T10:48:16.268Z 4f47d833-61f4-4af4-b824-cf46e5d0880d APM Server transport error: Error: write after end at writeAfterEnd (/var/task/node_modules/readable-stream/lib/_stream_writable.js:257:12) at Client.Writable.write (/var/task/node_modules/readable-stream/lib/_stream_writable.js:301:21) at Client.sendTransaction (/var/task/node_modules/elastic-apm-http-client/index.js:276:15) at Instrumentation.addEndedTransaction (/var/task/node_modules/elastic-apm-node/lib/instrumentation/index.js:185:22) at Instrumentation.wrappedAddEndedTransaction [as addEndedTransaction] (/var/task/node_modules/elastic-apm-node/lib/instrumentation/async-hooks.js:53:34) at Transaction.end (/var/task/node_modules/elastic-apm-node/lib/instrumentation/transaction.js:218:32) at captureAndMakeCompleter (/var/task/node_modules/elastic-apm-node/lib/lambda.js:48:11) at wrappedLambdaCallback (/var/task/node_modules/elastic-apm-node/lib/lambda.js:60:20) at exports.handler.apm.lambda (/var/task/index.js:38:9) at at process._tickDomainCallback (internal/process/next_tick.js:228:7)

tallakh avatar Apr 15 '19 11:04 tallakh

Yes, it's still a known issue. It's proving to be complicated to fix. Basically, when Lambda freezes the VM it disconnects any sockets still in-use and, when the process wakes up again, it's unaware the sockets have been closed until after it tries to write to them. This is resulting in the write after end happening when the next message is sent to the apm-server.

Qard avatar Apr 15 '19 21:04 Qard

I've been thinking that we need a way to either force close the underlying TCP socket after each lambda function execution (though that would increase the function running-time overhead), or we should somehow ignore those errors when running in a lambda context (though that might hide some real errors).

We should probably also update the docs do suggest that you disable metrics when running in lambda as that will keep trying to reopen the TCP socket - and metrics inside a lambda doesn't make much sense anyway.

watson avatar Apr 15 '19 21:04 watson

Hi all, so.... current situation is - for everybody reading this issue (please correct me):

Do NOT upgrade/use elastic stack of version 7.x, because elastic-apm-nodejs of version 1.x is not supported with APM of version 7.x

If using elastic-apm-nodejs in AWS lambda, use elastic stack of version < 6.5.x and elastic-apm-node-js of version < 2.x

Martin

martinduris avatar Apr 20 '19 15:04 martinduris

Hi @watson,

We should probably also update the docs do suggest that you disable metrics when running in lambda as that will keep trying to reopen the TCP socket

We've tried disabling metrics by passing the metricsInterval config option but we still experience the issue. Do you have other suggestions we may try?

We're running server v7.0.0 with node client ^2.11.5.

Thank you so much for all the work here!

willbrazil avatar May 29 '19 10:05 willbrazil

@willbrazil Setting metricsInterval: 0 will only reduce the likelihood that this error appears, not completely eliminate it. As it stands currently, you might see this error when the VM is being resumed after having been suspended by AWS Lambda. Unfortunately, we can't detect when this happens. However, all data being sent afterward, while the VM is still running, should make it to the APM Server successfully.

If your lambda function is only called once every 20 minutes, this might mean nothing or only very little data get through. But if your lambda function is called several times a minute or more, 99+% of the collected data should get through as expected.

watson avatar May 29 '19 13:05 watson

Thank you for such a quick response @watson! Some of our lambdas are handling ~60tps.

We're reproduced in a more controlled environment where we sent a request every second and still experience the issue unfortunately. We'll keep digging here. I know this is a tricky one specially because it's hard to repro locally.

Thank you again for all the info!

willbrazil avatar May 29 '19 14:05 willbrazil

I did a bit of investigation, and found a couple of issues.

The stack trace in https://github.com/elastic/apm-agent-nodejs/issues/827#issuecomment-483208921 is due to the client being ended in the transport in response to the beforeExit event:

https://github.com/elastic/apm-nodejs-http-client/blob/7480d2e781a1dc378d348a7835d16265d108df12/index.js#L42

Lambda apparently relies on this for scheduling multiple (i.e. warm) Lambda invocations. After the first cold invocation the client is ended, and then subsequent invocations will trigger the stack trace after attempting to write to an ended stream.

Commenting that out, I encountered a second issue: intermittent 502 errors, with the response body of {"message": "Internal server error"}. It wasn't obvious where this was coming from (logs weren't helpful), but I eventually narrowed it down to invoking the Lambda callback function inside of agent.flush:

https://github.com/elastic/apm-agent-nodejs/blob/63a48c28deeb98184b96dd7221af3936163e9a72/lib/lambda.js#L51-L54

With some additional logging I could see that the flush was occurring after the next beforeExit. According to https://docs.aws.amazon.com/lambda/latest/dg/running-lambda-code.html:

Background processes or callbacks initiated by your Lambda function that did not complete when the function ended resume if AWS Lambda chooses to reuse the execution context. You should make sure any background processes or callbacks in your code are complete before the code exits.

I suppose that the Lambda runtime is implicitly calling the callback with an empty body. If that is indeed the case, the required Lambda Proxy payload (statusCode, body) will be missing, and likely cause the 502 error.

axw avatar Sep 09 '19 07:09 axw

Hi all,

Is there any progress on fixing this issue? Right now we are stuck on Elastic stack 6.5 and APM agent 1.14.5 and we would really like to use the latest releases.

Thanks.

tallakh avatar Oct 02 '19 08:10 tallakh

We ended up writing our own integration to get around this issue and will be sticking with it regardless of how this issue plays out.

I think the current design is a problem for lambda as:

  • Lambdas need to store APM messages between invocations and attempt to send them the next time the lambda is active, this may never happen and if it does may not be active long enough to communicate the message over HTTP
  • Lambdas would need to block from returning their response in order to guarantee that APM messages are delivered
  • It requires that there is a NAT connection available when operating inside a VPC which increases costs

Our solution:

  • Our own APM client logs messages to the console
  • Logs end up in cloudwatch
  • Cloudwatch triggers a lambda
  • Lambda sends regular log lines to elastic logs or converts APM messages from our format to elastic and sends to elastic APM

This makes APM message processing passive, isolated from the main system and does not impose networking requirements

The recently released new relic offering for lambda also takes this approach which has given us some more confidence in this decision. https://docs.newrelic.com/docs/serverless-function-monitoring/aws-lambda-monitoring/get-started/enable-new-relic-monitoring-aws-lambda

davebond avatar Oct 02 '19 17:10 davebond

We've actually discussed the cloudwatch logs approach for exactly the same reasons you mentioned. It just hasn't yet been prioritized.

Qard avatar Oct 02 '19 19:10 Qard

Thanks @davebond, that seems like a sensible approach. Is this something that is on the roadmap for the AWS lambda integration for APM @Qard?

tallakh avatar Oct 03 '19 14:10 tallakh