Utopia Balancer
Choosing between endpoints: options with state, filters, and the First, Last, Random and RoundRobin algorithms.
This library is maintained by the Appwrite team.
Getting started
[]
= { = "https://github.com/appwrite/appwrite" }
A balancer picks one endpoint out of many: a worker for the next job, a region for the next request. You give it options, filters that rule out the options that cannot serve right now, and an algorithm that chooses among the rest. Options can be any type; Candidate is a ready-made one holding named values such as a hostname or a CPU load. This guide covers the common tasks.
Rotate between options
RoundRobin hands out each option in turn and starts over after the last. Start it at -1 to begin with the first option.
use ;
let mut balancer = new;
for host in
let mut picks = Vecnew;
for _ in 0..4
assert_eq!;
Skip options that cannot serve
Filters decide which options the algorithm may choose. An option must pass every filter. filtered lists all the options that pass, for when you act on every one of them rather than choosing.
use ;
let mut balancer = new;
balancer
.add_option
.add_option
.add_option
.add_filter;
assert_eq!;
balancer.add_filter;
assert_eq!;
Reproduce random choices
Random picks uniformly with PHP's Mersenne Twister. Seed it to replay a sequence in a test: Random::seeded(7) picks what PHP picks after mt_srand(7).
use ;
let mut balancer = new;
for dc in
let mut picks = Vecnew;
for _ in 0..3
assert_eq!;
Balance your own endpoint type
Options do not have to be Candidates. Use your own type, and filters and custom algorithms see it directly.
use ;
let mut balancer = new;
balancer
.add_option
.add_option
.add_option
.add_filter;
assert_eq!;
Contributing
Development happens in appwrite/appwrite, where this crate lives at crates/utopia/balancer. Run these commands from a checkout of it. The contributing guide covers each step.
Test
Compare with PHP
Replay the results PHP recorded for every case against Rust, without PHP:
COMPAT_LIB=balancer
Run every case on both runtimes, fuzz both with generated inputs, then run the whole conversion check. These need the dev stack (docker compose up -d):
Benchmark
This times every benchmark on PHP and on a release build of Rust, both in containers on the dev stack. It fails if Rust is slower. Add --write to record the run in tests/compat/balancer/bench.json. Run it on a quiet machine, one library at a time.
License
BSD-3-Clause. See LICENSE.