Databases are an essential piece of modern web applications. For developers, they provide a method of persisting, manipulating, and retrieving information. You can connect to both SQL and NoSQL databases using Serverless Functions on Vercel. Let's examine best practices for using databases in a serverless environment.
If you need a higher level of abstraction on top of your database, consider using a Content Management System (CMS).
Serverless Functions are stateless and asynchronous. They are not designed for a persistent connection to a database. When a function is invoked, a connection to the database is opened. Upon completion, the connection is closed. Because traditional relational databases have low concurrent connection limits, we should try to maximize connection re-use.
Rather than opening a connection with every request, connection pooling allows us to designate a single "pooler" that keeps an active connection to the database. When a user invokes a Serverless Function that would read from the database, it will first search for an already available connection instead of creating a new connection. For example, you might use PgBouncer for connection pooling.
Caching improves response times and increases performance. With serverless, this translates to cost savings because you're paying for less usage. With Vercel, you have multiple options for caching responses from your database. For more information, see Caching.
Vercel deployments use dynamic IP addresses due to the dynamic nature of the platform. As a result, it is not possible to determine the deployment IP address or address range because the IP may change at any time as the deployment scales instances or across regions.
To ensure your Vercel deployment is able to access the external resource, you should allow connections from all IP addresses. Typically this can be achieved by entering an IP address of
While allowing connections from all IP addresses may be a concern, relying on IP allowlisting for security is generally ineffective and can lead to poor security practices.
To properly secure your database, we recommend using a randomly generated password, stored as an environment variable, at least 32 characters in length, and to rotate this password on a regular basis.
Any database can work in a serverless environment. However, certain providers are optimized for serverless, allowing them to guarantee data correctness at all times, across all cloud regions.
Choosing a database provider depends on the requirements for your application. Below, you'll find a list of database providers, as well as example applications integrated with Next.js to quickstart your development.
- MySQL (Heroku, DigitalOcean, etc)
- AWS DynamoDB
- AWS S3
- AWS Aurora
- Azure Blob
For more information on what to do next, we recommend the following articles: