Treblle / treblle-laravel

The official Treblle SDK for Laravel. Seamlessly integrate Treblle to manage communication with your dashboard, send errors, and secure sensitive data.
https://www.treblle.com/
MIT License
129 stars 24 forks source link

feat: Treblle Middleware works with zero latency now #77

Closed bhushan closed 1 year ago

bhushan commented 1 year ago

Problem:

We wanted to have as much as low latency we could for Treblle data collection APIs on the SDK level.

Solution:

This PR uses pcntl_fork extension, which is already part of almost all the PHP installations.

Had look at the alternatives like AMPHP, Spatie Fork and even looked into Laravel Octane code. alternatives where nice but they had there own requirements.

Spatie Fork package looked nice though, but we wont be using full package functionalities so didnt make sense to add one more dependency, when we can walk away with simple solution.

Details:

creates a fork of current process, meaning duplicates current process in layman term.

$pid = pcntl_fork();

all the below code runs in both the processes after fork, so we check if process is child or not with $pid == 0; child process has $pid always 0

major problem with pcntl_fork function is, parent process might need data from child process and because of which it doesnt kills the process properly and hence zombie processes are created. So we have to kill it manually so it doesnt becomes resource heavy.

private function killProcessWithId($pid): string|false
{
   return strtoupper(substr(PHP_OS, 0, 3)) === 'WIN'  ? exec("taskkill /F /T /PID $pid") : exec("kill -9 $pid");
}
JustSteveKing commented 1 year ago

I like the idea, but we need to check if this PHP extension is included by default across multiple versions - and document when it is not supported.

If we can start using parallel processes then this is fantastic! Maybe we should look at how we can build an abstract wrapper around this process so we can add it to the plain PHP and Symfony packages too?

Definitely worth an investigation, great job @bhushan πŸŽ‰πŸ”₯πŸ’¨

JustSteveKing commented 1 year ago

This is fantastic, but I want to make sure we do something that supports all of the PHP SDKs not just one.

I will work on this, then we can change this to implement the same πŸ™‚