<turbo-stream action="append" target="posts_list"><template>    <div class="postbit" id="297004" data-post-id="297004">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="stefanchrobot" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/stefanchrobot/120/7657_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  stefanchrobot
                    <span class="op-star" title="Thread Starter">
                      <img alt="OP" class="op-star-icon" src="/assets/thread-icons/thread-icon-thread-starter-df91e872.png" />
                    </span>
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>Yes, the application is up and running. The migration fails to connect to the DB, but the application boots right after that with no issues and functions properly.</p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="297004" data-batch-url="/posts/batch_likers">
                        0
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/database-connection-issues-during-deployment-on-digital-ocean-app-platform/54842/12">Post #11</a>
	                </div>
	            </div>
              <div id="likers-container-297004" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="297004"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #11"></div>
  </section>
</div>
    <div class="postbit" id="297006" data-post-id="297006">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="stefanchrobot" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/stefanchrobot/120/7657_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  stefanchrobot
                    <span class="op-star" title="Thread Starter">
                      <img alt="OP" class="op-star-icon" src="/assets/thread-icons/thread-icon-thread-starter-df91e872.png" />
                    </span>
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>I think I’m loosing any hope in resolving the issue. <a class="mention" href="/u/ericmj" rel="nofollow">@ericmj</a> sorry for tagging you, but I feel like I’m out of ideas.</p>
<h3><a name="p-297006-issue-1" class="anchor" href="#p-297006-issue-1" aria-label="Heading link" rel="nofollow"></a>Issue</h3>
<p>The migrations fail to run even though the application properly connects to the database later on.</p>
<h3><a name="p-297006-setup-2" class="anchor" href="#p-297006-setup-2" aria-label="Heading link" rel="nofollow"></a>Setup</h3>
<ul>
<li>Digital Ocean App Platform app on basic plan, single instance</li>
<li>Digital Ocean Managed PostgreSQL 15 with SSL, no VPC</li>
<li>PostgreSQL provides 22 connections</li>
<li>DB pool size for the app (<code>DATABASE_POOL_SIZE</code>) is 6</li>
<li>Elixir 1.15.4, Erlang 26.0.2 on Alpine 3.18.2 (same issue happened with OTP25)</li>
<li>Using Elixir releases</li>
<li>Dockerfile command: <code>CMD ["sh", "-c", "/app/bin/migrate &amp;&amp; /app/bin/server"]</code></li>
<li>The scripts are the usual <code>exec ./myapp eval MyApp.Release.migrate</code> and <code>exec ./myapp start</code></li>
<li><code>config/runtime.exs</code>:<pre data-code-wrap="elixir"><code class="lang-elixir">config :myapp, MyApp.Repo,
  url: System.get_env("DATABASE_URL"),
  maintenance_database: System.get_env("MAINTENANCE_DATABASE"),
  pool_size: System.get_env("DATABASE_POOL_SIZE") |&gt; String.to_integer(),
  log: System.get_env("LOG_LEVEL_ECTO") |&gt; String.to_existing_atom(),
  ssl: true,
  ssl_opts: [
    verify: :verify_peer,
    cacerts: [
      "DATABASE_CA_CERT"
      |&gt; System.get_env()
      |&gt; then(fn pem -&gt;
        [{_type, der, _info}] = :public_key.pem_decode(pem)
        der
      end)
    ]
  ]
</code></pre>
</li>
<li><code>release.ex</code>:<pre data-code-wrap="elixir"><code class="lang-elixir">defmodule MyApp.Release do
  require Logger

  @app :myapp

  def manual_connect do
    Application.ensure_all_started(:ssl)
    Application.ensure_all_started(:postgrex)

    database_url = System.get_env("DATABASE_URL")

    conn_opts =
      Ecto.Repo.Supervisor.parse_url(database_url) ++
        [
          ssl: true,
          ssl_opts: [
            verify: :verify_peer,
            cacerts: [
              "DATABASE_CA_CERT"
              |&gt; System.get_env()
              |&gt; then(fn pem -&gt;
                [{_type, der, _info}] = :public_key.pem_decode(pem)
                der
              end)
            ]
          ]
        ]

    safe_conn_opts = Keyword.put(conn_opts, :password, "*****")
    Logger.info("connection options: #{inspect(safe_conn_opts)}")

    {:ok, pid} = Postgrex.start_link(conn_opts)

    Logger.info("Querying...")

    %Postgrex.Result{rows: [[count]]} =
      Postgrex.query!(pid, "SELECT count(*) FROM accounts;", [])

    Logger.info("Found #{count} account(s).")
  end

  def query_with_repo() do
    Application.ensure_all_started(:ssl)

    for repo &lt;- repos() do
      {:ok, _, _} =
        Ecto.Migrator.with_repo(repo, fn repo -&gt;
          result = Ecto.Adapters.SQL.query(repo, "SELECT COUNT(*) FROM accounts;")
          IO.inspect(result, label: "query result")
        end)
    end
  end

  def migrate(opts \\ []) do
    try do
      if opts[:manual_connect] do
        manual_connect()
      end

      load_app()

      for repo &lt;- repos() do
        {:ok, _, _} = Ecto.Migrator.with_repo(repo, &amp;Ecto.Migrator.run(&amp;1, :up, all: true))
      end
    catch
      kind, value -&gt;
        Logger.warning("Migration failed: #{inspect(kind)}, #{inspect(value)}")
    end
  end

  def rollback(repo, version) do
    load_app()
    {:ok, _, _} = Ecto.Migrator.with_repo(repo, &amp;Ecto.Migrator.run(&amp;1, :down, to: version))
  end

  defp repos do
    Application.fetch_env!(@app, :ecto_repos)
  end

  defp load_app do
    Application.ensure_all_started(:ssl)
    Application.load(@app)
  end
end
</code></pre>
</li>
</ul>
<h3><a name="p-297006-expected-behavior-3" class="anchor" href="#p-297006-expected-behavior-3" aria-label="Heading link" rel="nofollow"></a>Expected behavior</h3>
<p>The migrations run successfully.</p>
<h3><a name="p-297006-actual-behavior-4" class="anchor" href="#p-297006-actual-behavior-4" aria-label="Heading link" rel="nofollow"></a>Actual behavior</h3>
<p>The migrations fail:</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">09:46:41.723 [error] Could not create schema migrations table. This error usually happens due to the following:

  * The database does not exist
  * The "schema_migrations" table, which Ecto uses for managing
    migrations, was defined by another library
  * There is a deadlock while migrating (such as using concurrent
    indexes with a migration_lock)

To fix the first issue, run "mix ecto.create" for the desired MIX_ENV.

To address the second, you can run "mix ecto.drop" followed by
"mix ecto.create", both for the desired MIX_ENV. Alternatively you may
configure Ecto to use another table and/or repository for managing
migrations:

    config :myapp, MyApp.Repo,
      migration_source: "some_other_table_for_schema_migrations",
      migration_repo: AnotherRepoForSchemaMigrations

The full error report is shown below.

09:46:42.108 [warning] Migration failed: :error, %DBConnection.ConnectionError{message: "connection not available and request was dropped from queue after 2402ms. This means requests are coming in and your connection pool cannot serve them fast enough. You can address this by:\n\n  1. Ensuring your database is available and that you can connect to it\n  2. Tracking down slow queries and making sure they are running fast enough\n  3. Increasing the pool_size (although this increases resource consumption)\n  4. Allowing requests to wait longer by increasing :queue_target and :queue_interval\n\nSee DBConnection.start_link/2 for more information\n", severity: :error, reason: :queue_timeout}
</code></pre>
<h3><a name="p-297006-notes-5" class="anchor" href="#p-297006-notes-5" aria-label="Heading link" rel="nofollow"></a>Notes</h3>
<ul>
<li>This used to work, but started failing ~5 months ago and I was not able to fix it since then</li>
<li>The database exists, since the app boots and works properly</li>
<li>I can reproduce the issue by running the task manually in the app console:<pre data-code-wrap="elixir"><code class="lang-elixir">~ $ ./bin/myapp eval 'MyApp.Release.migrate'
&lt; same error as above&gt;
</code></pre>
</li>
<li>Running <code>./bin/myapp eval 'MyApp.Release.manual_connect'</code> works 7 out of 8 times <img src="https://forum.elixirforum.com/images/emoji/apple/grimacing.png?v=15" title=":grimacing:" class="emoji" alt=":grimacing:" loading="lazy" width="20" height="20"> <img src="https://forum.elixirforum.com/images/emoji/apple/thinking.png?v=15" title=":thinking:" class="emoji" alt=":thinking:" loading="lazy" width="20" height="20"><pre data-code-wrap="elixir"><code class="lang-elixir">~ $ ./bin/myapp eval 'MyApp.Release.manual_connect'
18:10:55.695 [info] connection options: [password: "*****", hostname: "app-9b676190-67dd-41ee-&lt;truncated&gt;", scheme: "postgresql", username: "db", database: "db", port: 25060, sslmode: "require", ssl: true, ssl_opts: [verify: :verify_peer, cacerts: [&lt;&lt;48, 130, 4, 65, 48, 130, 2, 169, 160, 3, 2, 1, 2, 2, 20, 127, 134, 181, 234, 214, 51, 106, 230, 141, 57, 143, 45, 82, 18, 133, 113, 172, 225, 180, 168, 48, 13, 6, ...&gt;&gt;]]]
18:10:56.109 [info] Querying...
18:10:58.999 [info] Found 2 account(s).

~ $ ./bin/myapp eval 'MyApp.Release.manual_connect'
18:11:12.907 [info] connection options: [password: "*****", hostname: "app-9b676190-67dd-41ee-&lt;truncated&gt;", scheme: "postgresql", username: "db", database: "db", port: 25060, sslmode: "require", ssl: true, ssl_opts: [verify: :verify_peer, cacerts: [&lt;&lt;48, 130, 4, 65, 48, 130, 2, 169, 160, 3, 2, 1, 2, 2, 20, 127, 134, 181, 234, 214, 51, 106, 230, 141, 57, 143, 45, 82, 18, 133, 113, 172, 225, 180, 168, 48, 13, 6, ...&gt;&gt;]]]
18:11:13.393 [info] Querying...
** (DBConnection.ConnectionError) connection not available and request was dropped from queue after 2696ms. This means requests are coming in and your connection pool cannot serve them fast enough. You can address this by:

  1. Ensuring your database is available and that you can connect to it
  2. Tracking down slow queries and making sure they are running fast enough
  3. Increasing the pool_size (although this increases resource consumption)
  4. Allowing requests to wait longer by increasing :queue_target and :queue_interval

See DBConnection.start_link/2 for more information

    (postgrex 0.17.2) lib/postgrex.ex:375: Postgrex.query!/4
    (myapp 0.1.0) lib/myapp/release.ex:42: MyApp.Release.manual_connect/0
    nofile:1: (file)
    (stdlib 5.0.2) erl_eval.erl:750: :erl_eval.do_apply/7
    (elixir 1.15.4) lib/code.ex:543: Code.validated_eval_string/3
</code></pre>
</li>
<li>Note the initial time in the query above: is it connecting lazily?</li>
<li>Running <code>./bin/myapp eval 'MyApp.Release.migrate(manual_connect: true)</code> sometimes work, but not reliably<pre data-code-wrap="elixir"><code class="lang-elixir">~ $ ./bin/myapp eval 'MyApp.Release.migrate(manual_connect: true)'
18:51:50.298 [info] connection options: ...
18:51:50.709 [info] Querying...
18:51:53.494 [info] Found 2 account(s).
18:51:55.402 [info] Migrations already up
</code></pre>
</li>
<li>Doesn’t seem to be migration-related, since running <code>MyApp.Release.query_with_repo</code> blows up almost always <img src="https://forum.elixirforum.com/images/emoji/apple/grimacing.png?v=15" title=":grimacing:" class="emoji" alt=":grimacing:" loading="lazy" width="20" height="20"><pre data-code-wrap="elixir"><code class="lang-elixir">~ $ ./bin/myapp eval 'MyApp.Release.query_with_repo'
query result: {:error,
%DBConnection.ConnectionError{
  message: "connection not available and request was dropped from queue after 2518ms. This means requests are coming in and your connection pool cannot serve them fast enough. You can address this by:\n\n  1. Ensuring your database is available and that you can connect to it\n  2. Tracking down slow queries and making sure they are running fast enough\n  3. Increasing the pool_size (although this increases resource consumption)\n  4. Allowing requests to wait longer by increasing :queue_target and :queue_interval\n\nSee DBConnection.start_link/2 for more information\n",
  severity: :error,
  reason: :queue_timeout
}}
</code></pre>
</li>
<li>Occasionally the migrations work <img src="https://forum.elixirforum.com/images/emoji/apple/grimacing.png?v=15" title=":grimacing:" class="emoji" alt=":grimacing:" loading="lazy" width="20" height="20"></li>
</ul>
<h3><a name="p-297006-my-guesses-6" class="anchor" href="#p-297006-my-guesses-6" aria-label="Heading link" rel="nofollow"></a>My guesses</h3>
<ul>
<li>Slow SSL handshake causing connection issues? Maybe the supervision tree in the app magically heals the issue when the app boots?</li>
<li>Weird timing issue somewhere in the release tasks?</li>
</ul> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="297006" data-batch-url="/posts/batch_likers">
                        1
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/database-connection-issues-during-deployment-on-digital-ocean-app-platform/54842/13">Post #12</a>
	                </div>
	            </div>
              <div id="likers-container-297006" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="297006"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #12"></div>
  </section>
</div>
    <div class="postbit" id="297158" data-post-id="297158">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="benwilson512" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/benwilson512/120/1457_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  benwilson512
                  </h3>
		          </div>
						
			          <div class="user-title">
									<span>Author of Craft GraphQL APIs in Elixir with Absinthe</span>
			          </div>
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>Do you see these failed connections in the database logs?</p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="297158" data-batch-url="/posts/batch_likers">
                        0
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/database-connection-issues-during-deployment-on-digital-ocean-app-platform/54842/14">Post #13</a>
	                </div>
	            </div>
              <div id="likers-container-297158" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="297158"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #13"></div>
  </section>
</div>
    <div class="postbit" id="297410" data-post-id="297410">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="stefanchrobot" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/stefanchrobot/120/7657_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  stefanchrobot
                    <span class="op-star" title="Thread Starter">
                      <img alt="OP" class="op-star-icon" src="/assets/thread-icons/thread-icon-thread-starter-df91e872.png" />
                    </span>
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>I’ve spent more time debugging this issue. I’ve copied <code>db_connection</code> and <code>postgrex</code> from <code>deps/</code> into <code>local_deps/</code>, made them a path dependency and then sprinkled them with logging. Here’s what I got.</p>
<p>When the migrations fail, it looks like the connection checkout times-out before <code>postgrex</code> connects to the database:</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">~ $ ./bin/myapp eval MyApp.Release.migrate
22:03:09.885 [info] DBConnection.ConnectionPool.start_link
22:03:09.898 [info] DBConnection.register_as_pool
22:03:10.001 [info] DBConnection.ConnectionPool.init target 50 interval 1000
22:03:10.001 [info] DBConnection.ConnectionPool.start_poll
22:03:10.001 [info] DBConnection.ConnectionPool.start_idle
22:03:10.109 [info] &gt;&gt; Postgrex.connect
22:03:10.110 [info] &gt;&gt; Postgrex.connect
22:03:10.594 [info] DBConnection.prepare_execute: %Postgrex.Query{ref: nil, name: "", statement: ["CREATE TABLE ", "IF NOT EXISTS ", [34, "schema_migrations", 34], 32, 40, [[[], [[34, "version", 34], 32, "bigint", [[], []]], ", "], [34, "inserted_at", 34], 32, ["timestamp", "(0)"], [[], []]], [", ", "PRIMARY KEY (", [[], 34, "version", 34], ")"], 41, []], param_oids: nil, param_formats: nil, param_types: nil, columns: nil, result_oids: nil, result_formats: nil, result_types: nil, types: nil, cache: :reference}
22:03:10.594 [info] DBConnection.parse
22:03:10.702 [info] DBConnection.run
22:03:10.702 [info] DBConnection.checkout
22:03:10.702 [info] DBConnection.ConnectionPool.checkout
22:03:10.805 [info] DBConnection.ConnectionPool.handle_info checkout busy
22:03:11.098 [info] DBConnection.ConnectionPool.handle_info :timeout
22:03:11.098 [info] DBConnection.ConnectionPool.start_poll
22:03:11.098 [info] DBConnection.ConnectionPool.handle_info :timeout
22:03:11.098 [info] DBConnection.ConnectionPool.drop_idle
22:03:11.098 [info] DBConnection.ConnectionPool.start_idle
22:03:12.093 [info] DBConnection.ConnectionPool.handle_info :timeout
22:03:12.093 [info] DBConnection.ConnectionPool.start_poll
22:03:12.093 [info] DBConnection.ConnectionPool.timeout
22:03:12.195 [info] DBConnection.ConnectionPool.handle_info :timeout
22:03:12.195 [info] DBConnection.ConnectionPool.drop_idle
22:03:12.195 [info] DBConnection.ConnectionPool.start_idle
22:03:13.003 [info] DBConnection.ConnectionPool.handle_info :timeout
22:03:13.003 [info] DBConnection.ConnectionPool.start_poll
22:03:13.003 [info] DBConnection.ConnectionPool.timeout
22:03:13.092 [info] DBConnection.ConnectionPool.drop_slow {-576460738507, 100}
22:03:13.092 [info] DBConnection.ConnectionPool.drop
22:03:13.101 [info] DBConnection.checkout: error %DBConnection.ConnectionError{message: "connection not available and request was dropped from queue after 2196ms. This means requests are coming in and your connection pool cannot serve them fast enough. You can address this by:\n\n  1. Ensuring your database is available and that you can connect to it\n  2. Tracking down slow queries and making sure they are running fast enough\n  3. Increasing the pool_size (although this increases resource consumption)\n  4. Allowing requests to wait longer by increasing :queue_target and :queue_interval\n\nSee DBConnection.start_link/2 for more information\n", severity: :error, reason: :queue_timeout}
22:03:13.199 [info] DBConnection.ConnectionPool.handle_info :timeout
22:03:13.199 [info] DBConnection.ConnectionPool.drop_idle
22:03:13.199 [info] DBConnection.ConnectionPool.start_idle
</code></pre>
<p>In the happy scenario, the connection seems to be made on time:</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">~ $ ./bin/myapp eval MyApp.Release.migrate
21:38:12.709 [info] DBConnection.ConnectionPool.start_link
21:38:12.793 [info] DBConnection.register_as_pool
21:38:12.891 [info] DBConnection.ConnectionPool.init target 50 interval 1000
21:38:12.891 [info] DBConnection.ConnectionPool.start_poll
21:38:12.891 [info] DBConnection.ConnectionPool.start_idle
21:38:12.997 [info] &gt;&gt; Postgrex.connect
21:38:12.999 [info] &gt;&gt; Postgrex.connect
21:38:13.699 [info] DBConnection.prepare_execute: %Postgrex.Query{ref: nil, name: "", statement: ["CREATE TABLE ", "IF NOT EXISTS ", [34, "schema_migrations", 34], 32, 40, [[[], [[34, "version", 34], 32, "bigint", [[], []]], ", "], [34, "inserted_at", 34], 32, ["timestamp", "(0)"], [[], []]], [", ", "PRIMARY KEY (", [[], 34, "version", 34], ")"], 41, []], param_oids: nil, param_formats: nil, param_types: nil, columns: nil, result_oids: nil, result_formats: nil, result_types: nil, types: nil, cache: :reference}
21:38:13.699 [info] DBConnection.parse
21:38:14.001 [info] DBConnection.ConnectionPool.handle_info :timeout
21:38:14.001 [info] DBConnection.ConnectionPool.start_poll
21:38:14.001 [info] DBConnection.ConnectionPool.handle_info :timeout
21:38:14.001 [info] DBConnection.ConnectionPool.drop_idle
21:38:14.001 [info] DBConnection.ConnectionPool.start_idle
21:38:14.095 [info] DBConnection.run
21:38:14.095 [info] DBConnection.checkout
21:38:14.095 [info] DBConnection.ConnectionPool.checkout
21:38:14.202 [info] DBConnection.ConnectionPool.handle_info checkout busy
21:38:14.893 [info] DBConnection.ConnectionPool.handle_info :timeout
21:38:14.893 [info] DBConnection.ConnectionPool.start_poll
21:38:15.013 [info] DBConnection.ConnectionPool.handle_info :timeout
21:38:15.013 [info] DBConnection.ConnectionPool.drop_idle
21:38:15.013 [info] DBConnection.ConnectionPool.start_idle
21:38:15.890 [info] DBConnection.ConnectionPool.handle_info :timeout
21:38:15.890 [info] DBConnection.ConnectionPool.start_poll
21:38:15.890 [info] DBConnection.ConnectionPool.timeout
21:38:16.087 [info] DBConnection.ConnectionPool.handle_info :timeout
21:38:16.087 [info] DBConnection.ConnectionPool.drop_idle
21:38:16.087 [info] DBConnection.ConnectionPool.start_idle
21:38:16.095 [info] &lt;&lt; Postgrex.connect
21:38:16.095 [info] &lt;&lt; Postgrex.connect
21:38:16.197 [info] Postgrex connect: {:ok, %Postgrex.Protocol{sock: {:ssl, {:sslsocket, {:gen_tcp, #Port&lt;0.6&gt;, :tls_connection, :undefined}, [#PID&lt;0.179.0&gt;, #PID&lt;0.177.0&gt;]}}, connection_id: 2191998, connection_key: -613615798, peer: {{209, 38, 218, 180}, 25060}, types: {Postgrex.DefaultTypes, #Reference&lt;0.822817904.78249985.212280&gt;}, null: nil, timeout: 15000, ping_timeout: 15000, parameters: #Reference&lt;0.822817904.78118913.212392&gt;, queries: #Reference&lt;0.822817904.78249985.212386&gt;, postgres: :idle, transactions: :naive, buffer: :active_once, disconnect_on_error_codes: [], scram: nil}}
21:38:16.197 [info] Postgrex connect: {:ok, %Postgrex.Protocol{sock: {:ssl, {:sslsocket, {:gen_tcp, #Port&lt;0.5&gt;, :tls_connection, :undefined}, [#PID&lt;0.178.0&gt;, #PID&lt;0.176.0&gt;]}}, connection_id: 2191999, connection_key: -574140242, peer: {{209, 38, 218, 180}, 25060}, types: {Postgrex.DefaultTypes, #Reference&lt;0.822817904.78249985.212280&gt;}, null: nil, timeout: 15000, ping_timeout: 15000, parameters: #Reference&lt;0.822817904.78118913.212393&gt;, queries: #Reference&lt;0.822817904.78249985.212382&gt;, postgres: :idle, transactions: :naive, buffer: :active_once, disconnect_on_error_codes: [], scram: nil}}
21:38:16.197 [info] DBConnection.ConnectionPool.handle_info :ets-transfer
21:38:16.197 [info] DBConnection.ConnectionPool.handle_checkin
21:38:16.197 [info] DBConnection.ConnectionPool.dequeue
21:38:16.197 [info] DBConnection.ConnectionPool.dequeue_fast
21:38:16.197 [info] DBConnection.ConnectionPool.go
21:38:16.197 [info] DBConnection.ConnectionPool.handle_info :ets-transfer
21:38:16.197 [info] DBConnection.ConnectionPool.handle_checkin
21:38:16.197 [info] DBConnection.ConnectionPool.dequeue
21:38:16.197 [info] DBConnection.ConnectionPool.dequeue_fast
21:38:16.197 [info] DBConnection.checkout: OK
...
21:38:16.786 [info] Migrations already up
</code></pre>
<p>Note that it still takes over 3 seconds to establish a connection (that’s a lot, ain’t it?).</p>
<p>My thoughts on this:</p>
<ul>
<li>It looks like the DB connection is established asynchronously. In case it takes a lot of time, the queries will be dropped instead of blocking until a connection is established.</li>
<li><code>postgrex</code> has a connect timeout - it’s 5 seconds by default, so it doesn’t come into play here.</li>
<li>Not sure why it takes so much time to connect to the DB. Maybe this is related to SSL and the handshake?</li>
<li>Not sure why the app boots properly. Maybe it’s because the migrations only have a pool of 2 connections, whereas the app is configured to use 6. Do the migrations just run out of connections because they are still connecting?</li>
<li>Bumping <code>:queue_target</code> and <code>:queue_interval</code> to some high values makes the problem go away reliably.</li>
</ul>
<p>Since I’ve spent significant time on this, I hope to turn this into some sort of an improvement (updating docs, updating the error message, filing an issue in one of the packages, etc.), but I first need to understand what the right solution is. Bumping the queueing params? Addressing slow connection times? Something else?</p>
<p>Looking forward to your thoughts on this! <a class="mention" href="/u/dimitarvp" rel="nofollow">@dimitarvp</a> <a class="mention" href="/u/benwilson512" rel="nofollow">@benwilson512</a> <a class="mention" href="/u/ericmj" rel="nofollow">@ericmj</a> <a class="mention" href="/u/josevalim" rel="nofollow">@josevalim</a> and basically anyone who has time and insight on this.</p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="297410" data-batch-url="/posts/batch_likers">
                        1
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/database-connection-issues-during-deployment-on-digital-ocean-app-platform/54842/15">Post #14</a>
	                </div>
	            </div>
              <div id="likers-container-297410" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="297410"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #14"></div>
  </section>
</div>
    <div class="postbit" id="297414" data-post-id="297414">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="dimitarvp" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/dimitarvp/120/38664_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  dimitarvp
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>I am definitely biased in favor of increasing the values of <code>:queue_target</code> and <code>:queue_interval</code> because I had similar (emphasis: definitely NOT identical to your) problems in a few hobby projects where I relied on slow and public 3rd party APIs. I was stupid enough to try and pre-populate a <code>Finch</code> HTTP pool with 20 connections and until they all got initialized the DB connections failed in a similar manner to yours.</p>
<p>In those cases bumping the above two parameters eliminated the problem (though I also fixed my apps to do less stupid things as well <img src="https://forum.elixirforum.com/uploads/default/original/2X/6/6c3193d1dd46244da3c8c6f719c9f5e2abdd5ae8.gif?v=15" title=":003:" class="emoji emoji-custom" alt=":003:" loading="lazy" width="20" height="20">).</p>
<p>I am not as well versed as the core library maintainers but naively I’d say just keep those two parameters bumped and add telemetry. Though definitely make sure to analyze / monitor impact in the rest of the operation of the app; IMO bumping those parameters might mask problems with lower-performing code in other places in your app. I think it’s worth the small risk though.</p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="297414" data-batch-url="/posts/batch_likers">
                        1
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/database-connection-issues-during-deployment-on-digital-ocean-app-platform/54842/16">Post #15</a>
	                </div>
	            </div>
              <div id="likers-container-297414" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="297414"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #15"></div>
  </section>
</div>
    <div class="postbit" id="297461" data-post-id="297461">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="benwilson512" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/benwilson512/120/1457_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  benwilson512
                  </h3>
		          </div>
						
			          <div class="user-title">
									<span>Author of Craft GraphQL APIs in Elixir with Absinthe</span>
			          </div>
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p><a class="mention" href="/u/stefanchrobot" rel="nofollow">@stefanchrobot</a> really nice job debugging. One thing that may help here is instead of running your migrations as an <code>eval</code> task, put the migrator in your supervision tree via <a href="https://hexdocs.pm/ecto_sql/Ecto.Migrator.html#module-example-running-migrations-on-application-startup" class="inline-onebox" rel="nofollow">Ecto.Migrator — Ecto SQL v3.14.0</a>. This way it isn’t competing with other activity in your application, and it will also block application start until the migrations can run.</p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="297461" data-batch-url="/posts/batch_likers">
                        3
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/database-connection-issues-during-deployment-on-digital-ocean-app-platform/54842/17">Post #16</a>
	                </div>
	            </div>
              <div id="likers-container-297461" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="297461"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-most-liked cat-most-liked" title="One of the top 3 liked posts in this thread!"></div>
  </section>
</div>
    <div class="postbit" id="297465" data-post-id="297465">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="stefanchrobot" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/stefanchrobot/120/7657_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  stefanchrobot
                    <span class="op-star" title="Thread Starter">
                      <img alt="OP" class="op-star-icon" src="/assets/thread-icons/thread-icon-thread-starter-df91e872.png" />
                    </span>
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p><a class="mention" href="/u/dimitarvp" rel="nofollow">@dimitarvp</a> I’ll make the parameters configurable via ENV and bump it for now. That sounds like the best short-term solution. But I am quite worried that it might hide some errors. Luckily, this is not a mission critical app.</p>
<p><a class="mention" href="/u/benwilson512" rel="nofollow">@benwilson512</a> Thanks! First time seeing this approach, but it looks really interesting.</p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="297465" data-batch-url="/posts/batch_likers">
                        1
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/database-connection-issues-during-deployment-on-digital-ocean-app-platform/54842/18">Post #17</a>
	                </div>
	            </div>
              <div id="likers-container-297465" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="297465"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #17"></div>
  </section>
</div>
    <div class="postbit" id="297468" data-post-id="297468">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="benwilson512" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/benwilson512/120/1457_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  benwilson512
                  </h3>
		          </div>
						
			          <div class="user-title">
									<span>Author of Craft GraphQL APIs in Elixir with Absinthe</span>
			          </div>
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>Yeah we’ve been doing this for a long time since it synergizes really well with the K8s liveliness probes and readiness probes. Basically what we have is two endpoints <code>/alive</code> and <code>/ready</code>. <code>/alive</code> unconditionally returns <code>true</code> but <code>/ready</code> looks like this:</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">  def ready(conn, _params) do
    if Application.get_env(:myapp, :ready) do
      json(conn, %{ready: true})
    else
      send_resp(conn, 503, "")
    end
  end
</code></pre>
<p>Then our supervision tree looks like:</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">Phoenix Endpoint, #( this has `/alive` 200, but `/ready` is 503 still.)
DB Migrator,
Repo,
...Other Children,
MyApp.DeploymentNotifier, # this is just a one shot genserver that sets the env variable used in `/ready`
</code></pre>
<p>K8s has two different timeouts for pods. The first is about whether it’s alive at all, and the second is whether it is ready. It also only hooks up nodes to the load balancer that are <code>/ready</code>. This is K8s specific but this paradigm is found in other deployment structures as well. Basically it just ensures your app has time to initialize anything it needs before getting traffic, while still getting <em>some</em> indication from the app that it is alive and starting to boot.</p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="297468" data-batch-url="/posts/batch_likers">
                        2
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/database-connection-issues-during-deployment-on-digital-ocean-app-platform/54842/19">Post #18</a>
	                </div>
	            </div>
              <div id="likers-container-297468" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="297468"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-most-liked cat-most-liked" title="One of the top 3 liked posts in this thread!"></div>
  </section>
</div>
    <div class="postbit" id="305034" data-post-id="305034">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="samrat" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/samrat/120/32253_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  samrat
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>I am experiencing the same issue, also with a managed DigitalOcean Postgres instance.</p>
<p>I’m fairly new to Elixir. Has there been a fix for this? Where can I bump up <code>:queue_target</code> and <code>:queue_interval</code>? The values seem part of DBConnection and I can’t tell where in the Ecto.Repo config to change this(if that is where it needs to be specified).</p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="305034" data-batch-url="/posts/batch_likers">
                        0
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/database-connection-issues-during-deployment-on-digital-ocean-app-platform/54842/20">Post #19</a>
	                </div>
	            </div>
              <div id="likers-container-305034" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="305034"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #19"></div>
  </section>
</div>
    <div class="postbit" id="305035" data-post-id="305035">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="dimitarvp" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/dimitarvp/120/38664_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  dimitarvp
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<aside class="quote no-group" data-username="samrat" data-post="20" data-topic="54842">
<div class="title">
<div class="quote-controls"></div>
<img alt="" width="24" height="24" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/samrat/48/32253_2.png" class="avatar"> samrat:</div>
<blockquote>
<p>Where can I bump up <code>:queue_target</code> and <code>:queue_interval</code>? The values seem part of DBConnection and I can’t tell where in the Ecto.Repo config to change this(if that is where it needs to be specified).</p>
</blockquote>
</aside>
<p>Just in your <code>Repo</code> config in <code>config/config.exs</code> or <code>config/{dev,test,prod}.exs</code>. Or <code>config/runtime.exs</code>.</p>
<p>Here is an example: <a href="https://forum.elixirforum.com/t/ecto-query-timeout/27946/6" class="inline-onebox" rel="nofollow">Ecto Query Timeout - will this configuration suffice? - #6 by dimitarvp</a></p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="305035" data-batch-url="/posts/batch_likers">
                        1
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/database-connection-issues-during-deployment-on-digital-ocean-app-platform/54842/21">Post #20</a>
	                </div>
	            </div>
              <div id="likers-container-305035" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="305035"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-last-post cat-last-post" title="Last post!"></div>
  </section>
</div>
</template></turbo-stream><turbo-stream action="replace" target="load-more-container"><template><div id="load-more-container" class="load-more-container">
    <span class="all-loaded">— All posts loaded —</span>
</div></template></turbo-stream>