DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
VGSources
Blog

How to Fix a 504 Gateway Timeout with Nginx and Ruby on Rails

A 504 from Nginx means the proxy did not receive a timely Rails response. This step-by-step guide shows how to identify the failing layer, test the upstream, inspect Rails and database latency, and adjust only the timeout that evidence supports.
Length10 min Posted Quest giverVGSources Team
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A 504 Gateway Timeout means Nginx, acting as a gateway, did not receive a response from your Rails upstream within the time allowed. The status does not by itself prove that Rails is down or that Nginx is misconfigured. The delay may be while Nginx connects to Puma, Unicorn, or Passenger; while Rails waits on a database or external service; while the application is CPU- or memory-bound; or because a proxy timeout is shorter than legitimate work.

Fix the failing phase before changing a timer: identify when the request fails, correlate Nginx and Rails timings, test the application server directly, then adjust only the relevant timeout if the operation is genuinely expected to take that long.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What a 504 means in a Rails deployment

MDN defines HTTP 504 as the response a gateway or proxy returns when it does not get a timely response from its upstream server. In a common Rails deployment, the chain is client, Nginx, an application server such as Puma, Unicorn, or Passenger, Rails code, the database, and sometimes Redis or an external HTTP service. Nginx can reach the gateway stage and still return 504 because any later component is unavailable, overloaded, silent, or slower than the applicable limit.

A 504 is therefore a boundary symptom, not a component diagnosis. A 502 generally means the proxy received an invalid response from the upstream; a 504 means the expected response did not arrive in time. The distinction helps classify the incident, but logs and direct tests are still required to locate the delay.

#1 Best Overall
Sale
Gaoye Blue Light Blocking Glasses
  • BLUE LIGHT BLOCKING GLASSES: Our blue light glasses for women boast UV400 protection, blocking harmful blue rays from computer screens. With these bluelight glasses women, you can enjoy gaming, reading, or watching TV with no worries of eye strain.
  • EYE RELIEF: Our blue light glasses are engineered to reduce blurry vision or strain caused by prolonged screen time. These womens blue light glasses aid in better sleep by preventing blue light from disrupting your natural sleep cycle, helping you fall asleep faster and enjoy a more restful night's sleep, making them the perfect christmas present.
  • COMFORTABLE: Crafted from durable material, our trendy blue light glasses for woman or blue light glasses men ensure long-lasting comfort. The high-transmittance lenses accessories, gamer gifts for men, help keep your eyes relaxed. Perfect stocking stuffers, gifts for gamers men, christmas gifts for men, halloween costumes.
  • LIGHTWEIGHT: These clear blue light glasses feature a lightweight frame, meaning they’ll stay comfy for long-term wear. Perfect as blue blockers glasses for women or mens blue light glasses, these non-prescription fake glasses for men can be worn throughout the day. The blue light blocking glasses women feature polycarbonate HD lenses, which are anti-reflective and restore true color.
  • WORRY-FREE PURCHASE: If you experience any issues, our support team is ready to assist you quickly. These are the perfect costume glasses for cosplay dressing up.

Start by measuring the failure

  1. Record the request. Note its URL, HTTP method, timestamp, status code, and whether it always fails after approximately the same elapsed time. Include whether only one route fails or all dynamic routes do.
  2. Map every timeout layer. Write down limits at the client, any load balancer or ingress, Nginx, the Rails application server, and the application dependencies. The outermost layer can terminate a request before Nginx’s setting is reached.
  3. Compare successful and failed requests. A stable boundary often indicates a configured timeout, while highly variable durations more often indicate load, contention, or an intermittently unavailable dependency. Treat that as a clue, not proof.

Do not begin by raising proxy_read_timeout. If the upstream process is not listening, a longer read period cannot create a connection; if a database pool is exhausted, it only makes clients wait longer.

Read Nginx logs before changing configuration

Find the matching access-log entry and error-log line for the exact timestamp. Capture the request duration, upstream address, upstream response time, and the phase named in the error message. A message indicating a timeout while connecting points toward a listener, socket, network, or readiness problem. A timeout while reading points toward slow or silent application work, dependency contention, or an overly short read interval.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

If your access-log format includes them, compare $request_time with $upstream_response_time. The first measures the complete Nginx request; the second measures time spent communicating with the upstream. A large upstream value shows that the wait is behind Nginx. A small or missing upstream value with a client-visible timeout suggests the failure occurred before a normal upstream exchange or at another proxy layer.

Correlate the same request with Rails logs and application metrics. Netdata’s troubleshooting guidance specifically recommends comparing upstream response timing with database locks, garbage-collection pauses, and other backend signals. Use the request ID or timestamp so that a slow neighboring request is not mistaken for the failed one.

Rank #2
Windex Gaming Cleaning Wipes, Pre-Moistened Wipes to Instantly Clean all Gaming Gear and Electronics, Resealable Packaging for a Freshness Lock, 25 count (Pack of 1)
  • WINDEX GAMING WIPES: effortlessly clean all your gaming gear and gaming electronics in one easy step with our new Windex Gaming Wipes
  • AMMONIA FREE: our ammonia-free formula is safe to use on all of your favorite gaming equipment like consoles, headsets, controllers, screens, keyboards, and more
  • PRE-MOISTENED WIPES: each wipe instantly removes dust, dirt, and stubborn smudges and fingerprints leaving a streak-free shine
  • ANTI-STATIC: great for cleaning and wiping down your gaming gear and electronics leaving behind no visible residue
  • COMPACT RESEALABLE PACKAGE: store your pack of Windex Gaming Wipes anywhere in your home for whenever a quick and easy wipedown is needed

Verify that the Rails upstream is reachable

Check the process and listener

Confirm that Puma, Unicorn, Passenger, or the selected Rails server is running under its process supervisor and listening on the exact port or Unix socket named in Nginx. For a TCP listener, inspect the host with a command such as ss -ltnp and verify the address and port. For a Unix socket, confirm that the path exists and that the Nginx worker user can access it.

A process can appear running while its socket is stale, its port is different from the deployed configuration, or it is still booting. Check supervisor logs, deployment ordering, socket ownership, and permissions. Restarting the process or repairing readiness is the remedy when no listener exists; increasing a proxy timeout is not.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Call the upstream directly

Send the failing path directly to the application server from the Nginx host, for example curl -i http://127.0.0.1:3000/path, using the actual port and path. For a Unix socket, use the socket path with a command such as curl --unix-socket /path/to/app.sock -i http://localhost/path. A direct success while the proxied request fails points toward Nginx, an outer proxy, headers, or a timeout mismatch. A direct timeout reproduces the problem below Nginx.

Test a lightweight endpoint and the failing route separately. If the lightweight endpoint responds but one controller action does not, focus on that action and its dependencies rather than restarting the whole stack.

Rank #3
Sale
LISEN Cell Phone Stand Phone Holder for Desk, Office Decor Gadgets for Men
  • Ergonomic & Adjustable Design: Fight "text neck" and improve your posture. Designed for comfort, it offers an adjustable height (7.1in-8.5in) (1.4in adjustable range) and angle (5°-85°) Please note: cell phone stand is only 9 inches tall—the length of a standard pencil
  • Without blocking subtitles Perfect for office desk Tiktok Face Time Zoom video—this is the ultimate kitchen desk essential for phones! Perfect viewing experience while reducing neck back strain, A must-have for gamers streamers desk, and anyone who values both style and support!
  • Sleek & Stable Design fits Otterbox Case: Say goodbye to bent cables, tangles, and tip-overs! LISEN’s stylish adjustable desk phone holder features a built-in charging hole and smart cable management, keeping your phone secure and your workspace clutter-free cool gadgets for men
  • ANTI-SLIP DESIGN free hands: The under 10.00 items easy gadgets back and the bottom of this kitchen essentials for women are fully covered by anti-skid silicone, which LISEN stand up desk decor can provide maximum protection device from any scratches and slides
  • Your Perfect Viewing Companion:If your product arrives damaged or breaks within 365 days, reach out to LISEN for a quick and hassle-free solution. Struggling with assembly, like tightening the screw? We’ve got your back! Your experience matters to us. (Product including: phone Holder stand*1, screw*1, hexagon screwdriver*1, specification*1)

Compare Nginx configuration with the actual deployment

Rails’ reverse-proxy guidance uses an upstream group, forwards the original host and client chain, disables proxy redirects, and sends requests with proxy_pass. Adapt the pattern to your real port, socket, TLS termination, buffering policy, and hostnames:

upstream application_server {
    server 127.0.0.1:3000;
}

server {
    listen 80;
    server_name example.test;

    root /var/www/myapp/public;

    location / {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_pass http://application_server;
        # Add measured connect/read/send values only when needed.
    }
}

The example is illustrative, not a universal production file. Confirm that Nginx is loading the server block you edited, that the upstream name resolves to the intended server, and that a more specific location is not handling the failing route. Validate syntax with nginx -t, then reload through the service manager used by your host. A reload applies a corrected configuration without requiring an application restart; always check the reload result and the active error log.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Find delays inside Rails and its dependencies

Application code and controller actions

Use Rails request logs and instrumentation to identify the controller action, time spent rendering, and time spent in database calls. Look for jobs accidentally executed inline, unbounded loops, expensive serialization, lock waits, and exceptions that prevent response headers from being sent. If one route is slow while static files and simple Rails routes are fast, investigate that route’s code path first.

Database and connection-pool contention

Separate query execution time from time waiting for a database connection. Rails documents ActiveRecord::ConnectionTimeoutError when a request cannot obtain a connection within the configured wait period. A pool that is too small, leaked connections, long transactions, database locks, or a database at its resource limit can leave Nginx waiting even though the Rails process is alive.

Rank #4
Ledagic IC+RGBW USB Powered Led Light Bar with App & Remote Control, 2 Pack
  • Easy Installation: Our gaming lights have been designed to enhance your entertainment experience. Simply position the led light bar next to your TV or game console to create a game room environment with ease. They come with USB power and a 60 inch cord for direct mounting and mobility
  • Audio Syncing & Extensive Mode: The built-in high-sensitivity music sensor allows you to sync the TV led lights to your favorite music. Lights react and move to the beat of music, film and game audio, creating an incredible immersive sound and light experience – and all without the need for an additional hub. You can choose from 64+ patterns, including strobe, illusion, jump, energy, gradient, running, chasing, fluttering mode etc. Each mode can be applied to different scenes
  • 64+ Chasing IC+RGB & W Effect: The independent control design of IC+RGB and white all-in-one multifunctional rgbw led bar lights monitor backlight allows you to easily switch the led lights for desk between IC+RGB and white to enjoy a variety of lighting effects, you can choose white lighting mode with high brightness for better illumination when working, etc. Choose IC+RGB lighting mode when you need to create an entertaining atmosphere for the light show, 16 million colours of Color changing rgb light bar let you dance to the beat and create a dynamic party atmosphere
  • Dynamic and Dimmable Lights: 1%-full brightness free brightness adjustment gives you the flexibility to adjust dimmable led light bar for room decorations or a variety of occasions
  • USB Powered: USB light bars for room can be powered by powernank, usb charger, TV, Monitor, laptop PC mainframe, making behind TV led lighting bar easy to install in any location.TV led lights are powered by the TV usb interface / PC mainframe, can be turned on/off synchronously with TV / PC

Check pool utilization and wait time, slow-query logs, lock views, transaction duration, CPU, memory, and disk I/O on the database. Fix the query, index, transaction, pool sizing, or database capacity indicated by those measurements before extending an HTTP timeout.

External services, Redis, and host pressure

An outbound HTTP call without an appropriate application-level deadline can hold a Rails request until Nginx gives up. Inspect dependency latency and failures, and ensure external calls have bounded connect and response timeouts with a fallback appropriate to the operation. Check Redis or other required services separately. On the Rails host, examine CPU saturation, memory pressure, swapping, disk waits, worker utilization, and garbage-collection pauses. A saturated worker pool can make a request wait even when individual requests are normally fast.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use the Rails health endpoint correctly

Rails provides an /up endpoint, or another path if you configure one. The default endpoint returns 200 when the application has booted without exceptions and 500 when boot has failed. It is useful for distinguishing a boot problem from a running process, but it is not a full readiness test: by default it does not prove that the database, Redis, or another dependency can serve a real request.

Call the endpoint through Nginx and directly against the upstream. If both return 500, investigate boot logs and environment or migration errors. If direct /up returns 200 but a business route times out, inspect that route and its dependencies. If the endpoint is 200 while database-backed requests fail, add an application-specific readiness check that exercises the dependencies required for successful traffic, while keeping the check inexpensive and safe.

Best Value
Sale
HUANUO FlowLift™ Dual Monitor Stand, Fully Adjustable Gaming Monitor Desk Mount for 13–32″ Computer Screens, Full Motion VESA 75x75/100x100 with C-Clamp & Grommet Base, Each Arm Holds 4.4 to 19.8 lbs
  • Compatible with Wide Screens - To ensure compatibility with the dual monitor mount, your each monitor must meet three conditions at the same time: First, computer screens size range: 13 to 32 inches. Second, screen weight range: 4.4 to 19.8 lbs. Third, the back of the monitor screen must have VESA mounting holes with a pitch of 75x75mm or 100x100mm.
  • Regarding the compatibility with desks - Your desk must meet three conditions at the same time: First, desk material: Only wooden desks are recommended, plastic or glass desks cannot be used. Second, desk thickness range: 0.59" - 3.54". Third, the bottom of the desk should not have any cross beams or panels, as this will interfere with installation. We recommend carefully checking that your desk and monitors meets all above conditions before purchasing.
  • Dual C-Clamp Hold - Worried your dual monitors might wobble or slip? Our upgraded base uses a larger platform plus a dual C-clamp structure to lock the dual monitor arm firmly to your desk. Each arm safely keeps your screens steady while you type, click and game—no shaking, no sliding, just a clean and secure setup you can trust every day. It also provides Grommet Mounting installation choice, both options ensure stable and secure fixation for your 0.59" - 3.54" desk.
  • Full-Motion Adjustment For Comfortable View - Pull the screen closer when you’re deep in a spreadsheet, push it back to watch videos, or rotate to portrait for coding — moving everything smoothly with just one hand. The monitor stand offers +85°/-50° tilt, ±90° swivel and 360° rotation. Raise your monitor up to 15.75″ to support a healthy sitting posture. Whether you’re working from home, gaming through the night, or switching between video calls and documents, getting the screens to your natural line of sight helps relieve neck, shoulder and back strain so you can stay focused longer with less fatigue.
  • Keep Your Desk Organized: By lifting both screens off the desktop, this dual monitor stand opens up valuable space for your keyboard, notebook, docking station or a simple, clutter-free work area. Built-in cable management guides wires along the arms, keeping cords out of sight and out of the way. Enjoy a tidy, modern workstation that looks as good as it feels to use.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Understand Nginx’s three upstream timers

Nginx documents three independent timeout controls for upstream communication. They describe intervals between operations, not one universal maximum duration for an entire response.

Directive What it governs Typical evidence when it is the relevant limit
proxy_connect_timeout Time allowed to establish the connection to the upstream. Error-log text indicates a connection timeout; the upstream is not reachable, not listening, or cannot accept a connection promptly.
proxy_read_timeout Maximum interval between successive reads from the upstream. Nginx connected, but Rails did not send headers or the next bytes within the interval. A response that continues to stream data can run longer than the nominal value.
proxy_send_timeout Maximum interval between successive writes while sending the request to the upstream. The upstream or network is not accepting request data promptly, often visible with large uploads or a stalled application server.

Because these are interval timers, a streaming response that regularly emits data may remain open beyond the configured read value. Conversely, a silent phase in a long-running Rails action can trigger a read timeout even when the total action would eventually complete.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Raise a timeout only when the measured work is legitimate

  1. Identify the phase. Use the error log and timings to decide whether connect, read, or send time is the limiting phase.
  2. Confirm the route’s expected behavior. A report export or other known long operation may need a longer silent interval; an ordinary page that suddenly takes minutes usually needs optimization or capacity work.
  3. Scope the change narrowly. Apply the directive in the smallest suitable location or server block rather than increasing it globally for every route.
  4. Align other layers. Ensure the load balancer, application server, client, and any upstream service will permit the same operation to complete. The shortest outer limit still wins.
  5. Document the reason and value. Record the observed phase, duration, route, and date so a future change does not turn a temporary workaround into an unexplained global limit.

Do not use a larger timeout to conceal a dead process, wrong socket, exhausted connection pool, slow query, unbounded external call, or resource starvation. Those causes require repair, capacity changes, or code changes.

Use symptoms to separate competing causes

Observation Most useful next check Likely class of cause
All dynamic routes fail, and direct upstream calls cannot connect. Process supervisor, listener address, socket path, permissions, and deployment readiness. Dead or unavailable application server, wrong endpoint, or local connectivity failure.
Nginx connects, but failures cluster at the same elapsed time. Compare the cluster with read limits at Nginx and outer proxies; inspect the Rails request at that timestamp. Silent slow work or a timeout shorter than legitimate processing.
Only one route fails while /up and simple routes succeed. Profile the controller, SQL, external calls, rendering, and locks for that route. Route-specific application or dependency latency.
Direct Rails requests are slow and database pool waits are high. Inspect pool size, query time, locks, transaction length, and database capacity. Database contention or connection-pool exhaustion.
Direct requests are fast but proxied requests fail. Check the active Nginx location, proxy headers, timeout values, buffering, and any load balancer before Nginx. Proxy configuration or an outer-layer limit.
Failures appear during CPU, memory, disk, or garbage-collection spikes. Correlate host metrics with worker utilization and Rails request timing. Application-host saturation or pauses.

Also check whether Rails logs contain the request at all. If Nginx reports a timeout but Rails never records the request, focus on connection establishment, routing, socket readiness, or an intermediary. If Rails logs the request and it remains open until the proxy limit, investigate the code path and dependencies.

Re-test safely and verify that the cause is fixed

  1. Apply the smallest configuration or code change indicated by the evidence, validate with nginx -t, and reload Nginx.
  2. Repeat the original request and a representative control request. Record status, total duration, upstream duration, and whether the response is complete.
  3. Watch Nginx access and error logs, Rails logs, database wait and query metrics, dependency latency, worker utilization, and host resources while reproducing the issue under representative load.
  4. Check for secondary effects such as more concurrent workers held open, rising memory use, depleted database connections, client retries, or a new timeout at an outer proxy.
  5. Keep the change only if latency and error rate remain acceptable and the underlying measured phase is understood. A request succeeding after a timeout increase does not, by itself, demonstrate that the root cause was corrected.

Why requests often fail at an apparently exact 60 seconds

An exact boundary usually means one layer has a timer near that duration, but the number alone does not identify which layer. Check Nginx’s active configuration, the load balancer or ingress, the application server, the client, and any service making the request. Compare each layer’s logs and timestamps. If Nginx’s read timer expires while Rails is still working, either optimize or redesign the operation, or raise that read interval narrowly when the silent period is expected. If an outer proxy expires first, changing Nginx will have no visible effect.

When to change the request design instead

Some operations should not occupy a synchronous web request for a long period. If a report, import, video processing task, or other workload regularly exceeds practical proxy limits, move the work to a background job, return a job identifier, and let the client poll a status endpoint or receive a completion notification. That design reduces worker occupancy and avoids making every intermediary hold an idle connection. It is an architectural change, not a substitute for fixing a broken listener or an unexpectedly slow query.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The reliable sequence is consistent: classify the 504 from logs and timing, prove whether the upstream is reachable, trace Rails and dependency latency, and then tune only the timer that matches the measured phase. This prevents a superficial timeout change from hiding a process, database, or capacity failure.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More quests from Patch Notes

  1. How to Set Up a RedM (RDR2) Server in 2026: License Key, txAdmin and server.cfg, Step by StepBlog11min
  2. Best RedM (RDR2) Server Hosting in 2026: Comparing Four Hosts on Slots, Memory and PriceBlog10min
  3. How to Host a Mindustry Server in 2026: server-release.jar, Port 6567 and the Commands That MatterBlog7min
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.