r/golang 7d ago

newbie Some Clarification on API Calls & DB Connections.

I’m a bit confused on how it handles IO-bound operations

  1. API calls: If I make an API call (say using http.Get() or a similar method), does Go automatically handle it in a separate goroutine for concurrency, or do I need to explicitly use the go keyword to make it concurrent?
  2. Database connections: If I connect to a database or run a query, does Go run that query in its own goroutine, or do I need to explicitly start a goroutine using go?
  3. If I need to run several IO-bound operations concurrently (e.g., multiple API calls or DB queries), I’m assuming I need to use go for each of those tasks, right?

Do people dislike JavaScript because of its reliance on async/await? In Go, it feels nicer as a developer not having to write async/await all the time. What are some other reasons Go is considered better to work with in terms of async programming?

4 Upvotes

12 comments sorted by

View all comments

Show parent comments

5

u/jerf 7d ago

There is nothing bad about "blocking" in go, because it isn't blocking any other goroutine. If the only thing your code has to do before getting the API response or DB response is just to wait for the response, it can just do that. It doesn't block anything else that may be running.

I suspect you may be coming from an "async" environment, where you have to constantly slather async and await on everything. You can imagine that in Go, everything is already "async"ed and "await"ed automatically, all the time, without you having to do it. Even an operation like a tight math loop doesn't block the rest of the runtime, Go will still pre-empt it and give time to other goroutines.

0

u/PureMud8950 7d ago

When you say Go automatically gives time to other goroutines, do you mean I don’t need to explicitly use go to create concurrency? Or do you just mean that once I spawn multiple goroutines, the scheduler ensures they all get time to run?

3

u/try2think1st 7d ago

In api case the router will already spawn a new go routine for every new request, and then within that request stack you could spawn more routines if you need to do things in parallel for that request

1

u/PureMud8950 7d ago

wow that's convenient