> For the complete MongoDB documentation index, see www.mongodb.com/docs/llms.txt

<!--
Tab options on this page. Append to the .md URL to filter:
  ?tabs=<id,...>   select specific tabs (e.g. ?tabs=nodejs,shell)
  ?allTabs=true    include every tab
  (no param)       default: one tab per tabset

Available tabs:
  drivers: c, cpp, csharp, go, java-sync, kotlin-coroutine, kotlin-sync, nodejs, php, python, ruby, rust, scala
-->

# Manage Connections with AWS Lambda

## Best Practices

Use the following best practices to properly manage connections between [AWS Lambda](http://docs.aws.amazon.com/lambda/latest/dg/welcome.html) and Atlas:

- Define the client to the MongoDB server outside the [AWS Lambda handler function.](http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-handler.html)

  Don't define a new client object each time that you invoke your function. Doing so causes the driver to create a new database connection with each function call. This can be expensive and can result in your application exceeding database connection limits. For best performance, follow these guidelines:

  1. Create the client object once.

  2. Store the object so your function can reuse the client across function invocations.

  The [Connection Example](https://www.mongodb.com/docs/atlas/manage-connections-aws-lambda.md#std-label-lambda-aws-example) reuses existing database connections to speed up communication with the database and keep connection counts to the database at a reasonable level with respect to application traffic.

### Node.js

- If your handler takes a callback as its last argument, set the `callbackWaitsForEmptyEventLoop` property on the [AWS Lambda Context](http://docs.aws.amazon.com/lambda/latest/dg/nodejs-context.html#nodejs-prog-model-context-properties) object to **false**.

  ```js
  context.callbackWaitsForEmptyEventLoop = false;
  ```

  This allows a Lambda function to return its result to the caller without requiring that the MongoDB database connection be closed. Setting this property is not applicable for [async handlers.](https://docs.aws.amazon.com/lambda/latest/dg/nodejs-handler.html)

- If you have a Lambda function that connects to a sharded cluster with many shards, you might experience performance issues. For example, with a ten shard cluster, the driver connects to all thirty [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) instances by default. You can use the `srvMaxHosts` option in your connection string to set the maximum number of hosts that the driver connects to. To improve driver performance, set `srvMaxHosts=3`. For example:

  ```text
  mongodb+srv://<db_username>:<db_password>@<clusterName>.mongodb.net/?retryWrites=true&w=majority&srvMaxHosts=3
  ```

  To learn more, see [Connection Options.](https://www.mongodb.com/docs/drivers/node/current/fundamentals/connection/connection-options/)

* Restrict network access to your Atlas cluster.

  Connect to your Atlas cluster over private networking using a [Network Peering connection](https://www.mongodb.com/docs/atlas/security-vpc-peering.md#std-label-vpc-peering) between your Atlas cluster and your AWS (Amazon Web Services) Lambda function, or, alternatively, a [private endpoint](https://www.mongodb.com/docs/atlas/security-private-endpoint.md#std-label-private-endpoint-concepts), so that you can allow only private IP addresses from your [IP access list.](https://www.mongodb.com/docs/atlas/security/ip-access-list.md#std-label-add-to-access-list)

  If you don't use private networking, consider connecting to your Atlas cluster via a [NAT gateway](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-nat-gateway.html) with a mapped Elastic IP address. Otherwise, you must allow all IP addresses (0.0.0.0/0) to access your service cluster.

  **Warning:**

  Adding `0.0.0.0/0` to your [IP access list](https://www.mongodb.com/docs/atlas/security/ip-access-list.md#std-label-add-to-access-list) allows cluster access from anywhere in the public Internet. Ensure that you're using strong credentials for all database users when allowing access from anywhere.

**Note:**

If you add to a project access list any IPv4 `/0` CIDR, such as `0.0.0.0/0` or `10.0.0.0/0`, Atlas sends an alert email to all users directly granted a role to the project, or indirectly granted a role through team membership (if the team is granted a role to the project).

- Set [maxIdleTimeMS](https://www.mongodb.com/docs/manual/reference/connection-string/#mongodb-urioption-urioption.maxIdleTimeMS) to `60000` to automatically close your connections after 1 minute of idle time. Tuning your `maxIdleTimeMS` can help reduce the occurrence of timeout errors from your serverless functions.

* [Set Up Unified AWS Access](https://www.mongodb.com/docs/atlas/security/set-up-unified-aws-access.md#std-label-set-up-unified-aws-access) and use AWS (Amazon Web Services) IAM authentication where possible.

  You can connect to your Atlas clusters using AWS (Amazon Web Services) [IAM roles](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html) instead of hardcoding your credentials in Lambda. Hardcoded credentials are viewable by anyone who accesses your AWS Lambda environment, which can pose a security risk. With AWS (Amazon Web Services) IAM authentication, Atlas accesses AWS (Amazon Web Services) Lambda through an [assumed IAM role](https://docs.aws.amazon.com/IAM/latest/UserGuide/using-service-linked-roles.html), so you don't need credentials in your connection strings.

  Atlas supports AWS (Amazon Web Services) IAM authentication for clusters running MongoDB version 7.0 or higher. We strongly advise using AWS (Amazon Web Services) IAM authentication for Lambda connections if your cluster meets the requirements.

* The amount of memory allocated to a Lambda function defaults to 128 MB. You can configure the amount of memory allocated to a Lambda function, between 128 MB and 10,240 MB. Ensure you allocate enough memory. Increase the memory to increase the amount of virtual CPU available and improve MongoDB driver performance. To learn more, see [Memory and computing power](https://docs.aws.amazon.com/lambda/latest/operatorguide/computing-power.html).

* Set your [AWS\_STS\_REGIONAL\_ENDPOINTS](http://docs.aws.amazon.com/sdkref/latest/guide/feature-sts-regionalized-endpoints.html) and [AWS\_REGION](http://docs.aws.amazon.com/sdkref/latest/guide/feature-region.html) environment variables.

## Connection Example

### Node.js

### AWS (Amazon Web Services) IAM Authentication

```js
const { MongoClient } = require('mongodb');

// Get the URI for the cluster then set AWS_ACCESS_KEY_ID as the username in the
// URI and AWS_SECRET_ACCESS_KEY as the password, then set the appropriate auth
// options. Note that MongoClient now auto-connects so no need to store the connect()
// promise anywhere and reference it.
const client = new MongoClient(process.env.MONGODB_URI, {
  auth: {
    username: process.env.AWS_ACCESS_KEY_ID,
    password: process.env.AWS_SECRET_ACCESS_KEY
  },
  authSource: '$external',
  authMechanism: 'MONGODB-AWS'
});

module.exports.handler = async function () {
  const databases = await client.db('admin').command({ listDatabases: 1 });
  return {
    statusCode: 200,
    databases: databases
  };
};
```

### Other Authentication

```js
const { MongoClient } = require('mongodb');

// MongoClient now auto-connects so no need to store the connect()
// promise anywhere and reference it.
const client = new MongoClient(process.env.MONGODB_URI);

module.exports.handler = async function () {
  const databases = await client.db('admin').command({ listDatabases: 1 });
  return {
    statusCode: 200,
    databases: databases
  };
};
```
