Thanks for the tips I'm sure they will imporove my code. I have solved the problem by reducing my mysql wait_timeout variable and increasing my max connections variable. So all the sleeping mysql processes now timeout. sth->finish unfortunately does not seem to make any differance.