Swap is used when RAM becomes insufficient. It can be a sign that your application needs more RAM, but normally if an application is hungry for RAM, the issue is located in the application, because it should free RAM once it is done doing something. Again this situation is pointing to an infinite loop somewhere, like a nested rewrite or a nested page with missing resources that are creating infinite script iterations. These again lead to an excessive RAM usage. This causes the 504 error, because scripts never end, so they are not responding to Nginx so Nginx displays the 504 error. Back to field no. 1, you will need to check what the scripts of the application are doing.