Async in Codebase: When to Use and When to Stick with Sync

If async is "faster," why isn't our entire codebase asynchronous? It helps make waiting more efficient. → Need to wait for a database call? Go async. → Calling an external API? Make it async. → Executing your own logic without any waiting? Stick with sync. More async simply means: → More promises to manage → more things that can silently break → Code that becomes harder to follow and understand Async is a tool for handling waiting scenarios. not a solution to everything. #BackendDevelopment #JavaScript #SoftwareEngineering #SystemDesign #NodeJS #WebDevelopment #Programming #TechTips #Developer #CleanCode #CodingLife #SoftwareDevelopment #API #Tech #LearnToCode

  • graphical user interface, text, application

Hmmm that's not entirely accurate. That depends a lot on the async runtime and the short answer is that you SHOULD make a lot more things async if you care about performance. For example let's consider nodejs or tokio. Tokio is like a super beefed up nodejs runtime with a lot more features. But they both are beholden to the same principle. If you do a lot of heavy computation, that will block the main worker thread entirely. The longer the thread is blocked, the more work piles up. All the db calls and other IO that you were waiting for will be ready, and there will be a backlog of callbacks that can't run because the whole thread is blocked with your computation. In NodeJS if you need to do heavy computation you should use something like worker threads (https://nodejs.org/api/worker_threads) or some higher level library that wraps it. Tokio has a nicer API with spawn_blocking which moves the block of code to be run on a thread from a threadpool managed by tokio. Alternatively you could try to manage the task interleaving yourself. The way you can do this in node/tokio is by yielding back to the runtime a lot. If you have some really long loop for example, you might yield every 100th iteration or something like that.

Async itself isn't fast, it makes code faster when there's multiple promises to resolve so you wait for them all together instead of awaiting one by one. for example, if there's 4 database queries in one request, it'll take longer if you resolve and await them one by one. But you can use promise.all to await for all queries asynchronously so they don't have to wait for each other.

Async isn't necessarily faster. Infact if applied incorrectly it makes it slower. Also, in ts you can use void ;-)

Like
Reply
See more comments

To view or add a comment, sign in

Explore content categories