Dwight Watson

Dwight Watson

A blog about Laravel & Rails.

Using Laravel with PlanetScale PgBouncer

I’ve been using PlanetScale Postgres with Laravel Cloud for a little while now, but occasionally run into issues where the number of connections to the database were exhausted: FATAL: remaining connection slots are reserved for roles with the SUPERUSER attribute. Luckily, PlanetScale gives you PgBouncer out of the box to pool your connections.

Laravel recently added suport for pooled Postgres connections and it only requires a minor adjustment to your database config. You need to add the pooled and direct options to your pgsql config.

'pgsql' => [
    'driver' => 'pgsql',
    // ...
    'pooled' => env('DB_POOLED', false),
    'direct' => array_filter([
        'host' => env('DB_DIRECT_HOST'),
        'port' => env('DB_DIRECT_PORT'),
        'username' => env('DB_DIRECT_USERNAME'),
        'password' => env('DB_DIRECT_PASSWORD'),
        'sslmode' => env('DB_DIRECT_SSLMODE'),
    ]),
],

Shipping that change alone won’t do anything - you then need to opt-in. For PlanetScale it’s simply a matter of changing the port. You move the default connection to 6432 so it points to your PgBouncer instance, and DB_DIRECT_PORT=5432 so it points to the primary database instance.

DB_PORT=6432
DB_POOLED=true
DB_DIRECT_PORT=5432