2 years ago, I published a PHP solution on the blog for choosing the right server from a servers list, based on the available bandwidth configured: Asymmetric Load Balancing Server Solution.
The algorithm can be used in Load Balancing proxy servers, for CDNs as well as for any other needs where a balanced distribution of resources is required;
Recently I am working on a cache plugin written in PHP, developed for any kind of web pages (non CMS) as well as for Wordpress: page, object and database.
You must be wondering why I don’t choose a plugin that is already free?
Because most of them are too complex, and they have long lost their perspective on simplicity, utility and performance!
And when I came to the implementation of a solution for CDN, I remembered the php function published over 2 years ago … but after so long it seems that my brain has advanced more in the optimization segment, the old solution seemed to me “heavy”.. So after less than 5 minutes I realized that the method of choosing a server was still very good, but there was still room for optimization!
So, below is a new version for Asymmetric Load Balancing Server, much faster and even simpler!
<?php $config_cdn = [ 'cdn1.cdnserverxyz.com' => 10, 'cdn2.cdnserverxyz.com' => 30, 'cdn3.cdnserverxyz.com' => 60, ]; # server config as [hostname => number], where number is bandwidth or a load percentage; # 10,30,60 can be 1,3,6 or 100,300,600, it's all about keeping the ratio between numbers. /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ function getAsym_LB_ServerV2(&$config_cdn) { $server_rand = mt_rand(1, array_sum($config_cdn)); $segment_bandwidth = reset($config_cdn); foreach ($config_cdn as $server=>$bandwidth) { if ($server_rand <= $segment_bandwidth) { break; } $segment_bandwidth += $bandwidth; } return $server; } /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ echo getAsym_LB_ServerV2($config_cdn);
Execution speed tests performed in PHP 7.4.2 showed that the above version is 40% faster than the one published 2 years ago.
Conclusion: Software Optimization Never END!
Be First to Comment