Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversHalloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon 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 Prepare a Node.js and MongoDB Server for Heavy Traffic

Learn how to prepare a Node.js and MongoDB deployment for heavy traffic with measured connection pools, stateless application processes, production replica sets, resilient retries, query-focused indexes, monitoring and a clear vertical-scaling versus sharding decision.
Length10 min Posted Quest giverVGSources Team

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.

Prepare Node.js and MongoDB as separate scaling tiers: run several stateless Node.js processes behind a load balancer, keep one shared MongoClient per process, cap connection wait queues, and operate MongoDB as a production replica set. Add indexes for real query patterns, measure event-loop and database saturation, and load-test before increasing capacity. Scale a single deployment vertically while its data and write load fit one server; move to sharding only when the dataset or write demand exceeds that limit and you can select a shard key that distributes work.

Start with a two-tier architecture

A busy service should have an application tier and a database tier with independent capacity and failure controls. A typical request path is:

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.
  1. Clients connect to a load balancer.
  2. The load balancer distributes requests among multiple Node.js processes or containers.
  3. Each process reuses one long-lived MongoDB driver client.
  4. A MongoDB replica set serves reads and writes, with durability and election behavior chosen explicitly.

Do not treat “more Node.js workers” as a database scaling plan. Every process can create its own pool of database connections, so adding workers increases MongoDB connection pressure unless pool limits are recalculated.

What must be shared outside a process

Processes behind a load balancer are stateless from the routing layer’s perspective. Store sessions, rate-limit counters, job state, upload metadata, and caches in shared infrastructure rather than process memory. Otherwise, a request routed to a different worker can appear unauthenticated or lose intermediate state. If you require sticky sessions, document why and understand that they reduce the load balancer’s freedom to redistribute traffic during failure.

Measure before adding workers

Capture request rate, p50, p95 and p99 latency, error rate, CPU saturation, memory pressure, garbage-collection behavior, and event-loop delay. Add workers when the event loop or CPU is the bottleneck and the database still has headroom. If database latency or connection queues are already high, more workers can make the outage worse.

#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.

Build the Node.js application tier for concurrency

Use multiple processes or containers

Node.js documents the cluster module for running multiple processes that share a server port. In production, the more flexible pattern is several processes or containers behind a load balancer, allowing independent health checks, rolling replacement, and horizontal capacity changes. Keep request handlers asynchronous; synchronous CPU-heavy work blocks the event loop for every request handled by that process.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import http from 'node:http';
import { MongoClient } from 'mongodb';

const client = new MongoClient(process.env.MONGODB_URI, {
  maxPoolSize: 120,
  waitQueueTimeoutMS: 500,
  monitorCommands: false
});
await client.connect();
const db = client.db(process.env.MONGODB_DB);

const server = http.createServer(async (req, res) => {
  // Keep handlers asynchronous and apply per-operation time limits.
  const rows = await db.collection('items')
    .find({ active: true }, { maxTimeMS: 1000 })
    .limit(50)
    .toArray();
  res.setHeader('content-type', 'application/json');
  res.end(JSON.stringify(rows));
});

server.listen(process.env.PORT || 3000);

The example values are illustrative, not universal targets. Choose pool and timeout values from measured concurrency, query duration, and the number of processes.

Use readiness and liveness separately

A liveness check should answer whether the process can be restarted; it should not fail merely because MongoDB is temporarily electing a primary. A readiness check can remove a process from service when its database dependency is unavailable or its event loop is overloaded. During startup, mark the process unready until the shared client has connected and required indexes or migrations are confirmed.

Bound work during spikes

  • Set request deadlines and reject work that cannot complete within the caller’s useful time window.
  • Limit request-body size and concurrent uploads.
  • Use a bounded queue for noninteractive work; return a clear overload response rather than allowing unbounded memory growth.
  • Apply rate limits per account, token, IP range, or other abuse-resistant identity.
  • Cache safe, frequently requested results to reduce repeated database reads.

Size MongoDB connection pools correctly

“A connection pool is a cache of open database connections maintained by Node.js driver.” The driver maintains a pool for each server in the MongoDB topology. The current driver default for maxPoolSize is 100 connections per server pool. waitQueueTimeoutMS defaults to 0, which means operations can wait indefinitely for a pooled connection unless you set a limit.

Create one long-lived client per process

Create the MongoClient once during process startup and reuse it. Opening a client per request creates connection churn, TLS and authentication overhead, and unpredictable bursts against MongoDB. Close the client only during graceful shutdown.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
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

Account for topology-wide sockets

A three-node replica set can add six monitoring sockets for one MongoClient. Application sockets are in addition to those monitoring connections. If you run 10 application processes, each with a pool of 100 connections per server, the theoretical aggregate can be far larger than 1,000 sockets because the pool is maintained per server in the topology. Check the driver’s current topology behavior and observe actual connection counts rather than relying on a simple process-times-pool multiplication.

Use the 110–115% figure only as a starting point

MongoDB’s production checklist suggests beginning with 110–115% of typical concurrent database requests, then measuring and adjusting. This is a heuristic, not a guaranteed capacity number. “Typical concurrent requests” must come from your own workload, not peak requests per second divided by an assumed latency.

Setting Documented default or guidance Operational implication
maxPoolSize 100 connections per server pool Each process can open up to this many pooled connections to each server; aggregate limits across processes and hosts.
waitQueueTimeoutMS 0 (no wait limit) Set a finite value so overload fails or sheds work predictably instead of accumulating indefinitely.
Initial sizing heuristic 110–115% of typical concurrent database requests Use only for an initial test, then tune from queue time, latency, errors, and database capacity.
Replica-set monitoring Six additional monitoring sockets for one three-node topology Include monitoring connections when budgeting file descriptors and network capacity.

Choose a bounded wait policy

A finite waitQueueTimeoutMS turns pool exhaustion into a controlled failure. Return a retryable response or enqueue work elsewhere when the timeout expires. A very short value can reject legitimate bursts; a very long value merely moves the queue into your application and inflates tail latency. Tune it alongside endpoint deadlines and the database’s observed service time.

Prevent connection storms

Use exponential backoff with jitter when reconnecting after a network fault or election. Do not have every process retry immediately in a tight loop. During deployments, stagger process startup or use a connection ramp so a full fleet does not establish all pools at once.

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

Design collections and indexes for the real workload

MongoDB creates only the _id index automatically. Every other index must be created deliberately. Start with the dominant filter, sort, and equality/range patterns in your application, then verify them against production-shaped data.

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)

Build indexes from access paths

  1. List the most frequent and most latency-sensitive queries, including their filters, sort order, and limits.
  2. Create the smallest compound indexes that support those patterns; place fields according to the equality, sort, and range behavior of the query.
  3. Run explain and confirm that the winning plan examines an appropriate number of keys and documents.
  4. Recheck plans after data growth, schema changes, and major version upgrades.
  5. Remove indexes that serve no real query or impose more write and storage cost than their benefit justifies.

An index can reduce read work while increasing write amplification and memory use. Indexing every field is not a scalability strategy.

Keep the working set in memory when possible

MongoDB performance depends heavily on whether frequently accessed data and indexes fit in available physical memory. If the working set regularly spills to storage, disk latency becomes part of request latency. Measure cache behavior, disk latency, and I/O operations before deciding that more application workers are needed.

Fix schema problems before hardware escalation

MongoDB identifies ineffective indexes, poor schema design, insufficient hardware capacity, and excessive connections as common causes of degraded performance. Review document growth, unbounded arrays, repeated large payloads, and access patterns that require scanning many documents. A schema that matches the dominant reads can postpone an expensive scaling change.

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

Use a replica set for production availability

For an election-resilient production deployment, MongoDB’s checklist recommends at least three data-bearing voting members. Configure writes with w: "majority" when the durability requirement justifies the associated acknowledgment cost. A single node cannot elect a replacement if it fails; a replica set provides redundancy but does not remove the need for backups and recovery testing.

Handle elections and transient errors

Primary elections interrupt some operations. The application must recognize transient read and write errors, retry only operations that are safe to retry, and use exponential backoff. A retryable write can be attempted according to the driver’s retry rules; a non-idempotent application action may need an idempotency key or a durable command record before retrying.

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

Bound database operations

Set maxTimeMS on reads that must not consume unlimited server work. Use wtimeout on writes when an acknowledgment deadline is more useful than waiting indefinitely. These limits should be consistent with the endpoint’s overall deadline, leaving time for serialization and response delivery.

Separate read distribution from consistency

Primary reads provide the simplest consistency model. Routing reads to secondaries can distribute load, but introduces replication-lag visibility and read-preference decisions. Use secondary reads only for operations that tolerate the chosen staleness; do not route user-visible, immediately-after-write reads there without an explicit consistency design.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Choose vertical scaling or sharding deliberately

When vertical scaling is the right next step

Increase CPU, memory, storage capacity, or IOPS while one deployment still contains the dataset and can serve the write load. Vertical scaling is operationally simpler: fewer moving parts, no shard-key design, and easier query routing. Atlas production guidance treats cluster size and topology, storage capacity, and IOPS as foundational production choices. Measure which resource is saturated before paying for a larger machine.

When sharding becomes necessary

Use sharding when the dataset exceeds one server’s capacity or write demand must be distributed among multiple mongod instances. For write-heavy applications, MongoDB’s performance guidance recommends deploying sharding and adding one or more shards to distribute load.

Choose a shard key that avoids hotspots

A useful shard key spreads writes and storage while preserving common query patterns. A monotonically increasing key can funnel new writes to one shard; a highly random key can distribute writes but force scatter-gather queries if common lookups do not include it. Analyze cardinality, frequency, monotonicity, and the proportion of requests that include the candidate key. A poor key can make a sharded cluster slower and harder to rebalance than a well-sized replica set.

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.
Decision Prefer it when Main trade-off
Vertical scaling Data and write load fit one deployment and one resource is clearly saturated. Simpler operations, but there is a ceiling on one server’s capacity.
Sharding Data or write demand exceeds one server and a distributing shard key is available. More capacity, but more routing, balancing, and key-design complexity.
Primary-only reads Freshness and straightforward consistency matter most. The primary carries all read traffic.
Secondary reads Some reads tolerate replication lag and can be distributed. Results may be stale and behavior is more complex during lag or failover.

Instrument both driver and database behavior

The Node.js driver exposes command, server-discovery-and-monitoring, and connection-pool events. Command monitoring is disabled by default; enable it with monitorCommands: true when the diagnostic value outweighs event volume and sensitive-data concerns.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const client = new MongoClient(uri, { monitorCommands: true });
client.on('commandStarted', event => {
  // Record command name and duration context; avoid logging sensitive values.
});
client.on('connectionPoolCreated', event => {
  // Tag metrics by process, host and pool.
});

Track these signals together

  • Application request rate, status-code error rate, and p50/p95/p99 latency.
  • Event-loop delay, CPU saturation, heap usage, garbage-collection pauses, and process restarts.
  • Pool size, checked-out connections, wait-queue timeouts, connection creation and closure rates.
  • MongoDB operation execution time, slow operations, disk latency, IOPS, cache pressure, and replication lag.
  • Primary elections, transient errors, write acknowledgment time, and per-endpoint timeout counts.

Investigate sudden connection growth separately from legitimate traffic growth. MongoDB notes that unusually high connections without corresponding workload can indicate a driver or configuration error, such as creating clients repeatedly or multiplying pools during a deployment.

Prepare for a traffic spike

Before the spike

  • Run load tests with production-shaped documents, indexes, read/write ratios, and concurrency.
  • Pre-warm application instances and verify that readiness checks remove unhealthy instances.
  • Confirm pool limits, wait-queue deadlines, endpoint timeouts, and rate limits are finite.
  • Verify replica-set failover behavior and backup restoration, not just steady-state success.
  • Set alerts on tail latency, event-loop delay, pool waits, replication lag, disk latency, and error rate.

During the spike

  1. Check whether the bottleneck is Node.js CPU/event-loop delay, pool exhaustion, MongoDB CPU, memory, disk, or replication.
  2. If Node.js is saturated and MongoDB has headroom, add processes or instances gradually.
  3. If pools are waiting while MongoDB is saturated, do not add workers; shed or defer work and protect interactive endpoints.
  4. Disable expensive optional features, reduce result sizes, and serve cached responses where correctness permits.
  5. Watch connection counts after every capacity change to detect a pool multiplication problem.

After the spike

Compare observed concurrency, query plans, pool waits, and resource saturation with your capacity model. Remove emergency limits only after latency and error rates remain stable. Record which endpoint, index, pool, or infrastructure limit was reached so the next load test exercises the actual failure mode.

A practical production checklist

  • Multiple stateless Node.js processes or containers run behind a health-aware load balancer.
  • Sessions, caches, queues, and other shared state live outside individual processes.
  • One long-lived MongoClient is reused per process.
  • maxPoolSize is based on measured concurrency and aggregate process count.
  • waitQueueTimeoutMS, request deadlines, maxTimeMS, and appropriate wtimeout values bound work.
  • Indexes match real filters and sorts, and query plans are checked with explain.
  • The working set, storage latency, and IOPS are monitored as data grows.
  • The production database has at least three data-bearing voting members when election resilience is required.
  • Writes use majority acknowledgment where durability requirements justify it.
  • Transient election errors are retried with backoff and idempotency safeguards.
  • Read preference reflects freshness requirements rather than capacity assumptions.
  • Sharding is postponed until one deployment’s data or write capacity is exceeded and a tested shard key is available.
  • Driver events and application, database, and infrastructure metrics are correlated in one dashboard.
  • Workload-specific load tests establish capacity; no universal requests-per-second or latency figure is assumed.

How to document the scaling decision

Before changing topology, write down the workload assumptions: region, data size and growth, read/write ratio, peak concurrency, consistency requirements, acceptable recovery point and recovery time, and the largest tolerated tail latency. Record whether each number is measured, estimated, or a temporary limit. This makes a vertical resize, a new application tier, a secondary-read policy, or sharding an auditable decision rather than a reaction to one graph.

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.

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

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
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

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.