refactor the routing algorithm and implement state cleanup