Sync/Async Programming
In this blog, I try to explain best what synchronous and asynchronous programming is.
If a caller sends a message to a receiver and is waiting for a response, can it do something else? I am saying a caller/receiver instead of a server/client, as these calls happen everywhere. By design, when we first built computing, everything was synchronous. This can be seen as a sine wave where a caller and a server are in sync or the same rhythm. Asynchronous means they are not in sync.
Synchronous I/O
The caller sends the request to the receiver and then blocks it. This is when the caller is blocked, not doing anything, and hence a total time waste. In the old days, the CPU removed the process from the processor, thinking it is just blocked, and added a new process that is not blocked (Context switching). So the caller cannot execute in the meanwhile. Finally, when the receiver responds, the Operating system can put the process back to the processor. Hence the caller unblocks. This shows how the client and the server are entirely in sync.
Example of OS Synchronous I/O:
1. Program asks the CPU to read a file from the disk.
2. Program’s main thread is taken off the CPU.
3. Read completes, and the program starts executing again.
// A simple Js example
// Program starts
// Programs uses CPU to execute work.
SampleFunction();
// Program reads from the disk
// Program can't do anything until file loads
readfile("SyncExample.dat")
// Program resumesAsynchronous I/O
The caller sends the request to the receiver and can work until it gets the response. But now the main question is how to know when it gets the response. Here are two choices,
a) The caller can check when the response is ready. This is very popular in Linux, known as epoll. This is where the caller checks again and again if the response is ready.
b) The receiver calls back when it's done. This is where in windows, there are I/O completionist ports (IOCP), or in Linux, it is io-uring. It works on the mechanism of a completionist queue where the receiver writes when the things are done.
Talking specifically from the point of NodeJs, it uses epoll in Linux, and in the case of windows, it uses a completionist stack. Another thing that nodeJs does is spins up a new thread that blocks in case something requires to do a blocking operation. By default, Nodejs has 4 worker threads in libuv library, which it uses for I/O operations, but it's configurable.
Get Manav Garg’s stories in your inbox
Join Medium for free to get updates from this writer.
Example of an OS asynchronous call (NodeJS)
a) Program spins up a secondary thread
b) the Secondary thread reads from the disk. Obviously, OS removes from the current processor
c) the Main program still runs and executes.
d) Thread finishes and calls the main thread.
// A simple Javascript example
// Program starts
// Programs uses CPU to execute work.
SampleFunction();
// Program reads from the disk
// Program hapilly moves on to the samplefunction2
readfile("SyncExample.dat", onReadFinish(console.log))
//file is not probably read yet
SampleFunction2();
//onReadFinish function called
// executing itSynchronous v/s Asynchronous in Request Response
Now we are going to discuss things purely from the perceptive of a client and server (backend).
So synchronicity can also be known as a client property where it can wait or move on. Nowadays, no client is synchronous, and most libraries are asynchronous. Mostly client sends the request, and it gets a response, and some callback is getting called whenever the response is getting executed. So in Node.js specifically, there is an event loop main loop that checks out for the response.
This can be confusing, as it was always for me when someone explained it with this beautiful real-life example that synchronous is like asking a question in a meeting where the meeting will move on if the presenter responds. Asynchronous is like asking a question in an email which can be responded to whenever the receiver gets time.
Asynchronous backend Processing
Being a backend engineer, it would be unfair if I don’t talk about making the backend asynchronous. In many code/ repositories, the client is primarily asynchronous, but the backend still makes it wait. So when a client requests to push some data, let’s say to do a database call, many times it's asked to wait for the response from the backend, which returns a status 200 response after the commit. Now, if we move out the lens to the backend, the frontend is asynchronous, but the back end is still synchronous. So how do we return an immediate response?
One of the solutions is to use this beautiful data structure, named a queue. If a client sends a request, we will not promise to execute it immediately, but we will flush it into the queue. The reason for this is that the backend might be completing the previous requests, and the client is not blocked anymore; we can send the response that we have queued the request, and here is a promise/JobID. For more information, you can read about message queues.
There are very popular solutions apart from this, depending on the use case.
A real-world example of an Asynchronous workload:
a) Asynchronous commits in Postgres ↗.
b) Asynchronous I/O in Linux (io-uring).
c) Asynchronous I/O fsync (fs-cache): Whenever we write something to any file, it is not directly written to disk but to the file system cache. There is a cache in the Operating system, and the writes go into pages. And then, the operating system flushes all the pages in one go.
We can summarise the entire thing as follows:
a) The synchronous programming approach executes tasks sequentially. Each task is carried out after it has waited for any preceding task to finish.
b) When a task is run in an asynchronous programming model, we can move on to another without waiting for the previous one to finish.
Thanks for reading; I hope it was helpful.
In case of any further doubts, feel free to connect over LinkedIn/ Instagram.











