Get to the root of 504 Gateway errors

Hello,

So, lately it seems, a few of my client sites will randomly come up with 504 Gateway server errors. They are routed through CloudFlare, so generally CloudFlare will cache them and then dish out an "offline version" of the website. Sometimes when trying to view the site, CloudFlare will just straight up dish out a 504 Gateway error page.

Now, it's not constant. Like, most of the time, the websites are totally fine and load nice and fast! I have done absolutely everything I know how for "optimization" and performance (using the Hummingbird plugin in conjunction with W3 according to your awesome blog tutorials).

And yet, but SiteGround (my host) and CloudFlare say it's a script/plugin on my site that's taking too long to load and that's what's throwing the 504 errors from time to time. They then proceed to tell me to "optimize my site" which I have already done.

So, any advice on how I can get to the root of what's causing some of my client sites to throw the 504 errors? Is there any way to test and find out which scripts may be causing the 504 gateway errors?

The sites that this happens on the most are:

https://statmedcaresolutions.com
https://mnmediation.com
https://lighthouseministryintl.org (I know, horribly design - I just manage it)

I just had a HUGE bout of statmedcaresolutions.com going offline, online, offline, online, for about 30 minutes from about 11PM to 11:30PM. It's now up and running fine and I'm trying to grab log information.

Your help is greatly appreciated!

Thanks!

Joshua