Packages · Open source
Laravel Weighted Distribution
Hand things out in a fixed ratio, one at a time. It doesn't roll dice, so the ratio is exact after every pick and not only on average.
Sharing incoming work between teams that were each promised a share. Random selection is right on average and wrong this morning, and the team that came up short notices this morning.
Before
$teams = ['north' => 5, 'south' => 3, 'west' => 2];
// a fixed seed, so this prints the same ten picks on every run
$random = new Random\Randomizer(new Random\Engine\Mt19937(1));
$leads = [];
for ($lead = 1; $lead <= 10; $lead++) {
$roll = $random->getInt(1, 10);
foreach ($teams as $team => $weight) {
if (($roll -= $weight) <= 0) {
$leads[] = $team;
break;
}
}
}south west north west north north north north west north
north: 6
south: 1
west: 3That is the usual way, a weighted random pick. Over these ten leads, north got six, south got one and west got three. Here is the same split with the package.
After
use Keaton\WeightedDistribution\WeightedDistribution;
$teams = WeightedDistribution::make('sales-leads')
->target('north', 5)
->target('south', 3)
->target('west', 2);
$leads = [];
for ($lead = 1; $lead <= 10; $lead++) {
$leads[] = $teams->allocate()->target;
}north south north west north south north west south north
north: 5
south: 3
west: 2Exactly 5, 3 and 2, and each team's leads are spread through the run. You ask allocate() where the next item goes, and it keeps count for you. It stays exact however long it runs. After every pick, each target is less than one item away from its exact share. Over 1,000 leads the random pick is off by up to 21.5 leads, and the package is never off by more than 0.6.
What it does
- Route leads to teams or buyers by weight, with a daily cap on each. When one is full, the others share its leads by their own weights.
- Split traffic for an A/B test. The groups are the right size from the first visitor.
- Send exactly one order in every twenty to a manual review, with the reviews twenty orders apart.
- Spread API calls over two providers, with each provider's rate limit as its cap.
- Roll a change out to one request in ten, then turn the weights up.
- Save the reason for every pick. explain() returns it as a sentence.
- Run it on every queue worker. With the cache store, they hand out one sequence between them.