Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Sharded load balancing with nginx and perl
# Balancing over 4 nodes by hashing URI (consistently with md5)
# onto 16 shards.
upstream x0 { server 192.168.0.2; server 192.168.0.3 backup; }
upstream x1 { server 192.168.0.2; server 192.168.0.4 backup; }
upstream x2 { server 192.168.0.2; server 192.168.0.5 backup; }
upstream x3 { server 192.168.0.2; server 192.168.0.3 backup; }
upstream x4 { server 192.168.0.3; server 192.168.0.4 backup; }
upstream x5 { server 192.168.0.3; server 192.168.0.5 backup; }
upstream x6 { server 192.168.0.3; server 192.168.0.2 backup; }
upstream x7 { server 192.168.0.3; server 192.168.0.4 backup; }
upstream x8 { server 192.168.0.4; server 192.168.0.5 backup; }
upstream x9 { server 192.168.0.4; server 192.168.0.2 backup; }
upstream xa { server 192.168.0.4; server 192.168.0.3 backup; }
upstream xb { server 192.168.0.4; server 192.168.0.5 backup; }
upstream xc { server 192.168.0.5; server 192.168.0.2 backup; }
upstream xd { server 192.168.0.5; server 192.168.0.3 backup; }
upstream xe { server 192.168.0.5; server 192.168.0.4 backup; }
upstream xf { server 192.168.0.5; server 192.168.0.2 backup; }
perl_set $x 'sub {
use Digest::MD5 qw(md5_hex);
my $r = shift;
my $uri = $r->uri;
my $shard = substr md5_hex($uri), 0, 1;
"x$shard"
}';
server {
location / {
proxy_pass http://$x;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.