Learn Node.js in about a week!
Learning should be fun and quick; no need to spend ages in just one single course.
What exactly is highWaterMark in Node.js streams?
An indispensable safety mechanism and an extremely useful setting to use with streams.
Streams are one of the most important and pervasive concepts in Node.js. Many built-in APIs in Node rely on streams to support quick and efficient transfer of data chunks.
Now, when it comes to streams, there's this useful concept referred to as a highWaterMark. In this article, I'll share with you with exactly is it and how and when to configure it.
A quick review of streams
Let's first quickly review the idea of a stream in Node. Basically, a stream is a flow of small chunks of data. Just like you have a stream of water, so is a stream in Node except that it is for data (not for water).
The most primitive concept pertaining to a stream is that of a chunk which is just a small unit of data.
The rationale behind breaking down a large reservoir of data into multiple, small chunks is to prevent overwhelming the memory. For example, in an HTTP server setup, if the user requests a 1GB video file, then one option is to load that file entirely in memory and then forward it to the client. Certainly, this is undesirable.
A stream allows you to forward this 1GB file while making sure that the memory usage doesn't actually touch 1GB. The file is broken into small chunks (each typically a few KBs to maybe a few MBs), and each chunk is loaded in memory and forwarded to the client in succession.
What is highWaterMark?
By design, as you learned above, streams are built to prevent memory over-consumption issues due to unbounded loading or accumulation of data. So it's no surprise to know that streams in Node.js come with a safety mechanism in place to prevent such a scenario.
This safety mechanism is called highWaterMark. Let's understand how it works...
Both readable and writable streams in Node internally maintain a buffer.
- A readable stream reads data from its source and dumps the read data into this buffer before handing it over to its consumer.
- A writable stream has data from the producer first written into this buffer after which it's forwarded to the underlying destination.
Now, in some cases, these internal buffers can start to accumulate large amounts of data. To prevent this accumulation from clogging up memory and rendering the usage of streams useless, Node uses highWaterMark.
highWaterMark specifies a threshold limit, in number of bytes, for the size of the internal buffer of a stream. Different stream implementations have different limits depending on the nature of the underlying source or destination.
For example, file-related readable and writable streams — the ones created using createReadStream() and createWriteStream() — have a default highWaterMark value of 64KB (at the time of this writing).
highWaterMark indirectly also specifies the size of each chunk that's read from or written to a file. So, if highWaterMark is 64KB (the default), then each chunk read from a file will be 64KB (or less if the file's data ends before that) in size.Examples of when to configure highWaterMark?
Node makes it really easy for you to configure highWaterMark for any stream. In fact, built-in stream implementations, such as the createReadStream() function provided by the node:fs module, also allow you to configure it.
The question is: When to configure highWaterMark?
Really simple: you should configure highWaterMark depending on whether you want to increase the threshold limit for the underlying buffer's size or decrease it. And, of course, this depends on the underlying application. Let me present two examples to you.
Fewer filesystem calls for read
First, consider reading a file using the createReadStream() function discussed before. By default, highWaterMark is 64KB so each chunk that is read by Node is 64KB (or less) in size. Now, each chunk makes a separate filesystem call and that obviously carries overhead.
You might decide beforehand to increase the chunk size in order to issue fewer system calls and, as a result, improve the performance of the read. You can easily do so by raising the highWaterMark limit.
The code below, for instance, configures this limit to 512KB (which means that there will now be fewer filesystem calls made as each chunk is bigger than before):
import { createReadStream } from 'node:fs';
let rs = createReadStream(
'./some-large-file.txt',
{ highWaterMark: 512 * 1024 }
);Over to the second example.
A fast read source
Consider a scenario where you're reading in data from a source and passing it over to a writable stream in order to write to an underlying destination. Also suppose that the read source is something you can't control and it produces huge bursts of data for a short period of time.
In this case, a low value for highWaterMark means that you have to mostly pause writing to the writable stream and wait for a 'drain' event to be emitted before you can resume writing. This might not be feasible because your data source is continuously providing data to you.
In this case, raising the highWaterMark would allow you to buffer all those bursts of data in memory and not have wait for any pause/resume cycles on the writable stream.
The special value 0
One last thing I want to share with you is that Node considers 0 to be a special value for highWaterMark. So what's special about it?
you ask. Good question.
A highWaterMark of 0 means that NO buffering is to be done — as soon as data is obtained, it must be handed immediately over to the consumer (for a readable stream) or written to the underlying destination (for a writable stream).
Moreover, a highWaterMark of 0 also ensures that NO extra reading is done by a readable stream prior to being requested for it. The following snippet elaborates on this phenomenon.
What is meant by extra buffering?
By default, readable streams in Node are designed to pre-load extra data to hand over to the consumer later when needed. This is done to improve the performance of readable streams.
So, for example, if you ask a readable stream for 10 bytes of data, it will read the underlying source and hand over the read data to you but also automatically load more data on the next tick without you having to manually ask for it.
More often than not, this behavior is desirable. However, in some cases, like reading from the terminal, it can be problematic — you certainly wouldn't want Node to ask for surplus inputs from the user in the terminal! In these cases, the solution is to set highWaterMark to 0.
Internally, Node uses highWaterMark: 0 in multiple places. Take the example of reading from or writing to the terminal.
For this, you use process.stdin and process.stdout, respectively, both of which are streams. These streams (when they are connected to the terminal) are initialized by Node with a highWaterMark of 0.
This highWaterMark value ensures that data is read only when required to be read (and no extra reads are performed) and that when data is written to the terminal, it's written immediately without any buffering.