<p>I have PHP application running as a Docker container based on Alpine Linux inside Kubernetes. Everything went well until I tried removing container with test database and replacing it with <a href="https://azure.microsoft.com/cs-cz/services/postgresql/" rel="nofollow noreferrer">Azure PostgreSQL</a>. This led to significant latency increase from under 250ms to above 1500ms.</p>

<p>According to profiler most time is spent in <a href="http://php.net/manual/en/pdo.construct.php" rel="nofollow noreferrer">PDO constructor</a> which is establishing connection to database. <strong>The SQL queries themselves, after connection was established, then run in about 20ms.</strong></p>

<ul>
<li><strong>I tried using IP instead of address and it was still slow.</strong></li>
<li>I tried connecting from container using psql and it was slow (see full command below) </li>
<li>I tried DNS resolution using <a href="https://pkgs.alpinelinux.org/package/edge/main/x86/bind-tools" rel="nofollow noreferrer">bind-tools</a> and it was fast. </li>
<li>Database runs in same region as Kubernetes nodes, tried even same resource group, different network settings and nothing helped.</li>
<li>I tried requiring/disabling SSL mode on both client and server</li>
<li>I tried repeatedly running 'select 1' inside an already established connection and it was fast (average 1.2ms, median 0.9ms) (see full query below)</li>
</ul>

<p>What can cause such a latency? 
How can I further debug/investigate this issue?</p>

<hr>

<p>psql command used to try connection:</p>

<pre><code>psql "sslmode=disable host=host dbname=postgres user=user@host.postgres.database.azure.com password=password" -c "select 1"
</code></pre>

<hr>

<p>Query speed</p>

<pre><code>\timing 
SELECT;
\watch 1
</code></pre>

<p>As far as I can tell it is caused by Azure specific authentication on top of PostgreSQL. Unfortunately Azure support was not able to help from their side.</p>

<p>Using connection pool (<a href="https://pgbouncer.github.io/" rel="nofollow noreferrer">PgBouncer</a>) solves this problem. It is another piece of infrastructure we have to maintain (docker file, config/secret management, etc.), which we hoped to outsource to cloud provider.</p>
