Fixed race condition when stopping connections

to be backported to stable