I am getting 502 error while trying to delete topics created by specific user

I had a similar problem before, I needed to delete around 200000 posts from different users with lots of condition. Any ordinary method will bring long-term lag.
Finally I take the dumbest way. Loop from 1 to max post id. If it satisfy the condition, delete it. It took me about an hour to iterate through the them (about 900000 posts)