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

iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more

A 504 Gateway Timeout means Nginx, acting as a gateway, did not receive a response from your Rails upstream before a configured wait expired. The status alone does not tell you whether Rails is slow, unreachable, blocked on a database, waiting on an external API, or being cut off by a shorter timeout in another proxy. Find which phase is waiting first, then change only the setting that governs that phase.

Use this order: record the exact failure and timing, inspect Nginx and Rails logs, test the application server directly, verify the reverse-proxy configuration, measure database and dependency latency, and only then tune a timeout. Increasing proxy_read_timeout can mask a slow request or make overloaded workers stay busy longer if the underlying cause is not fixed.

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

What a 504 means in an Nginx–Rails deployment

MDN defines HTTP 504 as the response returned when a server acting as a gateway or proxy “did not get a response in time from the upstream server in order to complete the request.” In a common Rails deployment, the chain is:

client → Nginx → Puma, Unicorn, or Passenger → Rails code → database, cache, and external services

#1 Best Overall
Sale
Compressed Air Duster,130000RPM Super Power Cordless Air Duster,Rechargeable Brushless Blower,3 Gear Adjustable Blower with LED Light,Dust Remover for Computer/House/Outdoor/Car
  • Powerful Turbo Fan:CAGIWIRU Electric Air Duster have reached speed up to 130000RPM,Can efficient remove dust and debris.With LED light and Three Adjustable Speed to meet with different cleaning tasks.
  • With Attached USB C Fasting Charging cable.Charing 3 hours,Enjoy up to 240 minutes of use on the lowest setting, For third speed can use for 25mins.with four charging options to meet with your needs.
  • Wide Application:Upgraded attached 5 different nozzles,making it suitable for a variety of scenes, such as car,pet, pc, keyboards, and other electronic devices. It also serves for office and home clean duster.
  • Handy Design & Portable:Cordless air duster electric nozzle is Light weight and small size, design and comfortable to hold and space saving, convenient to carry around. You can put it in your room or inside the car without taking up space.
  • Warranty & Support: Our Electric air duster comes with 5 years warranty and 24/7 customer service. During this period, if you have any questions,pls kindly feel free to contact us.

Nginx generated the 504 because it did not receive the upstream response it needed. That makes 504 a boundary symptom, not a diagnosis. A wrong Unix-socket path, a stopped application server, a saturated worker pool, slow SQL, an exhausted Active Record connection pool, a long external HTTP call, CPU pressure, or an Nginx timer that is too short can all produce the same status.

This differs from a 502 Bad Gateway. A 502 means the proxy received an invalid response from upstream; a 504 means the expected response did not arrive within the relevant wait period. The distinction narrows the investigation, but you still need timings and logs to identify the component at fault.

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

Start by proving when and where the request fails

Record the failure precisely

For one failing request, write down the URL, HTTP method, timestamp with timezone, response status, response body, and elapsed time. Note whether every request fails or only one route, HTTP method, tenant, payload size, or time of day. A repeatable boundary such as approximately 60 seconds often indicates a configured timer, but the owner could be a browser, API client, load balancer, Nginx, Rails server, or an upstream service. Do not assume that Nginx owns the interval.

Compare the timeout values at every hop. An outer layer that expires first can hide the behavior of an inner layer, while a longer inner timeout cannot help if a load balancer has already closed the connection.

Reproduce from the machine running Nginx

Testing locally removes client-side and some network variables. Use a request that is safe for the endpoint:

curl -v -w 'nstatus=%{http_code} total=%{time_total}sn' 
  -H 'Host: example.test' 
  http://127.0.0.1/slow-route

If Nginx is on a different host from Rails, run a direct test from the Nginx host to the configured upstream address and port. For a Unix socket, use a socket-aware client or a temporary local proxy; a failed socket check is useful evidence even when a normal browser request only shows 504.

Free tools Windows power users keep installed

One-click scans. No signup required.

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

Read Nginx logs before changing configuration

Find the matching access-log entry

Search the access log by timestamp, request path, or a request identifier. Capture the client status, total request time, upstream address, upstream status, and upstream response time when those fields are present. If your current format does not record timings, add them temporarily or in a controlled configuration change:

Rank #2
EVEO® Screen Cleaner Spray Kit (Streak-Free) TV Screen Cleaner for Smart TV, Lcd, LEd, Oled | Computer Screen Cleaner Spray and Wipe Microfiber Cloth - TV, Monitor, Laptop, iPad, Car - 6.7oz 1 Pack
  • Screen Cleaner is Your Screen’s New Bestfriend! - EVEO is proud to present a screen cleaner that’s perfectly suited for your TV. Meet your new screen cleaner, computer screen cleaner, laptop cleaner, iPad cleaner, Macbook,tv cleaner or any other electronic device. Our screen cleaner spray and wipe along with the included plush microfiber cloth, easily removes dust, fingerprints & other smudges on the screen’s surface. Clean effectively for a streak-free screen
  • Gentle on your Screens - Our screen cleaner spray and wipes is compatible to be used even for the most sensitive LCD, LED, CRT, and OLED screens in proper use. Be at ease knowing that this product is compatible with all the major brands: LG, SONY, Samsung, Sharp, iPad, iPhone, Android screens, Kindle, PC monitors - we’ve got you covered! Can be used as LCD screen cleaner, tv cleaner, smart tv screen cleaner, and more
  • Premium Super Soft Plush Microfiber Cloth - Included in this efficient screen cleaning kit. This screen cleaner spray and wipe has our signature plush microfiber cloth specially designed to comply with screens and monitors and leave them streak-free. Has been shown to effectively absorbs stubborn stains, zero streaks, and no fiber shedding. Always use this together with our screen cleaner for the best results
  • Easy-to-Use Screen Cleaner Kit + microfiber cleaning cloth - The EVEO Screen Cleaning Kit will easily be your new favorite tool when it comes to taking care of the things you love most, quick and easy solution for a streak-free screen. Simply screw on the sprayer gun on the screen cleaner bottle. Spray the cleaning liquid onto the microfiber cloth, then wipe the screen until desired cleanliness & shine is achieved.
  • Quality Screen Care Kit Worth Purchasing - Enjoy a convenient Screen Cleaner anytime, anywhere you need it. Your satisfaction is our top priority. We stand behind the quality of our products and that’s why, you shouldn’t be worrying at all. We manufacture the Best Screen Cleaner. and can be used for laptop cleaning kit, laptop screen cleaner, tv screen cleaner for smart tv. MacBook screen cleaner, monitor cleaner or screen cleaner spray for electronic devices with microfiber cleaning cloth
log_format upstream_timing '$remote_addr - $host [$time_iso8601] '
  '"$request" status=$status request_time=$request_time '
  'upstream_addr=$upstream_addr upstream_status=$upstream_status '
  'upstream_connect_time=$upstream_connect_time '
  'upstream_header_time=$upstream_header_time '
  'upstream_response_time=$upstream_response_time';

Reload only after validating the complete configuration with nginx -t. Keep the existing format if another system parses it, or send the additional fields to a separate diagnostic log.

Interpret the error-log wording

An error stating that Nginx timed out while connecting to upstream points toward a listener, socket, network, process-readiness, or accept-queue problem. A timeout while reading a response means Nginx connected but did not receive the next expected bytes in time. That usually sends the investigation toward Rails execution, database waits, external calls, worker starvation, or a read timer that is shorter than the legitimate silent period.

Correlate the Nginx timestamp with Rails request logs and application metrics. Netdata’s diagnostic guidance specifically recommends comparing upstream response timing with database locks, resource saturation, and garbage-collection pauses. If Nginx reports a 504 but Rails has no corresponding request, investigate the connection path and listener first; if Rails logs the request and it remains open, investigate the code and its dependencies.

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

Verify that the Rails upstream is actually reachable

Check the application-server process

Confirm that the intended Puma, Unicorn, or Passenger process is running under the expected service account and has completed boot. Check the service manager, process list, and recent deployment logs. A process that repeatedly crashes, is still starting, or has exhausted its workers can leave Nginx waiting even though the service appears enabled.

Check the exact port or Unix socket

Compare Nginx’s proxy_pass target with the address on which Rails is listening. Verify both sides rather than relying on an environment variable you assume is loaded:

ss -ltnp | grep 3000
ss -lx | grep myapp

For a TCP listener, test the port from the Nginx host:

curl -v http://127.0.0.1:3000/up

For a socket, check that the path exists, is owned by the account Nginx uses, and has execute permission on every parent directory. A stale socket left by an old deployment, a changed release path, or a permission mismatch can prevent a connection. Restarting Nginx or increasing a read timeout cannot repair an absent listener.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
BladeHawks RGB Gaming Mouse Pad Extra Large Extended 31.5x12 Inch-Black
  • 【Large size】:Measuring 800 x 300 mm/ 31. 5×12 inches, which is wider and taller than others. Large mouse pad can perfectly fit your keyboard and mouse of any size, and there is also ample space for peripherals such as phones, tablets, etc.
  • 【LED backlight mouse pad】:Blade Hawks RGB mouse pad provides 7 static modes and 7 dynamic modes will give you the options you are looking for. Power-off memory function remembers the last lighting mode you selected. The super glow fiber Chroma will give you a colorful gaming setup that you want.
  • 【Anti-slip rubber base】:Made from Natural rubber, this gaming mousepad will firmly grip your desktop, allowing you to enjoy the ultimate precision in the games you are most passionate about. It also comes with a texture that enhances this ability even further.
  • 【Smooth and waterproof surface】: Micro-textured cloth surface, for extremely precise mouse control and a smooth movement. When liquid splashes on the gaming mouse pad, it forms water droplets and slides down. Will not delay your work or gameplay.
  • 【Plug and play】: This mouse and keyboard pad is powered by USB, plug and play, no driver required. One button control light modes. Press one time to change the lighting mode, press twice to change the brightness, press and hold about 3 seconds turn ON/OFF.

Use a direct result to classify the fault

  • Direct upstream request fails immediately: repair the Rails process, listener, socket, permissions, network route, or deployment ordering.
  • Direct upstream request is fast but the public route times out: compare Nginx location matching, headers, buffering, TLS or load-balancer layers, and the exact upstream target.
  • Direct upstream request also waits: keep the investigation inside Rails, its database, external dependencies, or host resources.

Compare Nginx configuration with the deployment

Rails’ reverse-proxy guidance uses an upstream group, forwards the original host and client-chain information, disables proxy redirects, and sends the location to that upstream. Adapt the pattern to your actual port or socket, TLS setup, static-file layout, and service manager:

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 timeouts at the narrowest location.
    }
}

Check for a more specific location block that overrides the settings shown above. Confirm that the upstream name resolves to the intended server, that a trailing slash in proxy_pass is deliberate, and that the forwarded host and scheme match Rails’ URL and routing expectations. Validate and reload with the commands appropriate to your host:

sudo nginx -t
sudo systemctl reload nginx

A reload applies a valid configuration without needlessly dropping existing connections. If your platform does not use systemd, use its service manager’s equivalent reload operation.

Trace time spent inside Rails and its dependencies

Slow controller actions or inline work

Inspect Rails logs for the request’s start and completion, controller action, view-render time, database time, and exception details. Look for report generation, file processing, exports, or jobs accidentally executed inline during a web request. Move work that does not need to complete before the response into a background job and return an explicit job status when the application’s workflow permits it.

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

Database locks, slow SQL, and pool waits

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. Check Active Record pool size against the number of web workers and threads, database connection limits, lock waits, long transactions, and query plans. A larger Nginx timeout does not create database connections or remove a lock; it can instead keep more web workers occupied while they wait.

External HTTP and other network calls

Find calls to payment, identity, storage, messaging, or other external services in the slow request path. Record each client’s connect and response timeout separately, and use bounded retries with backoff. A dependency that waits for its own unbounded socket timeout can make Rails appear silent to Nginx. Prefer asynchronous processing or a cached result when the user does not need the remote response synchronously.

CPU, memory, disk, and garbage collection

During a 504, inspect CPU load, memory pressure, swap, disk I/O, file-descriptor limits, container throttling, and Ruby garbage-collection pauses. A host can accept connections while being too saturated to schedule Rails workers promptly. Compare worker and thread counts with available CPU and database capacity; adding concurrency to an already constrained database can increase queueing rather than reduce latency.

Rank #4
Sale
Vaydeer Wrist Rest for Keyboard and Mouse, Computer Ergonomic Wrist Support Pad, Soft Memory Foam Arm Cushion for Desk, Palm Hand Office Laptop Typing
  • 【Softer and More Comfortable】Vaydeer wrist rest has unique diamond pattern, which is the combination of softness and aesthetics. The materials of wrist rest are improved into higher quality memory foam and covered with silky smooth lycra. The computer wrist rest makes you as comfortable and cushiony as like rest your wrists on clouds.
  • 【Ergonomic Wrist Saver】The wrist rests for keyboard and mouse comes with a 17.32×3.15×0.83 inch keyboard wrist pad and a 5.94×3.15×0.83 inch mouse wrist support. Based on ergonomic design, the unique concave shape is the perfect fit for your wrist joints. The wrist rest pad fits most computer keyboards and laptops, improve hand and wrist posture, release your wrist and arm stress.
  • 【Non-Slip Rubber Bottom】Featuring an anti-skid silicone base on the bottom, this wrist keyboard support stays firmly in place on your desk, preventing the padding from sliding around, ensuring stable and consistent wrist support during extended computer sessions.
  • 【Better Experience & Pain Relief】Our keyboard arm rest is beneficial to alleviate the soreness caused by direct contact and friction between your arm and a hard desk surface, reducing the risk of wrist fatigue or carpal tunnel. The soft texture of memory foam can evenly distribute the pressure around your wrists and provide good support with just enough give.
  • 【Helpful in Multiple Scenarios】Whether you're working, studying, writing, typing, gaming, this keyboard and mouse rest combo is an essential accessory to add comfort and support to your hands and wrists. It’s also a great gift for men, women, family, friend, coworker, gamer, teacher, etc.

Use Rails’ health endpoint, but know what it proves

In supported Rails versions, /up returns HTTP 200 when the application has booted without exceptions and 500 when boot failed. Request it through both the upstream and Nginx paths:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
curl -i http://127.0.0.1:3000/up
curl -i -H 'Host: example.test' http://127.0.0.1/up

A 200 proves that Rails booted and can answer that endpoint; it does not prove that the database, Redis, a message broker, or an external API is usable. The default check deliberately has that limited scope. If successful user requests require dependencies, implement a separate readiness check that performs bounded, non-destructive dependency tests and configure the load balancer or process supervisor to use it. Keep a lightweight liveness check for “the process is running” separate from readiness, which answers “this instance can serve traffic.”

Understand Nginx’s three upstream timeout controls

NGINX documents three independent timers for upstream communication. They are not one global maximum request duration.

Directive What it governs Typical diagnostic clue
proxy_connect_timeout Time allowed to establish the connection to the upstream server. Errors occur while connecting; listener, socket, network, or accept-queue issue is likely.
proxy_read_timeout Time between successive reads from the upstream, including waiting for response headers or the next data chunk. Connection succeeds, but Rails is silent longer than this interval.
proxy_send_timeout Time between successive writes while sending the request to the upstream. Large or slow request bodies, a blocked upstream reader, or client-upload behavior is implicated.

The read and send values describe inactivity intervals, not necessarily total response duration. A streaming response can run longer than the nominal read value if data continues to arrive before each interval expires. Conversely, a normal request that sends no headers for the entire interval can time out even if it would eventually succeed.

Match the symptom to the most likely cause

Observed pattern Most useful checks Likely corrective action
Fails while connecting; upstream address or socket is absent ss, service status, socket path, permissions, deployment logs Start or repair the app server, fix the target, permissions, readiness, or process supervision.
Rails logs never show the request Nginx location selection, upstream address, network path, load-balancer routing Correct routing or listener configuration before changing read timeouts.
Only one slow route fails near the same interval Controller trace, SQL timing, external-call timing, request payload Optimize or move the work; raise a narrow read timeout only if the delay is intentional.
Many routes slow down under load Worker and thread utilization, Active Record pool waits, CPU, memory, GC, database locks Remove the bottleneck, right-size concurrency and pools, and scale or shed load safely.
Only requests using one dependency fail Dependency latency, connection and read timers, retry behavior, dependency health Bound the call, handle failure, cache or queue work, and restore the dependency.
Failure occurs at a stable 60-second boundary Every proxy, load balancer, client, Nginx, app-server, and dependency timeout Identify the layer owning the boundary; align values intentionally rather than guessing.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Raise a timeout only after measuring the failing phase

  1. Identify the phase. Use Nginx error text and upstream timing fields to determine whether the wait is connect, read, or send.
  2. Confirm the work is legitimate. Verify that the Rails action is expected to take that long and that no lock, pool exhaustion, unbounded retry, or failed dependency explains it.
  3. Change the narrowest scope. Put a route-specific value in the relevant location block instead of increasing the timeout for every request.
  4. Keep layers coherent. Ensure the load balancer and client permit at least the intended duration, or deliberately return an asynchronous job response when they cannot.
  5. Validate and reload. Run nginx -t, reload Nginx, and record the change and its reason.
  6. Retest under representative load. Confirm status, total time, upstream time, worker utilization, database pool waits, and error rate. A request succeeding after a timeout increase does not prove that the bottleneck disappeared.

For example, if a report endpoint performs a measured 75-second calculation and emits no data, a route-specific proxy_read_timeout 90s; may be appropriate after the application and database are healthy. The value is an operational decision for that deployment, not a universal recommendation. If the same endpoint sometimes waits indefinitely on a locked query, increasing the timer only delays failure and ties up more capacity.

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.

Fix the underlying causes instead of hiding them

Wrong listener, socket, or deployment order

Make the process supervisor create the socket or bind the port before Nginx sends traffic. Use a readiness gate so a new release is not advertised until Rails has booted. Remove stale socket files safely during controlled restarts, preserve ownership and directory permissions, and ensure the Nginx account can traverse the path.

Worker starvation

Count concurrent requests, queueing time, and active workers. A small worker pool, a blocked thread, or a long synchronous job can leave new requests waiting. Separate web traffic from background workers, cap expensive endpoints, and set application-level deadlines so one request cannot consume a worker forever.

Best Value
Sale
Under Desk Cable Management Tray No Drill, Metal Mesh Cable Management Under Desk with Clamp Mount, 2 Hole Cable Tray with Wire Management and Cord Organizer for Home Office Standing Desk
  • 【No Drill Mounted】Cable management tray can be assembled in as little as 3 minutes or less-simply. Side clips easily clampe the edge of desk, pass through the holes on the sides, and secure excess cables with baskets. Desk cable management supports inward or outward installation to meet your needs in different scenarios, and provides you with great convenience when collecting and organizing wires.
  • 【Rubber Pad Protects Desk】Wire organizer under desk built-in soft rubber pads on the clamp protect your desk from scratches, so you will not damage your furniture or office.
  • 【Sturdy and Beautiful】Cord management under desk is made of high-quality carbon steel and holds about 15 lbs. The wire basket has 2 holes on each side of the tray to enable your cables to pass freely. Cable baskets are suitable for desk thickness use from 0.4" to 2.4".
  • 【Space Saving & Keep Organized】Desk cable management tray holds all your power cords, outlet strips, USB hubs and computer transformers hidden from your feet, and the data cables will not enter the vacuum cleaner to keep your desk clean and tidy. Desk wire organizer is also suitable for use in the kitchen and outdoors.
  • 【Reduce Safety Risks】Cable tray under desk keeps all plugs away from your kids, no more worry about tripping. Using 2 holes wire tray saves extra space, helps you easily cabling and wire protection. The mesh design is not easy to accumulate dust, but avoids safety accidents caused by messy wires.

Database contention

Inspect lock graphs, slow-query logs, transaction duration, missing indexes, and connection-pool utilization. Shorten transactions, eliminate unnecessary queries, paginate large reads, and schedule maintenance outside peak traffic. Align Rails pool settings with actual worker and thread concurrency and the database’s connection limit.

External-service instability

Give each outbound client an explicit connect and read deadline, classify retryable errors, and use circuit breaking or fallback data where appropriate. Log dependency name, attempt number, and elapsed time without recording credentials or sensitive payloads. Queue work that does not need to block the HTTP response.

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

Resource pressure and garbage collection

Track per-process memory, Ruby allocation and GC pause time, CPU throttling, and disk latency. Reduce object creation in hot paths, stream or batch large responses, fix leaks, and set capacity limits before adding more concurrency. A restart can clear an acute leak, but it is not a durable fix without finding why memory grows.

Retest and prevent a repeat incident

After a change, replay the original request and a normal fast request. Verify that the direct upstream and public Nginx paths agree, then watch logs and metrics during representative traffic rather than a single successful curl. Keep dashboards or alerts for:

  • Nginx 5xx counts separated into 502 and 504.
  • Request time, upstream response time, and upstream connect time by route.
  • Rails worker and thread utilization, queueing, and exception rate.
  • Active Record pool usage and connection wait time.
  • Database lock waits, query latency, CPU, memory, disk I/O, and Ruby GC pauses.
  • Latency and error rate for every synchronous external dependency.

Document the intended timeout at each layer, the endpoint’s expected work, and the rollback command. Add a deployment check that validates Nginx configuration, confirms the upstream listener, requests the liveness endpoint, and verifies readiness before shifting production traffic.

Bottom line

Fix a Rails 504 by locating the boundary that is waiting, not by blindly enlarging a timer. Logs and direct upstream tests distinguish an unreachable listener from a connected but silent application; Rails, database, dependency, and host metrics identify the real bottleneck. Once the measured phase is healthy, set the smallest appropriate Nginx timeout and align the other layers so the system fails predictably instead of hiding overload.

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

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.