Besides setting a maximum request limit, there may be situations where we would like to slow down response such that it sends a chunk every x
milliseconds. This can be useful when testing slow connections.
Usually, you will want to limit file uploads because it wouldn't be relevant to throttle a JSON response of 20 KB.
There are several NPM modules that do throttling, such as slow-stream
and throttle
. Let's say we have a file attached to a note and want to send a 64-byte chunk at a time, each 100 milliseconds, using slow-stream
, as follows:
streamFromDatabaseOrFileSystem('note-attachment-asdAsd21j3o8uad', { bufferSize: 64 }) .pipe(new SlowStream({ maxWriteInterval: 400 })) .pipe(res);
Both the modules mentioned work with streams, as you can see from the preceding example. The
slow-stream
module can also handle back pressure, so if we're dealing with a proper implemented stream, we won't have memory leaks.