fix race condition that can cause 'write after end' errors