Web developers often observe this kind of mistake on the servers with nginx as the frontend and Apache as the backend. The problem is usually assigned to nginx and the latter gets strenuously cured. Quite often it’s not the point, anyway.
It should be admitted that 504 Gateway Timeout happens when nginx sends client Apache requests but Apache fails to return HTTP-response within the established limit of time.
So the essence of this problem is that Apache failed to respond. It’s possible that the site workload has increased and Apache gets short of time to give HTTP-responses while the new requests keep gathering in line. Clients are stuck in the line. If they are not served in the established time, connection fails.