Next.js Discord

Discord Forum

CPU heavy server-side function blocks the entire app

Unanswered
Harlequin Duck posted this in #help-forum
Open in Discord
Harlequin DuckOP
I have a function that does a bunch of complex stuff. It has a very huge loop does a bunch of recursive calls and more, but no IO bound stuff.
The function itself takes a few seconds to run.
If I call this function in a Server-Action my entire next-App gets blocked, meaning if I open new tabs in the browser they all keep loading until the currently running server function is done.
Any Ideas?
I tried to use nodes worker threads, but did not get a working import path in *new Worker("path"). I guess nexts build looks different then my directory.
Could I maybe make an API Route that executes this function and somehow tell next.js to create a thread for each request?

9 Replies

actually it is not Next.js but Node.js, which is single thread event loop designed for I/O bound application although some of cpu intensive logic such as crypto, worker threads runs in libuv os thread.
in my case cpu intensive codes are offloaded to Go and Rust upstream servers
You can offload to an api, just keep in mind that if you’re hosting it on vercel you’ll be limited to 60s of run time on a pro plan
Consider using something like fly.io or ec2 if you need a server for long running operations
or, not recommended but u can spin up multiple processes/instances using k8s or something.
vercel aws lambda might work in that point
Or just aws lambda
And increase the resources it’s allocated. They can run for a max of 15 minutes, which is typically enough
Harlequin DuckOP
Thank you, guys. :)
Yes, I will offload to an API. It's probably bad practice to have business logic in the next.js app anyway.