diff --git a/apps/docs/content/guides/database/connecting-to-postgres.mdx b/apps/docs/content/guides/database/connecting-to-postgres.mdx index b06d0b05a35..61e94e3ad14 100644 --- a/apps/docs/content/guides/database/connecting-to-postgres.mdx +++ b/apps/docs/content/guides/database/connecting-to-postgres.mdx @@ -98,6 +98,31 @@ postgresql://postgres:[YOUR-PASSWORD]@db.[PROJECT-REF].supabase.co:6543/postgres Get this string from the Supabase Dashboard by clicking [Connect](/dashboard/project/_?showConnect=true&method=transaction). +### Configure your client + +Your connection library keeps its own pool of connections, separate from the poolers Supabase runs. Configure it for the environment your code runs in. + +In a serverless function: + +1. Create the client once at module scope, not per request. +2. Set the pool to 1 connection. The client is shared by every invocation on that warm instance, so this caps the instance, not the request. +3. Turn off prepared statements, which [transaction mode](#pooler-transaction-mode) doesn't support. + +```ts lib/db.ts +import postgres from 'postgres' + +export const sql = postgres(process.env.DATABASE_URL, { + max: 1, + prepare: false, +}) +``` + +Library defaults assume a persistent backend, so they are too high for serverless. [Postgres.js](https://github.com/porsager/postgres) defaults to 10 connections. That is 10 connections for every warm instance of your function, and the number of warm instances isn't something you control. A few dozen instances is enough to exhaust the pool. + +Raise the pool above 1 only when you have evidence that concurrent invocations on one instance are queuing for the connection. + +For more on sizing an application-side pool, see the [Supavisor FAQ](/docs/guides/troubleshooting/supavisor-faq-YyP5tI). If you use Prisma, [Prisma troubleshooting](/docs/guides/database/prisma/prisma-troubleshooting) covers the equivalent `connection_limit` setting. + ### Data APIs and client libraries [#data-apis-and-client-libraries] The Data APIs let you interact with your database using REST or GraphQL requests. You can use these APIs to fetch and insert data from the frontend, as long as your tables have [Row Level Security](/docs/guides/database/postgres/row-level-security) (RLS) enabled and policies that allow the access. RLS with no policies denies every request.