Sorting With Redis or How To Find Least Busy Server

March 04, 2016

Reading time ~2 minutes

Sorting Server IPs By a Property in the Hash

Apparently you can sort Redis lists by referencing other data structures in your storage.

More on Redis Sort command here.

Problem described here is an inherited design and doesn’t reflect my engineering opinion. I just had to make it work in given ecosystem.


Given a list of hardware servers we need to pull the least busy one from the pool.

Pool in our case is a sorted set of worker ips which is sorted by CPU load in descending order (least busy first). Thus queuer can just take first worker ip in the array and know that’s the least busiest worker.


We need a Redis DB running and be accessible by other servers to update information about themselves.

Will use a Redis Set to store our server ips. And Redis Hashes to store CPU utilization and some other info about the server.

Data Structures

$ redis-cli keys "server*"
1) "server:worker:"
2) "server:worker:"
3) "server_ips"

Here we have two workers and one server_ips set


$ redis-cli hgetall "server:worker:"
1) "cpu"
2) "0.38"
3) "host"
4) ""
5) "errors"
6) "0"
7) "type"
8) "worker"

In JSON that would be

  "cpu": "0.38",
  "host": "",
  "errors": "0",
  "type": "worker"

  "cpu": "0.50",
  "host": "",
  "errors": "0",
  "type": "worker"


$ redis-cli smembers "server_ips"
1) ""
2) ""

In JSON that would be

["", ""]

Actual Sorting> SORT server_ips BY server:worker*->cpu LIMIT 0 1 DESC
1) ""

Since cpu load of our “” worker is less than “0.50” it’s considered the least busy one.

It would be awesome to get entire hash back when you do the sorting, but you can only use GET command for hash property.

You can do pretty cool things with if you read the docs.

Phoenix On A Raspberry Pi with Exrm

## Intro> Before you read this be sure to look at:>> 1. [Phoenix Advanced Deployment](… Continue reading