Discourse site with very large database gives error 502 frequently

Well, yeah, as your DDOSing your server, you are straining it. For what you described in your initial post, you need to really boost your hardware. Discourse is not light/easy on hardware, it requires a lot of it and with 1 million topics and a database size of 20 GB, you need more than 4 GB of RAM, you are liking utilizing a LOT of your SWAP with that setup (if I had to guess)