Skip to main content

Introducing Persistent HTTP Connections in Unirest for PHP

· 3 min read

Previously, our PHP SDKs were initiating a new connection for each API call. Now, we have made HTTP connections persistent in Unirest for PHP SDK. Using persistent request allows all server requests to be made through one connection.

Details

Whenever a new HTTP connection is initiated from either the server or the client side, it has to follow some protocols, for seamless communication. These protocols provide multiple benefits, for example, TCP enables reliable communication between two endpoints.

But there is of course a downside to protocols. With every good protocol that provides reliability, there comes communication overhead. The number of handshakes we need to make at the start, and consequently while closing the connection can significantly lower the latency and congest the network being used. That is what a persistent connection helps us avoid:

  • It initiates the connection once
  • Makes the necessary handshakes with the server
  • Then uses the same connection for subsequent requests

Thereby avoiding any further handshakes till connection closure.

Previously, this behavior was missing in our PHP SDKs and we had to create a new connection for each API call.

What Has Changed?

Now, we are introducing persistent HTTP connections in our PHP SDKs. For example, if we create a client for our public Calculator API using PHP SDK and set some default values:

$client = new CalcClient();

$controller = $client->getSimpleCalculator();

$operation = OperationTypeEnum::MULTIPLY;
$collect['operation'] = $operation;

$collect['x'] = 2;

$collect['y'] = 3;

Then send a call to the getCalculate endpoint:

$controller->getCalculate($collect);

As this is the first call, a new connection will be created. Now, we make a second call with some different parameters like this:

$collect['x'] = 4;

$collect['y'] = 5;

$controller->getCalculate($collect);

This time, no new connection will be created. In fact, the connection created with the server for the last request will be reused, hence saving the network time of protocol handshakes.

If you want to close the connection after a request, pass the header Connection: close with your request. To demonstrate this behavior, let us take another API ConnectionAPI as an example:

$client = new ConnectionClient();

$controller = $client->getHeadersController();

$connectionHeader = 'close';

$controller->sendRequest($connectionHeader);

The above sendRequest() API call will send a header with key Connection and value close in the request. Most servers will also return the same header along with response. This will close the current connection, and a new connection will be created for the next API call.