Skip to content

NodeJS crashes when processing 50 images simultaneously #138

Closed

Description

@tybenz

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?

Activity

  1. lovell commented on Dec 12, 2014

    @lovell
    Owner

    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.

  2. tybenz commented on Dec 12, 2014

    @tybenz
    Author

    Using JPG images.

    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.

  3. tybenz commented on Dec 12, 2014

    @tybenz
    Author

    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.

  4. tybenz commented on Dec 12, 2014

    @tybenz
    Author

    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.

  5. lovell commented on Dec 12, 2014

    @lovell
    Owner

    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)?

  6. tybenz commented on Dec 12, 2014

    @tybenz
    Author

    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.

  7. tybenz commented on Dec 12, 2014

    @tybenz
    Author

    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.

  8. lovell commented on Dec 12, 2014

    @lovell
    Owner

    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.

    process.env.UV_THREADPOOL_SIZE = 1;
    
    var fs = require('fs');
    var sharp = require('sharp');
    
    sharp.concurrency(1);
    sharp.cache(50);
    
    var maxRss = 0;
    
    fs.readdirSync('./138').forEach(function(filename) {
    
      sharp('./138/' + filename).resize(1024, 576).toBuffer(function(err, data, info) {
        if (err) {
          console.log(err);
        } else {
          console.dir(info);
          console.dir(sharp.counters());
          if (process.memoryUsage().rss > maxRss) {
            maxRss = process.memoryUsage().rss;
            console.log(maxRss);
          }
        }
      });
    
    });

    Might you be using Buffer or Stream based input?

  9. tybenz commented on Dec 12, 2014

    @tybenz
    Author
  10. tybenz commented on Dec 12, 2014

    @tybenz
    Author

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

  11. lovell commented on Dec 12, 2014

    @lovell
    Owner

    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.

  12. 13 remaining items

  13. lovell commented on Dec 14, 2014

    @lovell
    Owner

    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.

  14. added and removed on Dec 14, 2014
  15. tybenz commented on Dec 14, 2014

    @tybenz
    Author

    I'll give it another shot.

    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?

  16. lovell commented on Dec 14, 2014

    @lovell
    Owner

    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

    var write = fs.createWriteStream( newPath );
    var transform = sharp().resize( newWidth, newHeight ).quality( 80 );
    var stream = fs.createReadStream( file.path ).pipe( transform ).pipe( write ); 

    with something along the lines of

    sharp( file.path ).resize( newWidth, newHeight ).quality( 80 ).toFile( newPath , function( err, info ) {
      resolve( ... );
    });

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

  17. tybenz commented on Dec 15, 2014

    @tybenz
    Author

    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?

  18. tybenz commented on Dec 15, 2014

    @tybenz
    Author

    Went ahead and tried it with fs.stat to retrieve file size. Works like a charm! Need to put under some more serious load, but major improvement!

  19. lovell commented on Dec 15, 2014

    @lovell
    Owner

    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.

  20. tybenz commented on Dec 15, 2014

    @tybenz
    Author

    Great! I tested the size change by installing from git. Looks great. Let me know when you release it to npm.

  21. lovell commented on Dec 15, 2014

    @lovell
    Owner

    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.

  22. lovell commented on Jan 5, 2015

    @lovell
    Owner

    @tybenz Is everything working OK for you now?

  23. tybenz commented on Jan 5, 2015

    @tybenz
    Author

    It is indeed! Thanks so much for the help!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions