www.mongodb.com Open in urlscan Pro
2600:9000:2490:1200:7:7859:3840:93a1  Public Scan

Submitted URL: https://www.mongodb.com/docs/atlas/manage-connections-aws-lambda/#std-label-lambda-aws-example
Effective URL: https://www.mongodb.com/docs/atlas/manage-connections-aws-lambda/
Submission: On August 01 via manual from US — Scanned from DE

Form analysis 2 forms found in the DOM

GET https://mongodb.com/docs/search/

<form role="search" method="GET" action="https://mongodb.com/docs/search/" class="css-dc0gsv">
  <div class="css-1q5aj3">
    <div class="css-36i4c2"><input type="text" placeholder="Search all documentation..." class="css-etrcff" value=""></div>
    <div class="css-1hc92ka">
      <div class="css-aef77t"><button role="button" type="button" class="css-14k7wrz"><span data-testid="selected-value" class="css-6k4l2y">All Documentation</span>
          <div class="css-109dpaz"><svg data-testid="icon" width="16" height="9" viewBox="0 0 16 9" fill="none" xmlns="http://www.w3.org/2000/svg" class="css-1yzkxhp">
              <path d="M1.06689 0.799988L8.00023 7.73332L14.9336 0.799988" stroke-linecap="round" stroke-linejoin="round" class="css-1tlq8q9"></path>
            </svg></div>
        </button>
        <div class="css-hn9qqo">
          <ul data-testid="options" role="listbox" class="css-ac9zo2">
            <li role="option" tabindex="0" class="css-11dtrvq">General Information</li>
            <li role="option" tabindex="0" class="css-11dtrvq">All Documentation</li>
            <li role="option" tabindex="0" class="css-11dtrvq">Realm Documentation</li>
            <li role="option" tabindex="0" class="css-11dtrvq">Developer Articles &amp; Topics</li>
            <li role="option" tabindex="0" class="css-11dtrvq">Community Forums</li>
            <li role="option" tabindex="0" class="css-11dtrvq">Blog</li>
            <li role="option" tabindex="0" class="css-11dtrvq">University</li>
          </ul>
        </div>
      </div><input type="hidden" id="q" name="q" value=""><input type="hidden" id="searchProperty" name="searchProperty" value="atlas-master">
      <div class="css-1myrko"><button type="submit" tabindex="0" class=" css-13l1z36" data-track="true"><img alt="search icon" src="https://webimages.mongodb.com/_com_assets/cms/krc3hljsdwdfd2w5d-web-actions-search.svg?auto=format%252Ccompress"
            class="css-r9fohf"></button></div>
    </div>
  </div>
</form>

GET https://mongodb.com/docs/search/

<form role="search" method="GET" action="https://mongodb.com/docs/search/" class="css-11a71ad">
  <div class="css-7590ag"><input type="text" placeholder="Search all documentation..." class="css-xrkki1" value=""></div>
  <div class="css-itzitu"><select class="select-overlay css-15v6p12" id="filter-select">
      <option value="General Information">General Information</option>
      <option value="All Documentation" selected="">All Documentation</option>
      <option value="Realm Documentation">Realm Documentation</option>
      <option value="Developer Articles &amp; Topics">Developer Articles &amp; Topics</option>
      <option value="Community Forums">Community Forums</option>
      <option value="Blog">Blog</option>
      <option value="University">University</option>
    </select><input type="hidden" id="q" name="q" value=""><input type="hidden" id="searchProperty" name="searchProperty" value="atlas-master">
    <div class="css-1myrko"><button type="submit" tabindex="0" class=" css-31biy7" data-track="true">Search</button></div>
  </div>
</form>

Text Content

All Documentation

 * General Information
 * All Documentation
 * Realm Documentation
 * Developer Articles & Topics
 * Community Forums
 * Blog
 * University


 * Products
   Atlas→
   
   Developer data platform
   
   --------------------------------------------------------------------------------
   
   Enterprise Advanced→
   
   Enterprise software and support
   
   --------------------------------------------------------------------------------
   
   Community Edition→
   
   Free software used by millions
   
   --------------------------------------------------------------------------------
   
    * Database→
    * Search→
    * Vector Search→
    * Stream Processing→
    * Data Lake (Preview)→
    * Charts→
    * Device Sync→
    * APIs, Triggers, Functions→
   
    * Enterprise Server→
    * Ops Manager→
    * Enterprise Kubernetes Operator→
   
    * Community Server→
    * Cloud Manager→
    * Community Kubernetes Operator→
   
   
   Tools→
   
   Build faster
   
   --------------------------------------------------------------------------------
   
    * Compass→
    * Shell→
    * VS Code Plugin→
    * Atlas CLI→
    * Database Connectors→
    * Cluster-to-Cluster Sync→
    * Mongoose ODM Support→
    * Relational Migrator→
   
   
 * Solutions
   
   By Industry
   
   
   
   --------------------------------------------------------------------------------
   
   By Use Case
   
   
   
   --------------------------------------------------------------------------------
   
    * Financial Services→
    * Telecom→
    * Healthcare→
    * Retail→
    * Public Sector→
    * Manufacturing→
    * All Industries→
   
    * Analytics→
    * Artificial Intelligence→
    * Internet of Things→
    * Mobile→
    * Payments→
    * Serverless Development→
    * All Use Cases→
   
   
   
   Developer Data Platform
   
   Innovate fast at scale with a unified developer experience
   
   Learn More
   
   --------------------------------------------------------------------------------
   
   White Papers & Presentations
   
   Webinars, white papers, datasheets and more
   
   View All
 * Resources
   Documentation→
   
   
   
   --------------------------------------------------------------------------------
   
    * Atlas→
    * Server→
    * Drivers→
   
    * Develop Applications→
    * Launch and Manage MongoDB→
    * View and Analyze→
    * Start with Guides→
   
   
   
   Community
   
   
   
   --------------------------------------------------------------------------------
   
   Education
   
   
   
   --------------------------------------------------------------------------------
   
    * Developer Center→
    * Events & Webinars→
    * Forums→
    * Champions→
    * Find a User Group→
   
    * University→
    * Certification→
    * Academia→
    * Intro to MongoDB Course→
    * Browse All Courses→
   
   
 * Company
   
   About
   
   
   
   --------------------------------------------------------------------------------
   
   Services
   
   
   
   --------------------------------------------------------------------------------
   
   Partnerships
   
   
   
   --------------------------------------------------------------------------------
   
    * Who We Are→
    * Customer Stories→
    * Blog→
    * Careers→
    * Pressroom→
    * Leadership→
    * Investors→
    * MongoDB Ventures→
   
    * Consulting→
    * Training→
    * Customer Support→
    * Customer Success→
   
    * Partner Ecosystem→
    * MongoDB for Startups→
   
   
 * Pricing

Sign In
Try Free

General InformationAll DocumentationRealm DocumentationDeveloper Articles &
TopicsCommunity ForumsBlogUniversity
Search
Docs Menu
   
   MongoDB Documentation
   
   --------------------------------------------------------------------------------
   
   Back to Launch & Manage MongoDB
 * MongoDB Atlas
 * Get Started with Atlas
 * Create and Connect to Database Deployments
 * Create a Database Deployment
 * Cloud Providers and Regions
 * Connect to a Database Deployment
 * Test Resilience
 * Manage Connections with AWS Lambda
 * Troubleshoot Connection Issues
 * Configure Security Features for Database Deployments
 * Configure Access to the Atlas UI
 * Migrate or Import Data
 * Interact with Your Data
 * Access Data with Atlas Data Lake
 * Set Up and Query Data Federation
 * Search Your Data with Atlas Search
 * Deploy Apps and Services
 * Back Up, Restore, and Archive Data
 * Manage Database Deployments
 * Monitor Your Database Deployments
 * Integrate Products and Services
 * Manage Billing
 * APIs
 * Atlas CLI
   upcoming
 * Reference
 * Get Help with Atlas
 * Production Notes
 * Release Notes

 * 



Docs Home → Launch & Manage MongoDB → MongoDB Atlas


MANAGE CONNECTIONS WITH AWS LAMBDA


On this page

 * Best Practices
 * Connection Example
 * AWS IAM Authentication
 * Other Authentication
 * AWS IAM Authentication
 * Other Authentication
 * AWS IAM Authentication
 * Other Authentication


BEST PRACTICES


Use the following best practices to properly manage connections between AWS
Lambda and Atlas:

 * Define the client to the MongoDB server outside the AWS Lambda handler
   function.
   
   Don't define a new MongoClient object each time 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. As an alternative, do the following:
   
   1. Create the MongoClient object once.
   
   2. Store the object so your function can reuse the MongoClient across
      function invocations.
   
   The Connection 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.


C#
Go
Java (Sync)
Node.js
Python
Ruby

 * If your handler takes a callback as its last argument, set the
   callbackWaitsForEmptyEventLoop property on the AWS Lambda Context object to
   false.
   
   context.callbackWaitsForEmptyEventLoop = false;
   
   Node.js
   
   
   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.

 * 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 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:
   
   mongodb+srv://<username>:<password>@<clusterName>.mongodb.net/?retryWrites=true&w=majority&srvMaxHosts=3
   
   
   
   To learn more, see Connection Options.




 * Restrict network access to your Atlas cluster.
   
   Connect to your Atlas cluster over private networking using a Network Peering
   connection between your Atlas cluster and your AWS Lambda function, or,
   alternatively, a private endpoint, so that you can allow only private IP
   addresses to your IP access list.
   
   If private networking is not an option, consider connecting to your Atlas
   cluster via a NAT gateway 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 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.

 * Set Up Unified AWS Access and use AWS IAM authentication where possible.
   
   You can connect to your Atlas clusters using AWS IAM roles 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 IAM authentication, Atlas accesses AWS Lambda through an
   assumed IAM role, so you don't need credentials in your connection strings.
   
   Atlas supports AWS IAM authentication for clusters running MongoDB version
   4.4 or higher. We strongly advise using AWS 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.


CONNECTION EXAMPLE



C#
Go
Java (Sync)
Node.js
Python
Ruby


AWS IAM AUTHENTICATION


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  };};

Node.js



OTHER AUTHENTICATION


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  };};

Node.js



←  Simulate Regional OutageTroubleshoot Connection Issues →
Select your language

Node.js

On this page

 * Best Practices
 * Connection Example
 * AWS IAM Authentication
 * Other Authentication
 * AWS IAM Authentication
 * Other Authentication
 * AWS IAM Authentication
 * Other Authentication

Share Feedback
© 2023 MongoDB, Inc.

About

 * Careers
 * Investor Relations
 * Legal Notices
 * Privacy Notices
 * Security Information
 * Trust Center

Support

 * Contact Us
 * Customer Portal
 * Atlas Status
 * Paid Support

Social

 * Github
 * Stack Overflow
 * LinkedIn
 * Youtube
 * Twitter
 * Twitch
 * Facebook

© 2023 MongoDB, Inc.




PRIVACY PREFERENCE CENTER

"Cookies" are small files that enable us to store information while you visit
one of our websites. When you visit any website, it may store or retrieve
information on your browser, mostly in the form of cookies. This information
might be about you, your preferences or your device and is mostly used to make
the site work as you expect it to. The information does not usually directly
identify you, but it can give you a more personalized web experience. Because we
respect your right to privacy, you can choose not to allow some types of
cookies, but essential cookies are always enabled. Click on the different
category headings to find out more and change our default settings. However,
blocking some types of cookies may impact your experience of the site and the
services we are able to offer.
MongoDB Privacy Policy
Allow All


MANAGE CONSENT PREFERENCES

STRICTLY NECESSARY COOKIES

Always Active

These cookies are necessary for the website to function and cannot be switched
off in our systems. They are usually only set in response to actions made by you
which amount to a request for services, such as setting your privacy
preferences, logging in or filling in forms. You can set your browser to block
or alert you about these cookies, but some parts of the site will not then work.
These cookies do not store any personally identifiable information.

PERFORMANCE COOKIES

Performance Cookies

These cookies allow us to count visits and traffic sources so we can measure and
improve the performance of our site. They help us to know which pages are the
most and least popular and see how visitors move around the site. All
information these cookies collect is aggregated and therefore anonymous. If you
do not allow these cookies we will not know when you have visited our site, and
will not be able to monitor its performance.

FUNCTIONAL COOKIES

Functional Cookies

These cookies enable the website to provide enhanced functionality and
personalisation. They may be set by us or by third party providers whose
services we have added to our pages. If you do not allow these cookies then some
or all of these services may not function properly.

TARGETING COOKIES

Targeting Cookies

These cookies may be set through our site by our advertising partners. They may
be used by those companies to build a profile of your interests and show you
relevant adverts on other sites. They do not store directly personal
information, but are based on uniquely identifying your browser and internet
device. If you do not allow these cookies, you will experience less targeted
advertising.

SOCIAL MEDIA COOKIES

Social Media Cookies

These cookies are set by a range of social media services that we have added to
the site to enable you to share our content with your friends and networks. They
are capable of tracking your browser across other sites and building up a
profile of your interests. This may impact the content and messages you see on
other websites you visit. If you do not allow these cookies you may not be able
to use or see these sharing tools.


BACK BUTTON PERFORMANCE COOKIES



Vendor Search Search Icon
Filter Icon

Clear
checkbox label label
Apply Cancel
Consent Leg.Interest
checkbox label label
checkbox label label
checkbox label label

Confirm My Choices


By clicking "Accept All Cookies", you agree to the storing of cookies on your
device to enhance site navigation, analyze site usage, and assist in our
marketing efforts. You can enable and disable optional cookies as desired. Read
our Privacy Policy. Read our Privacy Policy

Manage Cookies Accept All Cookies