DEV Community

Cover image for Boosting Performance with Symfony HttpClient and Parallel Requests
Victor
Victor

Posted on • Edited on

Boosting Performance with Symfony HttpClient and Parallel Requests

📝 This article is an English translation of the original French version available here: https://victor-prdh.com/blog/01-requete-asynchrone-symfony/

When developing a Symfony application that communicates with multiple APIs, it's tempting to send requests one after another. However, this approach can quickly become a bottleneck.

Fortunately, Symfony’s HttpClient component makes it easy to manage multiple parallel requests — without threads, promises, or workers.

In this article, I’ll show you how to take advantage of this feature to improve performance.


The Classic Problem: Sequential API Calls

Let’s take a simple example. You need to query 5 APIs to retrieve and merge data. Most developers would instinctively write something like this:

$results = [];

foreach ($urls as $url) {
    $response = $client->request('GET', $url);
    $results[] = $response->toArray();
}
Enter fullscreen mode Exit fullscreen mode

This code works, but it’s slow: each request waits for the previous one to complete before starting.


The Solution: stream() for Concurrent Requests

Symfony provides a more powerful API with the stream() method. It allows you to fire off all requests at once and process responses as soon as they’re ready — avoiding unnecessary blocking.

Here’s how:

$responses = [];

foreach ($urls as $url) {
    $responses[] = $client->request('GET', $url);
}

// Read responses as they come in
foreach ($client->stream($responses) as $response => $chunk) {
    if ($chunk->isLast()) {
        $result = $response->toArray();
        // Process the result
    }
}
Enter fullscreen mode Exit fullscreen mode

This code:

  • sends all requests in parallel
  • processes each response as soon as it’s complete
  • significantly reduces total execution time

Performance Gains

Gains depend on your target APIs, but in many cases, you can cut total response time by a factor of 2 to 10, especially when APIs take 300 to 500 ms to respond individually.


When to Use This Method

Use stream() whenever you have:

  • multiple independent API calls to make
  • simple response processing logic
  • slow or numerous third-party APIs

In Summary

Symfony HttpClient allows you to write simple, readable, and asynchronous code without adding unnecessary technical complexity.

The stream() method is a powerful tool to add to your toolbox for any API-driven Symfony project.


Go Further

To explore the full capabilities of HttpClient and stream(), check out the official Symfony documentation.


What About You?

Have you already used stream() in your Symfony projects?

Share your feedback or tips with me on LinkedIn — I’d love to chat!

Top comments (0)