• Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

Boosting Performance with Symfony HttpClient and Parallel Requests

Lomanu4 Оффлайн

Lomanu4

Команда форума
Администратор
Регистрация
1 Мар 2015
Сообщения
1,481
Баллы
155
? This article is an English translation of the original French version available here:

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

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();
}

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
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

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

.

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!


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх Снизу