DEV Community

Dev on Remote
Dev on Remote

Posted on

Synchronous vs Asynchronous Execution

These two terms are ones that show up the most when talking about code execution in software development.

What is the difference between synchronous and asynchronous execution?

In simple terms synchronous execution doesn't allow you to do some work while waiting for sth else to finish. Asynchronous execution allows you to do work on other task while waiting for previous to finish.

Nowadays synchronous execution isn't a preferred way.

Lets try to go a bit dipper into this topic and maybe explain it using some examples.

Synchronous Execution (old ways ;p)

  1. Caller sends a request and blocks you as a caller. You can't do anything, call any other method etc.
  2. Method gets executed. Receiver responds.
  3. You get unblocked and call a new method

This three step synchronous execution keeps the client and the server in sync. They always move synchronously.

Asynchronous Execution

  1. Caller send a request
  2. Caller can work, call other methods etc until it while not receiving a response from the receiver.
  3. Caller checks if the response was send from the receiver in the meantime by either polling and checking periodically if the response is ready, or receiver calls back when its done.

Since the caller can do other things in the meantime, its not in sync with the receiver.

Also its worth to note, that asynchronous execution doesn't mean we can't do things in order. We can.

Request Response

Request Response is a good example to use here. Everyone had a contact with it, so we won't need to use too many braincells imagining some unknown scenarios.

Most of the client libraries are asynchronous, since making them synchronous will be limiting them. Why should clients be blocked and wait for the response, when its more efficient to do some other work in the meantime?

Its like asking teacher a question in classroom. That's synchronous. You ask a question, there is a moment of pause waiting, and only then you can receive an answers. Here synchronous execution makes sense, since you don't want or can't do other things in the meantime. But looking at this from the perspective of the user in your app, it would be a terrible experience.

Example: Client sends an HTTP request and continues doing some other work, send another request etc. Once the response is send to the client some callback gets executed, like in node.js with event loop. Simple and no blocking.

But wait, isn't that actually moving a problem from the frontend client to the backend? It is, since BE will want to execute them one at the time. To make it work seamlessly we will want to use some techniques like background workers and queues.


Well, that was pretty short, but that was the goal. Cheers!

Top comments (0)