Skip to content

Using NodeJS fetch occasionally throws "SocketError: other side closed" in AWS Lambda when sending request to cognito-idp to list public tokens

0

We're getting the jwks.json by sending request using NodeJS fetch to cognito-idp.../.well-known/jwks.json

As I understood, the connection is re-used within Lambda instance across Lambda calls and at some point it may become stale, causing cognito to drop the connection, which as a result causes the fetch to fail.

I have tried to reproduce the problem locally with no avail. What is the recommended approach when trying to get this information from Cognito from inside the Lambda?

Should we re-try the fetch if we see familiar error message? Or should we instead use some class from AWS SDK v3? Am I even on the right track with the error?

asked a year ago283 views

1 Answer
0

You're on the right track regarding the connection issue. When using Lambda to fetch the JWKS from Cognito, you may occasionally encounter "SocketError: other side closed" errors due to connection reuse across Lambda invocations.

The recommended approach is to implement a retry mechanism for these requests. Since the JWKS keys don't change frequently, it's also highly recommended to cache these keys to avoid fetching them for every token verification, which would reduce the number of requests to the Cognito endpoint and minimize the chances of encountering connection issues.

For implementing this in your Lambda function:

  1. Add retry logic to your fetch calls that handles the specific socket error
  2. Implement caching of the JWKS keys, either in-memory (for the duration of the Lambda container's lifetime) or using a more persistent cache like DynamoDB
  3. Set appropriate timeouts on your fetch requests

While you could use the AWS SDK v3, it doesn't provide specific advantages for this particular use case since you're just making an HTTP request to a well-known endpoint. The core issue is handling connection resets properly, which would need to be addressed regardless of the HTTP client you use.

This approach is similar to how Lambda functions need to handle connection issues with other services, where implementing proper backoff-and-retry logic is essential to protect against intermittent connection problems.
Sources
AWS Lambda function examples for Amazon Neptune - Amazon Neptune
Verifying JSON web tokens - Amazon Cognito
Getting started with outbound identity federation - AWS Identity and Access Management

answered a year ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.