To fix the 504 error, match the server timeout and PHP max_execution_time with your script's runtime. Also, check if your load balancer is causing the timeout.
Using Java servlets or frameworks like Spring Boot is a good option for dynamic filtering. GraalVM might also be worth exploring for multi-language support.