title: How to handle Postgres connection pooling in Vercel serverless functions? (“too many connections for role”)
body: <p>I have a small hobby web app built on this template: <a href="https://github.com/tomsoderlund/nextjs-pwa-graphql-sql-boilerplate" rel="nofollow noreferrer">https://github.com/tomsoderlund/nextjs-pwa-graphql-sql-boilerplate</a></p>
  <p>It uses ElephantSQL’s free tier (5 connections), runs on Zeit Now v2 serverless functions – and keeps running out of Postgres connections (“<strong>too many connections for role &quot;djsktctf&quot;</strong>”).</p>
  <p>I’m using the <code>death</code> NPM to close connections - this is in <code>/api/graphql/index.js</code>:</p>
  <pre><code>const { ApolloServer, gql } = require('apollo-server-micro')
  const { config } = require('../../config/config')
  
  // Postgres (pg)
  const { Pool } = require('pg')
  const onProcessDeath = require('death')
  const pool = new Pool({ connectionString: config.databaseUrl })
  let client
  
  const initDatabaseClient = async () =&gt; {
    if (!client) client = await pool.connect()
  }
  initDatabaseClient()
  
  onProcessDeath((signal, err) =&gt; {
    client &amp;&amp; client.release()
  })
  
  const typeDefs = gql`
    ${require('../../graphql/font/schema')}
  `
  
  const resolvers = {
    ...require('../../graphql/font/resolvers')(pool)
  }
  
  const server = new ApolloServer({
    typeDefs,
    resolvers,
    introspection: true,
    playground: true
  })
  
  module.exports = server.createHandler({ path: config.graphqlPath })
  </code></pre>
  <p>Then inside <code>resolvers</code> it looks like this:</p>
  <pre><code>module.exports = (pool) =&gt; ({
    Query: {
      async articles (parent, variables, context, info) {
        const sqlString = `SELECT * FROM article LIMIT 100;`
        const { rows } = await pool.query(sqlString)
        return rows
      }
  }
  </code></pre>
  <p>How can I improve this to avoid running out of connections?</p>
  <h2>Update</h2>
  <p>After getting the answer below, I updated my code with <code>client.end()</code> and NOT using a shared client:</p>
  <pre><code>// const results = await runDatabaseFunction(async (pool) =&gt; { ... })
  const runDatabaseFunction = async function (functionToRun) {
    // Connect db
    const client = await pool.connect()
    // Run function
    const results = await functionToRun(client)
    // Release db
    await client.end()
    await client.release()
    return results
  }
  </code></pre>