- Регистрация
- 1 Мар 2015
- Сообщения
- 1,481
- Баллы
- 155
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.? This article is an English translation of the original French version available here:
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();
}
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
}
}
This code:
- sends all requests in parallel
- processes each response as soon as it’s complete
- significantly reduces total execution time
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
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 .
What About You?
Have you already used stream() in your Symfony projects?
Share your feedback or tips with me on — I’d love to chat!