Avoid sync in servers
Freezing
fs.readFileSync or crypto.pbkdf2Sync) is considered a critical anti-pattern. Because Node.js is single-threaded, these functions can effectively "freeze" your entire application.1. The "Freezing" Effect
When you call a Synchronous function, it blocks the Event Loop. Since the Event Loop is responsible for handling all incoming requests, timers, and database responses, everything stops until that one file operation or calculation is finished.
The Scenario
Imagine you have a web server where:
User A requests a very large file, and your code uses
fs.readFileSync.User B tries to load the homepage (a tiny request).
In a Synchronous setup: User B must wait for the server to finish reading the entire file for User A before the server even acknowledges User B's request. To User B, the site appears to be down or extremely laggy.
2. Synchronous vs. Asynchronous Performance
| Feature | Synchronous (Sync) | Asynchronous (Async/Await) |
| Event Loop | Blocked until the task finishes. | Free to handle other tasks. |
| Throughput | Handles 1 request at a time. | Handles thousands of concurrent requests. |
| Usage | Fine for CLI tools or startup scripts. | Mandatory for web servers/APIs. |
| Error Handling | Uses try/catch. | Uses try/catch with await |
3. Real-World Impact: The "Stop the World" Problem
If your server handles 100 requests per second and you execute a sync operation that takes 200ms:
The Event Loop stops for 200ms.
100-200 incoming requests are now backed up in the system kernel.
Once the sync task finishes, the server is suddenly hit with a massive "tidal wave" of pending requests, often leading to a crash or high CPU spikes.
4. Exceptions: When is Sync okay?
There are very few cases where Sync methods are acceptable:
Initial Startup: Loading a configuration file (
config.json) exactly once when the server starts up. Since no users are connected yet, blocking for a few milliseconds doesn't matter.CLI Scripts: One-off automation scripts where you don't care about concurrency.
Heavy Debugging: Occasionally used during local debugging to ensure a specific execution order without dealing with promises.
5. The Solution: Transitioning to Async
If you are currently using sync methods, you should refactor them to use fs.promises or standard callbacks.
Bad (Blocking):
app.get('/data', (req, res) => {
const data = fs.readFileSync('large-file.json'); // Entire server stops here!
res.send(data);
});Good (Non-Blocking):
app.get('/data', async (req, res) => {
try {
const data = await fs.promises.readFile('large-file.json'); // Event loop stays free
res.send(data);
} catch (err) {
res.status(500).send("Error reading file");
}
});Summary
To build a scalable server in Node.js, you must respect the Single Thread. Offload heavy work (I/O, hashing, compression) to the asynchronous APIs so the Event Loop can keep spinning and serving your users.