This usually happens if it couldn't either establish a TCP connection or the HTTP first-byte response took more then what was configured in Origin read/response timeout.
To troubleshoot HTTP 504 errors, check the configurations on your firewall, security groups, and origin server to identify the source of the errors.
By default, CloudFront allows you to keep the origin connection open for 30 seconds. If your applications need more than 30 seconds to process and then return a response, then CloudFront returns an HTTP 504 error.
For further details, you can check out the details from the AWS Training and Certification.
Hope this helps!