Best timeOut for mongoDB context timeout in golang

695 views
Skip to first unread message

Javad Rajabzade

unread,
Jan 15, 2022, 5:20:20 PM1/15/22
to golang-nuts
hi
I just joined a project and have been reading codes.

dbContext, cancelFunc = context.WithTimeout(context.Background(), 20*time.Minute)

For a database query, I found the context With Time Out, and it has been set to 20 minutes.
How much time is appropriate for a timeout query in Go?

Brian Candler

unread,
Jan 16, 2022, 5:19:40 AM1/16/22
to golang-nuts
There is no upper bound to the time a SQL query can take.  Even a simple "select" which requires a full table scan can take hours when run on a sufficiently large table.  Ditto a complex "update" command,  or a schema modification.

You don't have to apply any time limit at all.  But if you do, it's up to you to decide what is sensible in your environment, given the size of your dataset and the types of operation you are doing.  You should think about *why* you want a timeout at all, and under what situations it would be desirable to terminate a query before it has had time to complete - and in what situations it would cause problems.

You may also have some implicit timeout in your environment already: e.g. if you are handling HTTP requests, and those have their own timeout and run within their own context, then you could use the same context for your database queries.

Brian Candler

unread,
Jan 16, 2022, 4:24:01 PM1/16/22
to golang-nuts
Oops, subject said mongoDB not SQL.  But I think the point stands.

Marcin Romaszewicz

unread,
Jan 16, 2022, 9:20:49 PM1/16/22
to Brian Candler, golang-nuts
SQL Databases also typically have query timeouts on the DB side. When you cancel a context, the DB could still chug on that query for a while. For example, https://www.postgresql.org/docs/current/runtime-config-client.html (see statement_timeout). If you want to reliably cancel connections and not swamp your DB with runaway queries, do both.

On Sun, Jan 16, 2022 at 1:24 PM Brian Candler <b.ca...@pobox.com> wrote:
Oops, subject said mongoDB not SQL.  But I think the point stands.

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/6a5d0919-a828-41d4-8c53-722631013f68n%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages