#Is it OK to run a DB write in a goroutine? (or will I get attacked by a velociraptor)

6 messages · Page 1 of 1 (latest)

hushed idol
#

Relevant code here: https://github.com/emivespa/mutant/blob/master/api/mutant.go

Context: I have to return 200/403 based on whether the requests' DNA strand counts as mutant or human, and write all mutant/humans to a DB.
Is it OK to run the DB write in a goroutine in order to return 200/403 faster, or does it "mostly work" but will come back to bite me? (https://xkcd.com/292/)

BTW, any comments on the rest of the DB code g-r-e-a-t-l-y appreciated (it's my 1st working with running go-prisma).

amber walrus
#

@hushed idol it depends what you are doing with the DB call output. If you are just returning a 200/403 and no content then its fine. But if you run in a goroutine , then you cant write any errors to the returned user (conditional 403 based on the success of the db operation).

That being said, looking at your code it seems fine, as there is nothing inherently bad about running db operations in a goroutine. But yes, it will come back to bite you in the ass because if you are planning to make this an actual API, it will be necessary to return results based on the operation results.

Additionally, you should add a deadline to your context (i'm assuming this is some long-running read/write). If its not a long-running read/write, I see no issue just not using the goroutine for this. However, if it is a long-running op, then I would suggest optimizing the query itself (adding necessary indexes, smarter storage of data, etc.). Also, no need to cast dnaString to a string again on line 45.

Deadline ctx:

// call cancel func to cancel the context, you can ignore this, but I would just defer it in
// your goroutine. This context will cancel automatically after 30 seconds
opCtx, cancelFunc := context.WithTimeout(ctx, time.Seconds * 30)
hushed idol
#

Thank you! as I understand it the DB write is "analytics" meaning unrelated to what we return to the client. It logs in the DB for the /stats endpoint. Now using a timeout for the context, also improved DB code

solar goblet
#

There’s nothing wrong with putting the DB operation in the background to speed up the response. If you can see a profit with this then go for this. Just remember to use a different context, because the original one will be killed after the request is finished. And of course you need proper error/timeout handling. But in the terms of a good practice, if you don’t need the result for the response, it seems just fine!

hushed idol
#

yeah I'm not using the request context, it would always get killed

hushed idol
#

Got attacked by a velociraptor: putting DB processing in a goroutine means your tests might very well pass, but codecov tools will panic