Sorry for the very vague noob question, I really want to ask this:
When do we use async or sync code in the context of Elixir? AFAIK genserver call is synchronous which is blocking code. Do you have a real example or when do you decide which one to use? I’ve read these article When should I use asynchronous code in JavaScript? – Nico Zerpa, Your JavaScript Friend, but I haven’t found a good example when it is better to use sync over async and vice versa. Any help/enlightenment is greatly appreciated .
Imagine you want to read data from a source data store and write it to a destination data store. The requirements are not real-time. As long as the data arrives within 24 hours, everyone is happy.
Imagine the source data store will happily let you read 100,000 records per second.
Imagine the source data is bursty. Once per hour 1000,000 records show up in a few seconds and then nothing for the rest of the hour. And imagine the destination data store slows down when you make concurrent writes and it can’t handle batches larger than 1000 without spending much more money and re-architecture.
You can have a single Genserver responsible for writing to the destination.
Your code that consumes from the source data does not need to know anything about rate limiting or slowing down because it will receive back-pressure from the Genserver every time it tries to use call, which will block the process until it is done writing the batch to the destination.
Async example
Imagine you need to make 5 API requests and present a combination of all the data to the user. You could use Task.async to make all 5 requests, and after that, Task.await all of them.
If the Sync example is too slow
If you started with the sync example and you realize that you need to process faster, Elixir has a very deep toolbox for speeding things up by using an unbounded or configurable number of processes.
I know in C#/.NET, that you use async for IO operations. Using asynchronous code frees up the calling thread. I don’t know if it is the same for other languages.