27 October was a bad day for threads.

By the evening I had fixed two bugs that came from the same place: my code was starting more threads than my hosting would allow, and the hosting was killing it without saying why.

Bug 1: a share image that returned 503

My Laravel app makes share images on the server. It builds an SVG and turns it into a PNG with Imagick, which uses librsvg under the hood.

The new design had a blur filter. On my laptop it rendered fine. On the live site the page died, and the CDN showed a 503.

Works on my machine

The cause: librsvg draws blur filters on a thread pool, and the pool is sized to the number of CPUs. On a shared server that's a lot of CPUs. My hosting caps processes and threads per account, so one web request trying to start dozens of threads got killed.

The fix was one environment variable, set before rendering:

// librsvg draws blur filters on a thread pool sized to the CPU count; the hosting caps // processes and threads per account, so a request that spawns dozens of threads is killed. // One thread is plenty. putenv('RAYON_NUM_THREADS=1'); 

librsvg is written in Rust and uses the Rayon library for parallel work, and Rayon reads RAYON_NUM_THREADS. One thread renders a share card fast enough.

Then the 503 wouldn't go away

The fix was live, but the image still showed a 503. The CDN had cached the error from the broken deploy and kept serving it for that image URL.

So now image URLs carry a version number, and I bump it after a design change. A new URL means the CDN has to fetch a fresh copy.

Bug 2: 60 threads asking for 7 GB

The same day, a nightly scheduled job started failing with:

mmap() failed: [12] Cannot allocate memory 

The job does a lot of lookups in parallel: HTTP and DNS, 60+ threads at once. It didn't use much real memory. But glibc gives each thread its own malloc arena, and each one reserves 64 MB of address space. 60 threads reserved about 7 GB. My hosting puts a ceiling on virtual memory, not just real memory, and refused.

Anchorman: boy, that escalated quickly

The fix was another environment variable, set when the scheduler starts:

MALLOC_ARENA_MAX=2 

That caps glibc at 2 arenas shared by all threads. The job now finishes under a 1.5 GB ceiling. I also keep parallel HTTP pools at 12 or fewer.

What both bugs had in common

Neither one was a bug in my code. Both were defaults that make sense on your own machine (use every CPU, give every thread its own memory) and fall over on a server with strict limits.

And neither one failed loudly. One showed a 503 from a CDN. The other showed a memory error that wasn't about memory I was using.

What's the strangest limit you've hit on shared hosting or a small server?