Usually AWS CloudFont has timeout setting to wait responses from origin end points. If response takes more than default time out period, it throws 504 timeout error. So of common solutions are below.
Backend taking too much time to response:
CloudFront origin, by default has `Origin Response time’ of 60 sec, if endpoint ( usually EC2 instance / ELB) taking more than 60 sec to response then it throws 504 timeout error. So increasing timeout on CloudFront origin.
Unable to reach any of the origin:
Origin endpoint may be down or spinning new instance. Make sure endpoints are running and accessible. Quick way to check is by IP to insure that its running.