No More Hustleporn: Connecting Databases When You're Using Serverless
Tweet by Lee Robinson
Head of DevRel ▲ @Vercel. Helping developers build a faster web. Teaching about web development, serverless, and React / Next.js.
1/ You want to use serverless. But you've heard about issues connecting to your database...
Here's how can you use databases in serverless environments like AWS Lambda, @vercel, and @Cloudflare.
2/ How does it work with a traditional Node.js server?
1. A request is made
2. The server opens a connection to the database
3. A SQL query is executed
4. The data is returned and the connection is closed
At a large scale, this can hit the maximum number of connections allowed.
3/ Enter connection pooling.
Rather than connecting on every request, connection pooling allows you to designate a single pooler that keeps an active connection to the database.
On new requests, the pooler finds an available connection rather than creating a new connection.
4/ Okay, so what about serverless?
Traditional relational databases were built for long-running compute instances, not the ephemeral nature of functions.
Serverless & edge functions are not designed for persistent connections to a database.
5/ With serverless, it's easier to exhaust available connections to your database because functions scale immediately and near infinitely when there are spikes in traffic.
Databases in serverless environments require different solutions than connection pooling.
6/ The solution for relational databases with serverless? HTTP!
By exposing an API on top of your database, you can execute SQL without managing connections. No drivers or plugins required.
7/ For example, here's a Next.js API route connecting to the AWS Aurora Data API and executing a SQL query.
Since it's just an API call, you can consider this "connectionless" – the Data API is managing connections to the database for you!
8/ Another solution is PostgREST.
It generates a REST API for your Postgres database automatically (and is used by companies like @supabase and @retool).
Modernizing a familiar approach to REST APIs, with PostgreSQL and Cloudflare Workers
9/ Databases for Serverless 🚀
◆ PostgreSQL: @supabase @HasuraHQ @AmazonRDS
◆ MySQL: @planetscaledata @AmazonRDS
◆ Key/Value: @dynamodb @upstash
◆ Others: @fauna @edgedatabase
These all can provide a database over HTTP!