diff --git a/lib/realtime/database.ex b/lib/realtime/database.ex index 3a86a7479..81550b1be 100644 --- a/lib/realtime/database.ex +++ b/lib/realtime/database.ex @@ -87,9 +87,6 @@ defmodule Realtime.Database do @available_connection_factor 0.95 - defguardp can_connect?(available_connections, required_pool) - when required_pool * @available_connection_factor < available_connections - @doc """ Checks if the Tenant CDC extension information is properly configured and that we're able to query against the tenant database. """ @@ -110,12 +107,19 @@ defmodule Realtime.Database do "select (current_setting('max_connections')::int - count(*))::int from pg_stat_activity where application_name != 'realtime_connect'" case Postgrex.query(conn, query, []) do - {:ok, %{rows: [[available_connections]]}} - when can_connect?(available_connections, required_pool) -> - {:ok, conn} - - {:ok, _} -> - {:error, :tenant_db_too_many_connections} + {:ok, %{rows: [[available_connections]]}} -> + requirement = ceil(required_pool * @available_connection_factor) + + if requirement < available_connections do + {:ok, conn} + else + log_error( + "DatabaseLackOfConnections", + "Only #{available_connections} available connections. At least #{requirement} connections are required." + ) + + {:error, :tenant_db_too_many_connections} + end {:error, e} -> Process.exit(conn, :kill) diff --git a/mix.exs b/mix.exs index e5e7d53bb..c78cff459 100644 --- a/mix.exs +++ b/mix.exs @@ -4,7 +4,7 @@ defmodule Realtime.MixProject do def project do [ app: :realtime, - version: "2.55.1", + version: "2.55.2", elixir: "~> 1.17.3", elixirc_paths: elixirc_paths(Mix.env()), start_permanent: Mix.env() == :prod, diff --git a/test/realtime/database_test.exs b/test/realtime/database_test.exs index 54b85585a..320953d23 100644 --- a/test/realtime/database_test.exs +++ b/test/realtime/database_test.exs @@ -48,11 +48,13 @@ defmodule Realtime.DatabaseTest do # Connection limit for docker tenant db is 100 @tag db_pool: 50, - subs_pool_size: 50, - subcriber_pool_size: 50 + subs_pool_size: 21, + subcriber_pool_size: 33 test "restricts connection if tenant database cannot receive more connections based on tenant pool", %{tenant: tenant} do - assert {:error, :tenant_db_too_many_connections} = Database.check_tenant_connection(tenant) + assert capture_log(fn -> + assert {:error, :tenant_db_too_many_connections} = Database.check_tenant_connection(tenant) + end) =~ ~r/Only \d+ available connections\. At least 126 connections are required/ end end