In the spirit of reinventing the wheel for fun, I hacked this together as a quick challenge to myself last week. It’s a little rough around the edges, but I thought it was too cute not to share. If you have any bug fixes, please post them in the comments.

#!/bin/bash

set -e -u

function usage() {
  echo "USAGE: ${0} parent {port} {lower_bound_backend_port} {upper_bound_backend_port}"
}

[[ $# < 1 ]] && usage && exit 1

mode=${1};shift
case ${mode} in
  parent)
    PORT=${1};shift
    LOWER=${1};shift
    UPPER=${1};shift
    socat TCP-LISTEN:${PORT},fork,reuseaddr "EXEC:${0} child ${LOWER} ${UPPER}"
    ;;
  child)
    LOWER=${1};shift
    UPPER=${1};shift
    COUNT=0
    PORT=$(shuf -i ${LOWER}-${UPPER} -n 1)
    let "RANGE = UPPER - LOWER"
    SUCCESS=false
    while ((COUNT <= RANGE)) || ${SUCCESS}; do 
      set +e
      if socat STDIN TCP:127.0.0.1:${PORT},connect-timeout=2; then
        SUCCESS=true
        break
      else
        echo "unable to connect to port ${PORT}" >&2
      fi
      set -e
      let COUNT+=1
      let PORT+=1
      if ((PORT > UPPER )); then
        let 'PORT = LOWER'
      fi
    done
    if ! ${SUCCESS}; then
      echo "HTTP/1.1 500 Internal Server Error"
      echo
      echo "All REDACTED servers are down.  Please report to REDACTED@janestreet.com."
      exit 1
    fi
    ;;
  *)
    usage
    exit 1
    ;;
esac