You might be able to code this with Lua, but this should work as well:
........
server backend1.example.com; weight=1 fail_timeout=5;
server backend2.example.com; weight=1 fail_timeout=5;
least_conn;
........
server backend1.example.com; weight=1 fail_timeout=5;
server backend2.example.com; weight=1 fail_timeout=5;
least_conn;