Postgres Connection Limit Exceeded in Next.js App Using Effect and SqlClient

Has anyone seen this error with the SqlClient - it will happen after some time testing (the entire backend is Effect driven) my nextjs 14 app:

SqlError: PgClient: Failed to connect

--- The SqlError that is logged to my Nextjs server:
error: sorry, too many clients already

--- And here is the Postgres log I can see:
2025-01-23 21:41:40.670 UTC [485] FATAL:  sorry, too many clients already
2025-01-23 21:41:40.751 UTC [486] FATAL:  sorry, too many clients already
... about 10 times in total <~~~

---

This is my database layer which I provide to each repository in my runtime:
import { PgClient } from "@effect/sql-pg";
export const PgLive = PgClient.layer({
  url: Redacted.make(env.DATABASE_URL),
});

export const DrizzleLive = PgDrizzle.layer.pipe(Layer.provide(PgLive));
export const DatabaseLive = Layer.mergeAll(PgLive, DrizzleLive);


And here is how I provide it to the runtime:

 export const runtime = ManagedRuntime.make(Layer.mergeAll(
  ...Other layers
  InviteRepositoryService.Default.pipe(
    Layer.provideMerge(DatabaseLive)
  )
);

I then do the following at the edge of my application: 
runtime.runPromise( ... my Effect )


---

The effect versions I am using:
"effect": "3.12.7",
"@effect/sql": "0.25.2",
"@effect/sql-drizzle": "0.20.2",
"@effect/sql-pg": "0.22.2",
// And drizzle:
"drizzle-orm": "^0.32.1", <~ LTS is 0.38 BUT I didn';t have this issue when I was using drizzle without Effect.


----

Question:
- Am I meant to teardown the connection when the runtime is finished executing the promise? I imagine what's happening is there is no connection pooling & the connections aren't closing 🤔
Was this page helpful?