You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
NodeJS crashes when processing 50 images simultaneously #138
50 images at once is usually fine, but every now and then it cause my whole node process to crash.
I understand that what I'm trying to do is intense, but isn't there a way sharp could catch the issue and try again in the event that memory is running out or whatever happens to be causing the crash?
My cache is set to 50mb. Concurrency is default (1).
Any ideas? Or at least a way to get an error message to tell me what's going on?
Hi Tyler, the value passed to sharp.concurrency() controls the number of threads created by libvips to process each image, defaulting to the number of CPU cores. The maximum number of simultaneous images being processed is controlled by the value of libuv's process.env.UV_THREADPOOL_SIZE, also defaulting to the number of CPU cores.
You may get better throughput by either preventing multi-threading in libvips using sharp.concurrency(1) or manually adjusting the UV_THREADPOOL_SIZE environment variable.
What image formats are you using? libvips is great at minimising memory usage when processing JPEG, PNG, WebP and TIFF formats. For other inputs, such as PSD and GIF it will use libmagick, which holds the full decompressed image data in memory at once (~16 bytes per pixel). libmagick might also try to use /tmp for large images, so perhaps check that path is disk-based not RAM-based.
sharp.concurrency is set to 1 (my machine has 1 core). I haven't tweaked UV_THREADPOOL_SIZE but if it defaults to 1, then there's nothing new here for me to try. I'll doublecheck though.
Also, just so I'm clear, can you explain why a memory leak in libvips would cause node itself to crash? Was under the impression if was a child process/separate thread.
After thinking about it, I don't even think that 50 simultaneous images is an outrageous expectation. If I'm going to ship my web app to production using sharp, I need to know that someone can't crash my entire node app by giving me 50+ image uploads at once.
Again, I assumed the way that node handles IO would prevent me from having a memory leak in a native dependency cause the whole app to crash.
A single core system will process one image at a time using the default settings, with the other tasks queued. As you rightly suggest, 50 tasks is perfectly normal. One of the benchmark tests queues 128 tasks and I've run scripts that queue and process thousands of images.
"I assumed the way that node handles IO would prevent me from having a memory leak in a native dependency cause the whole app to crash"
libvips is used as a shared library in-process rather than by spawning child processes. I'm not aware of any protection offered by Node (or more specifically libuv) against memory leaks or buffer overflows for native addons.
What version of libvips are you using? I fixed a few memory leaks and a nasty buffer overflow earlier this year and would recommend at least v7.40.9.
I wonder if a specific image could be causing a problem. Are you able to share code and image samples (privately via e-mail if necessary)?
It seems likely that it's a memory issue though and not something with the images, as I can successfully get 50 images to work. The app crashes every now and then on those same images, and will consistently crash if I pass 100 images at once.
I've run the following script, which tries to match the environment you describe, against the 50 images you sent by e-mail. It reached a maximum RSS of 91MB. When run against a different directory containing 500 JPEG images it reached a maximum RSS of 130MB.
Looks like my max is about 275MB before it crashes on the 100 image test. I'm also trying to upload these images to another service, so the memory usage might vary there, but before when I was using image magick, I never had a crash (but that's using subprocesses which I'm trying to avoid).
I've been able to reproduce this, though not consistently yet. When it fails I see a vips warning: VipsJpeg: Premature end of JPEG file just before the segfault.
My best guess right now is that v8 heap compaction has kicked in and moved the Buffers but the queued task still has the old reference.
I've moved the dereference of the input Buffer to occur as soon as possible, allowing the garbage collector to free it sooner, which shaves a few MB off the Stream-based script.
Every attempt I've made at limiting process memory results in errors from within the heap allocation section of V8 code, either FATAL ERROR: heap setup Allocation failed - process out of memory or FATAL ERROR: v8::Context::New() V8 is no longer usable.
"I need to know that someone can't crash my entire node app by giving me 50+ image uploads at once."
"concurrent requests in my web app are a big deal"
The untrusted nature of the input data you plan to support on a memory-constrained system would lead me to persist to disk first. This will still allow concurrency, provide greater stability and remain faster than *magick.
The untrusted nature of the input data you plan to support on a memory-constrained system would lead me to persist to disk first. This will still allow concurrency, provide greater stability and remain faster than *magick.
I'm not sure I understand this. I thought I was persisting to disk first.
My endpoint takes the multipart upload and writes it to a file in a tmp directory. It then uses a stream to pipe the data into sharp.
I've been told that streams are much better for concurrency than trying to load an entire buffer into memory. Are you saying I should try the buffer-based approach instead?
to let libvips manage reading and writing disk-based data, something it's very good at.
Using Streams seems to result in not only the whole of the first compressed file being brought into memory but eventually the (compressed) contents of most if not all the files in the queue. The filesystem can provide data to Node.js faster than sharp can process it. Node.js doesn't apply backpressure to the filesystem as memory fills and sharp doesn't apply backpressure to Node.js as its queue grows.
A future limit option would make sharp responsible for applying backpressure when the queue reaches a given level. I'm unsure how good Node.js is at applying that backpressure upstream. From the little I've read on the topic so far, I believe it buffers it in memory, which if true is sadly the problem we're trying to avoid :sadface:
(As an aside, the concept of *nix streaming that C libraries such as libvips understand via file descriptors and the concept of Stream objects in Node.js don't quite line up. The history of how this module has managed to position itself in the middle of these two can be seen in #30.)
Ok I'll give it a shot... Is there a quick way of determining the final filesize without using fs.stat? IOW anyway that sharp can provide that info after resize/write?
Glad to hear you're making progress, excellent news.
I've added the size attribute to the info Object passed to the toFile callback. It does end up using stat internally, but as the OS has just written the file to disk, its inode data is very likely to be cached in memory so this should be about as fast as it's possible to get.
v0.8.3 is now published to npm with all the fixes and improvements we've discussed here. I've created #140 to investigate the best way to (automagically) apply backpressure.
A big thank you for alerting me to the problem where V8 heap compaction (part of garbage collection) meant that Buffers referenced by queued tasks might move without notification. I keep learning more about the internals of V8 every day!
Finally, if you're able to share details about what you're using this module for, I'd love to hear more over in the survey at #35.
Activity
lovell commentedon Dec 12, 2014
Hi Tyler, the value passed to sharp.concurrency() controls the number of threads created by libvips to process each image, defaulting to the number of CPU cores. The maximum number of simultaneous images being processed is controlled by the value of libuv's
process.env.UV_THREADPOOL_SIZE, also defaulting to the number of CPU cores.You may get better throughput by either preventing multi-threading in libvips using
sharp.concurrency(1)or manually adjusting theUV_THREADPOOL_SIZEenvironment variable.What image formats are you using? libvips is great at minimising memory usage when processing JPEG, PNG, WebP and TIFF formats. For other inputs, such as PSD and GIF it will use libmagick, which holds the full decompressed image data in memory at once (~16 bytes per pixel). libmagick might also try to use /tmp for large images, so perhaps check that path is disk-based not RAM-based.
tybenz commentedon Dec 12, 2014
Using JPG images.
sharp.concurrencyis set to 1 (my machine has 1 core). I haven't tweakedUV_THREADPOOL_SIZEbut if it defaults to 1, then there's nothing new here for me to try. I'll doublecheck though.tybenz commentedon Dec 12, 2014
Also, just so I'm clear, can you explain why a memory leak in libvips would cause node itself to crash? Was under the impression if was a child process/separate thread.
tybenz commentedon Dec 12, 2014
After thinking about it, I don't even think that 50 simultaneous images is an outrageous expectation. If I'm going to ship my web app to production using sharp, I need to know that someone can't crash my entire node app by giving me 50+ image uploads at once.
Again, I assumed the way that node handles IO would prevent me from having a memory leak in a native dependency cause the whole app to crash.
lovell commentedon Dec 12, 2014
A single core system will process one image at a time using the default settings, with the other tasks queued. As you rightly suggest, 50 tasks is perfectly normal. One of the benchmark tests queues 128 tasks and I've run scripts that queue and process thousands of images.
libvips is used as a shared library in-process rather than by spawning child processes. I'm not aware of any protection offered by Node (or more specifically libuv) against memory leaks or buffer overflows for native addons.
What version of libvips are you using? I fixed a few memory leaks and a nasty buffer overflow earlier this year and would recommend at least v7.40.9.
I wonder if a specific image could be causing a problem. Are you able to share code and image samples (privately via e-mail if necessary)?
tybenz commentedon Dec 12, 2014
I assume I have the latest version of libvips as I used sharp's preinstall script to install libvips. How do I double-check?
I can send you a zip of the images I'm using.
tybenz commentedon Dec 12, 2014
It seems likely that it's a memory issue though and not something with the images, as I can successfully get 50 images to work. The app crashes every now and then on those same images, and will consistently crash if I pass 100 images at once.
lovell commentedon Dec 12, 2014
I've run the following script, which tries to match the environment you describe, against the 50 images you sent by e-mail. It reached a maximum RSS of 91MB. When run against a different directory containing 500 JPEG images it reached a maximum RSS of 130MB.
Might you be using Buffer or Stream based input?
tybenz commentedon Dec 12, 2014
Stream-based. Here's a rough estimation of what I'm doing: https://gist.github.com/tybenz/310f37533ef90e198bad
tybenz commentedon Dec 12, 2014
Looks like my max is about 275MB before it crashes on the 100 image test. I'm also trying to upload these images to another service, so the memory usage might vary there, but before when I was using image magick, I never had a crash (but that's using subprocesses which I'm trying to avoid).
lovell commentedon Dec 12, 2014
I've been able to reproduce this, though not consistently yet. When it fails I see a
vips warning: VipsJpeg: Premature end of JPEG filejust before the segfault.My best guess right now is that v8 heap compaction has kicked in and moved the Buffers but the queued task still has the old reference.
13 remaining items
Move unref of input Buffer to C++ #138
lovell commentedon Dec 14, 2014
I've moved the dereference of the input Buffer to occur as soon as possible, allowing the garbage collector to free it sooner, which shaves a few MB off the Stream-based script.
Every attempt I've made at limiting process memory results in errors from within the heap allocation section of V8 code, either
FATAL ERROR: heap setup Allocation failed - process out of memoryorFATAL ERROR: v8::Context::New() V8 is no longer usable.The untrusted nature of the input data you plan to support on a memory-constrained system would lead me to persist to disk first. This will still allow concurrency, provide greater stability and remain faster than *magick.
tybenz commentedon Dec 14, 2014
I'll give it another shot.
I'm not sure I understand this. I thought I was persisting to disk first.
My endpoint takes the multipart upload and writes it to a file in a tmp directory. It then uses a stream to pipe the data into
sharp.I've been told that streams are much better for concurrency than trying to load an entire buffer into memory. Are you saying I should try the buffer-based approach instead?
lovell commentedon Dec 14, 2014
Ah, sorry, I've just taken another look at the gist you posted a couple of days ago. Apologies, I should have done this sooner, my fault.
Given you're reading from and writing to disk, perhaps try replacing
with something along the lines of
to let libvips manage reading and writing disk-based data, something it's very good at.
Using Streams seems to result in not only the whole of the first compressed file being brought into memory but eventually the (compressed) contents of most if not all the files in the queue. The filesystem can provide data to Node.js faster than sharp can process it. Node.js doesn't apply backpressure to the filesystem as memory fills and sharp doesn't apply backpressure to Node.js as its queue grows.
A future
limitoption would make sharp responsible for applying backpressure when the queue reaches a given level. I'm unsure how good Node.js is at applying that backpressure upstream. From the little I've read on the topic so far, I believe it buffers it in memory, which if true is sadly the problem we're trying to avoid :sadface:(As an aside, the concept of *nix streaming that C libraries such as libvips understand via file descriptors and the concept of Stream objects in Node.js don't quite line up. The history of how this module has managed to position itself in the middle of these two can be seen in #30.)
tybenz commentedon Dec 15, 2014
Ok I'll give it a shot... Is there a quick way of determining the final filesize without using
fs.stat? IOW anyway that sharp can provide that info after resize/write?tybenz commentedon Dec 15, 2014
Went ahead and tried it with
fs.statto retrieve file size. Works like a charm! Need to put under some more serious load, but major improvement!Add 'size' attribute to callback's info Object #138
lovell commentedon Dec 15, 2014
Glad to hear you're making progress, excellent news.
I've added the
sizeattribute to theinfoObject passed to thetoFilecallback. It does end up usingstatinternally, but as the OS has just written the file to disk, its inode data is very likely to be cached in memory so this should be about as fast as it's possible to get.tybenz commentedon Dec 15, 2014
Great! I tested the
sizechange by installing from git. Looks great. Let me know when you release it to npm.lovell commentedon Dec 15, 2014
v0.8.3 is now published to npm with all the fixes and improvements we've discussed here. I've created #140 to investigate the best way to (automagically) apply backpressure.
A big thank you for alerting me to the problem where V8 heap compaction (part of garbage collection) meant that Buffers referenced by queued tasks might move without notification. I keep learning more about the internals of V8 every day!
Finally, if you're able to share details about what you're using this module for, I'd love to hear more over in the survey at #35.
lovell commentedon Jan 5, 2015
@tybenz Is everything working OK for you now?
tybenz commentedon Jan 5, 2015
It is indeed! Thanks so much for the help!