DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowHalloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
Skip to content
World desk11 min

How to Rate Limit a Node.js App With Nginx on Ubuntu

A practical Ubuntu guide to putting NGINX in front of Node.js, limiting API requests per IP, choosing burst and nodelay behavior, testing safely in dry-run mode, and troubleshooting proxy identity.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Put NGINX in front of your Node.js process, define a shared limit_req_zone in the main http {} block, and apply limit_req to the API location that proxies to Node. The configuration below allows an average of five requests per second per client IP, absorbs a burst of ten requests, returns HTTP 429 when the burst is exhausted, and provides a dry-run rollout so you can observe real traffic before rejecting anything.

What NGINX rate limiting protects

A Node.js server can be overwhelmed by a sudden concentration of requests even when its average traffic is manageable. Login brute-force attempts, an accidentally aggressive mobile client, a retry loop, or a deliberate burst can consume connections and application resources before your code has time to respond. NGINX can reject or pace those requests at the edge, before they reach Node.js.

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.

The NGINX HTTP request-limit module uses a leaky-bucket algorithm. A zone stores per-key state and a configured rate drains that state over time. In the common arrangement, the key is $binary_remote_addr, so each client IP gets its own allowance. NGINX performs the check in the reverse proxy, while Node.js continues to handle requests that pass the policy.

A typical deployment is:

  • Client connects to NGINX, which may terminate TLS.
  • NGINX applies the request limit to an API location.
  • Allowed requests are proxied to Node.js, for example at 127.0.0.1:3000.

Rate limiting is not a replacement for authentication, authorization, input validation, or an application-level quota. It is an inexpensive first barrier that keeps excessive traffic from consuming Node.js capacity.

#1 Best Overall
Sale
TOZO A1 Wireless Earbuds Bluetooth 5.3 Light Weight in Ear Headphones | IPX5 Waterproof,2 Mics for AI Calls,Immersive Premium Sound Bass Headset with Charging Case,32 EQ via App Black
  • [Ultra-Lightweight Ear Buds Designed for Small Ears] Each earbud weighs only 3.7g and features a compact, ergonomic in-ear design made especially for small ears. Secure, low-profile, and comfortable for workouts, all-day wear or overnight sleeping.The ultra-slim profile sits flush in your ear with no hard edges poking or rubbing, so you can even sleep on your side without discomfort.
  • [Immersive Stereo Sound with TOZO OrigX Technology] TOZO OrigX tuning delivers clear vocals, balanced mids, and natural stereo sound for music, podcasts, and videos.
  • [Long Battery Life for Daily Use] Get up to 7 hours of playtime on a single charge, with up to 32 hours total using the charging case—ideal for workdays, commuting, and extended listening sessions.
  • [Bluetooth 5.3 & Stable Connection] Bluetooth 5.3 provides fast pairing, stable wireless performance, and reduced dropouts as you move around home or office.
  • [Deep Bass with Clear Vocals] High-performance drivers produce punchy bass while keeping vocals clean and detailed for everyday listening.

How the directives fit together

limit_req_zone: define state and an average rate

limit_req_zone is declared only in the main http {} context. Its basic form is:

limit_req_zone key zone=name:size rate=rate;

The key identifies a client or another trusted grouping. $binary_remote_addr is efficient for per-IP state. The zone name and size create shared memory that NGINX workers use together. The rate is an average, expressed as requests per second (r/s) or requests per minute (r/m).

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

For example, zone=api_limit:10m creates a zone named api_limit with 10 MB of shared memory, while rate=5r/s sets five requests per second as the long-term rate for each key. Those numbers are starting values for this example, not a universal capacity benchmark.

limit_req: apply the policy

Place limit_req in the server {} block or, more selectively, in an API location {} block. It references the zone and optionally defines a burst:

limit_req zone=api_limit burst=10 nodelay;

burst=10 permits up to ten requests above the immediate rate as a temporary queue. Without nodelay, requests in that queue are delayed so processing follows the configured rate. With nodelay, requests that fit within the burst are forwarded immediately; the burst acts as a short allowance rather than a waiting line. Requests beyond the burst are rejected.

Rejection status

NGINX documents HTTP 503 as the default status for requests rejected by limit_req. APIs commonly return 429 (Too Many Requests), which makes the condition explicit to clients. Set that choice deliberately:

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

The status directive belongs in the same applicable context as the request-limit policy. If you omit it, clients receive the documented default 503.

Dry-run mode

limit_req_dry_run on; counts requests that would exceed the configured rate but does not limit processing. It is useful during rollout: you can inspect logs and application latency, adjust the values, and only then enforce the policy.

Rank #2
Sale
Smart Watch for Men Women Compatible with iPhone Samsung Android Phone 1.69 inch Full Touch Screen IP68 Waterproof Bluetooh Fitness Tracker Heart Rate/Sleep Monitor (Black)
  • 【IP68 Waterproof Multifunctinal Smart Watch】Torjalph fitness activity tracker smart watch is IP68 waterproof technology ,you can wear it when swimming,handwashing,it's rain-proof which means that you perform multiple exercise modes outside without worrying about sweat or rain corroding your fitness smart watch,and this watch equipped with a 230 mAh large capacity battery magnetic charging ,and this sports activity tracker watch can be used 5-7 days If fully charged.
  • 【Larger 1.83'' Full Screen Watch & Multi-dial Selection】1.83 inch full HD color touch screen smart watch for men / women provides excellent 240*284 resolution image quality ,This Bluetooth smart watch offers a better touch experience and remarkable immersion and ,more than 200 watch faces for you to choose from App"Da Fit ", you can change the dial style according to your mood to wear keeping the world on your wrist
  • 【Accurate Activity Tracker Smart Watch 】sports watch activity tracker uses sweat and dust resistant breathable silicone strap, our Fitness Tracker Smart Watch for Android iOS Phones supports 12 sports modes,walking,running,bicycle,swimming,badminton,basketball,football,rope skipping. This bluetooth calls smart watch for men women is lightweight and stylish, bringing more convenient and relaxing sports experience while also providing more protection.
  • 【Your 24 Hour Personal Daily Health Monitor】Fitness watch for women men full touch screen IP67 waterproof bluetooth smartwatch for Android iOS Phones with heart rate blood pressure monitor multifunction Andriod smart watch with steps counter sleep monitor sports fitness watch, monitoring blood oxygen saturation allows you to understand your physical condition in real time to track fitness progress ,to know your health status in time.
  • 【More Functions Bluetooth Call Smart Watch】This fitness activity smart watch full screen for iPhone and Android phones includes a bunch of new features including:The bluetooth smart watch can hang up the phone, receive and display WhatsAPP /Text /Facebook /Twitter /Messenger reminder.Support sedentary reminder, alarm clock, stopwatch, timer,weather information,music control, remote camera control compatible with Android 5.0 and above or iOS 9.0 and above smartphones.

Prerequisites on Ubuntu

  • An Ubuntu server with administrative access through sudo.
  • A Node.js application listening on a local address such as 127.0.0.1:3000.
  • A DNS name pointing to the server if you will use a named virtual host.
  • Permission to edit files under /etc/nginx/ and inspect /var/log/nginx/.

Keep Node.js bound to localhost when NGINX is the intended public entry point. Exposing the Node port directly would let clients bypass the NGINX limit.

Install and verify NGINX

Ubuntu’s NGINX installation guide documents using the official signing key and repository when you need the latest NGINX Open Source packages. After that repository is configured, install the package and verify that the service answers locally:

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.
sudo apt update
sudo apt install nginx
sudo systemctl enable --now nginx
curl -I 127.0.0.1

The last command should return an HTTP response from NGINX. If it fails, check the service before changing rate-limit settings:

sudo systemctl status nginx
sudo journalctl -u nginx --no-pager

NGINX configuration files live under /etc/nginx/. Access and error logs are normally under /var/log/nginx/. Distribution layouts can include a main nginx.conf plus files included from conf.d or sites-enabled; inspect the existing file before adding a second server definition.

Build a per-IP API limit

1. Back up the active configuration

sudo cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.bak

If your virtual host is in a separate file, back up that file as well. A backup gives you a direct recovery path if a syntax or routing change prevents NGINX from reloading.

2. Define the shared zone in http {}

Open the main configuration:

sudo nano /etc/nginx/nginx.conf

Add the zone inside the existing http {} block, not inside server {} or location {}:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
http {
    limit_req_zone $binary_remote_addr zone=api_limit:10m rate=5r/s;

    # existing MIME, logging, and include directives remain here
}

Do not create a second top-level http {} block. If a zone with the same name already exists, reuse it or choose a distinct name after checking which locations reference it.

3. Apply the zone to the API location

Add or edit the virtual host that proxies requests to Node.js. This complete example limits only paths beginning with /api/:

Rank #3
New Bee Guitar Cable 10ft Electric Instrument Bass AMP Cord
  • [Low Noise High Fidelity] New bee guitar cord with 22AWG oxygen-free-copper center conductors provides enhanced signal transfer, the PVC insulation material and the high-density stranded copper double shield provide noise rejection for quiet operation
  • [Ideal for Choice] New bee 1/4 straight and right angle metal connectors, ensures a secure connection in any instrument, pedal, or amp jack. L shape great fro on stage guitar stands
  • [Wide Compatible] Suitable for mixer, power amplifier, microphone, effector, decoder, equalizer, electoronic organ, electric guitar, electric bass and other electronic equipments. Widely used in the installation of smart home, karaoke speaker, professional stage audio, etc
  • [Easy Disassemble] Making incidental repairs quick and easy! Very nice, flexible cable
  • [Dont Hesite to Order] 24 hours customer services and professional technology team are standing by
server {
    listen 80;
    server_name example.com;

    location /api/ {
        limit_req zone=api_limit burst=10 nodelay;
        limit_req_status 429;

        proxy_pass http://127.0.0.1:3000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

Replace example.com with the hostname in your deployment. The proxy_pass destination must match the address and port where your Node process listens. The forwarded headers preserve host, client-address, and protocol information for the application.

4. Validate before reloading

sudo nginx -t

Only reload after the test reports a successful syntax check:

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

A reload lets existing connections finish while workers adopt the new configuration. If validation fails, read the file name and line number in the error, correct it, and run nginx -t again. Never force a reload with an invalid configuration.

Roll out without surprising clients

Start in dry-run mode

Temporarily add the directive to the same API location:

location /api/ {
    limit_req zone=api_limit burst=10 nodelay;
    limit_req_status 429;
    limit_req_dry_run on;

    proxy_pass http://127.0.0.1:3000;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
}

Run sudo nginx -t, reload, and observe traffic during representative busy periods. Dry-run mode records excess activity without rejecting or delaying requests, so compare the NGINX access and error logs with Node.js latency and error metrics.

Generate controlled requests

Use a test endpoint that is safe to call repeatedly. This shell loop sends 30 sequential requests and prints each status code:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
for i in $(seq 1 30); do
  curl -s -o /dev/null -w "%{http_code}n" http://example.com/api/health
 done

Sequential requests may not fill the burst. To create concurrency from a test machine, run several loops or use a load-testing tool approved for your environment. Keep the test small enough that it cannot become an outage itself.

During dry-run, all requests should still be processed, but the logs should show which requests would have exceeded the limit. Confirm that ordinary traffic is not being misclassified and that the chosen key represents the client identity you intend to control.

Rank #4
BSIMB 15.6" Digital Family Calendar & Chore Chart, No Subscription Fees
  • Digital Family Calendar: BSIMB digital calendar wall touch screen puts an end to your chaotic life. Designed for busy families, the digital calendar keeps you organised and in step with your family. Assign different colours and tasks to each family member to make family scheduling easier and more intuitive.
  • Easy Setup and Auto-Sync: Plug in, connect to WLAN and auto-syn your electric calendar in minutes. Digital wall calendar compatible with Google calendar, iCloud calendar, Outlook calendar, Cozi calendar and Yahoo calendar. Add events directly on the device or through the ecalendar app. Electronic calendar stays current whether you're at work or traveling—no manual updates needed.
  • All-In-One Home Assistant: Smart calendar builds habits and encourage independence with personalised chores. Display daily meal plan to reduce the daily ‘What's for dinner?’ stress. To-do lists keep track of everything you want. Turning chores into valuable achievements with stars and rewards, making life easier and more enjoyable.
  • Manage Anytime Anywhere: BSIMB electronic calendar for family stay connected with the powerful ecalendar app. Access and manage your digital wall calendar anytime, anywhere with free features like stars & rewards, photo screensaver, chore charts, meals plans, to-do lists etc. Electronic planner paid features like Magic Import tailor advanced tools for users with special needs.
  • Stay in Touch with Loved Ones: Share photos or videos from your phone to electronic wall calendar with app, instantly update your life moment, and keep in touch with your family, especially those who are far away; you can also surprise your smart calendar digital wall by sending him a wish card; it's also great for keeping tech-illiterate elders in touch with the youngsters.

Enforce the policy

After reviewing the observations, remove or set limit_req_dry_run off;, validate, and reload:

sudo nginx -t && sudo systemctl reload nginx

Repeat the controlled test. Requests within the configured rate should pass. Requests that fit the burst should either be forwarded immediately because of nodelay or delayed if you removed that option. Sustained traffic beyond the burst should receive HTTP 429 in this example.

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

Choose rate, burst, and delay behavior

Average rate

Start with the traffic your Node.js endpoint can handle while preserving its latency objective, then compare that with normal per-client behavior. A value of 5r/s means five requests per second per key over time; it does not mean that only five requests can ever arrive in a one-second wall-clock window. The leaky-bucket state smooths the flow.

Use r/m when the endpoint is naturally measured per minute, such as an operation intended to run only a few times per minute. Keep the unit beside the number when documenting the policy so an operator does not confuse requests per minute with requests per second.

Burst size

A burst absorbs a short spike above the average. A larger burst improves tolerance for legitimate fan-out or reconnects but also permits more work to reach Node.js before rejection. A smaller burst protects the upstream more aggressively but can penalize clients that make several parallel calls during normal page loading.

Delayed queue versus nodelay

Setting Behavior for requests inside the burst Typical consequence
No nodelay NGINX delays queued requests so they leave at the configured rate. Smoother upstream load, but clients experience added latency.
nodelay NGINX forwards burst requests immediately and tracks them against the bucket. Lower latency for short spikes, with a larger instantaneous load on Node.js.

Choose based on endpoint behavior. A read-only API that can tolerate a brief spike may use nodelay. An expensive report-generation endpoint may benefit from delayed processing or a stricter burst.

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

Scope

Applying the directive to location /api/ leaves static files, health checks, and unrelated routes outside this policy. Applying it at server {} covers every matching location in that virtual host. Use separate zones when two classes of endpoint need independent rates.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Use the right client key

$binary_remote_addr is appropriate when NGINX directly sees the client address. If another trusted load balancer or proxy is in front, $remote_addr may be the proxy’s address, causing every user to share one bucket. Correct the trusted-proxy arrangement before switching to a forwarded header; blindly using a client-supplied header lets users evade the limit by changing it.

Per-IP limits also have trade-offs. Many users behind one corporate NAT or mobile carrier can share an address and exhaust the same bucket, while a distributed attack can use many addresses. For authenticated APIs, an application-level user or token quota can complement the edge IP policy.

Keep Express and NGINX identity consistent

Express uses the trust proxy setting to decide how proxy-provided address, protocol, and host information should be exposed. Configure it to match the real number and arrangement of trusted proxies:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
// Example only: choose a value that matches your topology
app.set('trust proxy', 1);

Do not copy that value without checking your deployment. With no proxy, trust none. With one controlled reverse proxy, trust that one hop; with multiple controlled hops, configure the corresponding topology or trusted addresses. An incorrect setting can make req.ip unreliable and can cause an application limiter, audit log, or session rule to disagree with NGINX. Forwarded headers must be written by infrastructure you control, not accepted indiscriminately from the public internet.

Observe and troubleshoot the enforced limit

Confirm which configuration is active

sudo nginx -T

This prints the complete expanded configuration, including included files. Search the output for limit_req_zone, limit_req, the zone name, and the matching location. It is often faster than guessing which virtual-host file NGINX loaded.

Inspect logs

sudo tail -f /var/log/nginx/access.log /var/log/nginx/error.log

Use the access log to check status codes and the error log to identify request-limit events or configuration problems. If your virtual host defines separate log files, inspect those paths instead. Correlate timestamps with Node.js logs to distinguish rejected requests from upstream failures.

Common symptoms and fixes

Symptom Likely cause Action
Every user receives 429 quickly. All traffic appears to come from one proxy address, or the rate is too low for the shared address. Verify the trusted proxy path and key; then tune the rate using observed traffic.
Clients see 503 instead of 429. limit_req_status is absent or not in the effective context. Set limit_req_status 429;, run nginx -t, reload, and confirm with nginx -T.
Static files or health checks are throttled. The directive is applied at server {} instead of only the API location. Move the policy to the intended location or create separate locations with separate policies.
Configuration test fails. Directive is in the wrong context, a brace is missing, or a zone name is duplicated incorrectly. Use the reported line number, check the surrounding braces, and ensure the zone is inside http {}.
Limits disappear after a restart. The edited file is not included by the active configuration. Use nginx -T and place the directives in a loaded file.
Node sees the wrong client IP. Forwarded headers or Express trust proxy do not match the topology. Verify NGINX headers, trusted hops, and the address observed at each layer.
Legitimate parallel requests fail. Burst is too small for the client’s normal connection pattern. Measure normal concurrency, increase burst cautiously, or give that endpoint a separate zone.

Operating the policy safely

  • Keep the zone definition in one place and document which locations consume it.
  • Record the rate unit, burst, status code, key, and whether nodelay is enabled alongside the deployment configuration.
  • Alert on increases in 429 responses, NGINX error-log limit events, and Node.js latency separately; they indicate different problems.
  • Repeat a dry-run observation after major client, mobile-app, or API changes.
  • Protect administrative and authentication endpoints with policies appropriate to their risk rather than assuming one API-wide value fits every route.
  • When running multiple NGINX instances, understand that each instance has its own in-memory zone unless your architecture provides a shared limiting mechanism. A per-instance limit therefore may not equal one global limit for a client.

The official NGINX documentation defines the directive semantics and examples but does not publish one requests-per-second number that is safe for every Node.js workload. Treat the values in this guide as a controlled starting configuration, validate them against your own latency and error objectives, and adjust them from measured traffic rather than from a universal benchmark.

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.

Reference configuration to adapt

This compact version combines the essential pieces. Keep the zone in http {}; place the server and location in the loaded virtual-host configuration:

# /etc/nginx/nginx.conf, inside http {}
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=5r/s;

server {
    listen 80;
    server_name example.com;

    location /api/ {
        # Enable this first while observing real traffic:
        # limit_req_dry_run on;
        limit_req zone=api_limit burst=10 nodelay;
        limit_req_status 429;

        proxy_pass http://127.0.0.1:3000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

Validate with sudo nginx -t, reload only after a successful test, observe in dry-run, and then enforce. That sequence keeps syntax errors and an overly aggressive first policy from becoming an avoidable outage.

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 *

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.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
Windows Errors? Fix Them Before They SpreadFree repair scan

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.