Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 13 additions & 9 deletions lib/realtime/database.ex
Original file line number Diff line number Diff line change
Expand Up @@ -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.
"""
Expand All @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion mix.exs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
8 changes: 5 additions & 3 deletions test/realtime/database_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
Loading