The Handshake Tax

Your Magento integration might be slow because of a hidden network cost.

I once ran a product export that talked to a pricing API. One product worked fast. The full catalog took forever. My database was idle. The profiler showed the problem was the network.

The code created a new HTTP client inside a loop.

Before you send data via HTTPS, your machine does heavy work. It performs a TCP handshake to open a socket. Then it performs a TLS handshake to exchange certificates and negotiate keys. This takes several round trips.

If you do this once, the cost is low. If you do this inside a loop of 40,000 products, you pay that cost 40,000 times. The actual data is small. The setup is the expensive part.

PHP often feels like you should build a client and throw it away. This works for a single web request. It fails in long-running processes.

Avoid this pattern in cron jobs, console commands, or message queue consumers:

This code opens a new connection and runs the full handshake for every single product.

Guzzle keeps connections alive if you use the same client instance. Move the client outside your loop:

  • $client = new \GuzzleHttp\Client(['base_uri' => 'https://api.example.com']);
  • foreach ($products as $product) {
  • $client->post('/sync', [...]);
  • }

Now the socket and TLS session stay open. You handshake once and stream the rest. In Magento, inject a configured client through your constructor instead of creating it manually.

Failure to do this causes more than just latency. You can run out of outbound ports. Closed connections pile up in TIME_WAIT faster than your OS reclaims them. Your service will stop opening new sockets entirely.

Check your code for this mistake. Run this command in your terminal:

grep -rn "new .*Client(" app/code | grep -i http

Look for any new client creation sitting inside a loop. Move the client out of the loop. It is a one-line change that provides a massive speedup for large syncs.

Source: https://dev.to/iamrobindhiman/the-handshake-tax-reuse-your-http-client-in-magento-integrations-3kk7