What programming language are you using?
Generally speaking the errors 509 and 504 "exception caught while reading socket" happen when your program stomps on the memory space in error. The fastest way to fix that is to remember exactly what you changed recently, if it was working fine before. But, I have encountered situations where it was not a recent mistake, but an old one that took a long time to appear. Fun, right?
Hopefully you can figure out what's wrong by looking at your code closely. But, another way is to periodically exercise your code in extreme situations if need be, to try to make it break. If it takes weeks to figure out where the problem is and you're still stuck, that's when I have turned to 3rd party tools (one example was a program called deleaker) which pad your program with protected memory space and will tell you when that space becomes violated, and then you can set breakpoints at memory addresses and trace backwards.