logoalt Hacker News

martinaldlast Thursday at 11:51 PM2 repliesview on HN

I feel like I'm on a different planet when I see this kind of comment.

What if you need to call multiple external APIs at once with complex json? Sure you can call them one after another, but if each take (say) 2s to return (not uncommon IME), then you are in real trouble with only one thread - even if it is just for one "request".

I guess I'm spoilt in .NET with Task.WhenAll which makes it trivial to do this kind of stuff.


Replies

theodorejblast Friday at 12:28 AM

This can be done with curl_multi_exec(), or with $client->getAsync() in Guzzle.

https://www.php.net/manual/en/function.curl-multi-exec.php

https://docs.guzzlephp.org/en/stable/quickstart.html#concurr...

show 1 reply
Gormolast Friday at 3:15 AM

> What if you need to call multiple external APIs at once with complex json?

A few years ago, I had a PHP project that had grown by accretion from taking a single complex input and triggering 2-3 external endpoints to eventually making calls to about 15 sequentially. Processing a single submission went from taking 5-10 seconds to over five minutes.

This was readily solved by moving to ReactPHP (https://reactphp.org/), which implements async via event loops. I was able to reduce the 15 sequential external API calls to four sequential loops (which was the minimum number due to path dependencies in the sequence of operations). That reduced the five minutes back to an average of 20-30 seconds for the complete process.

It wasn't using true multithreading, but in a situation where most of the time was just waiting for responses from remote servers, an event loop solution is usually more than sufficient.

show 2 replies