I am using golang + mongodb and got error like this

At first I would like to apologize with my bad English.
So I use go with docker , and mongo with server ubuntu.
When on production , it’s look like work normal but when got a lot of traffic or something I got error like this “server selection timeout, current topology: { Type: Unknown, Servers: [{ Addr: IP:PORT, Type: Unknown, Last error: connection() error occured during connection handshake: dial tcp IP:PORT: i/o timeout }, ] }”

and today I see in my mongo.log
“msg”:“Error sending response to client. Ending connection from remote”,“attr”:{“error”:{“code”:6,“codeName”:“HostUnreachable”,“errmsg”:“Connection reset by peer”},“remote”:”IP:50700”,“connectionId”:182673}}

“c”:“COMMAND”, “id”:51803, “ctx”:“conn254054”,“msg”:“Slow query”,“attr”:{“type”:“command”,“ns”“admin.$cmd”,“command”:{“hello”:1,“helloOk”:true,“topologyVersion”:{“processId”:{"$oid":“62b84b3d8070fc21d0f35ab6”},“counter”:0},“maxAwaitTimeMS”:10000,"$db":“admin”},“numYields”:0,“ok”:0,“errMsg”:“operation was interrupted”,“errName”:Disconnect",“errCode”:279,“reslen”:117,“locks”:{},“remote”:”IP:43521”,“protocol”:“op_msg”,“durationMillis”:114}}

In my code it’s look like this
I declare 1 function for connection
1 function for call collection
and If i have to insert i alway use this
db , err := functionConnection()
Collection := functionCallCollection()

after insert I declare like this
defer db.Disconnect(ctx1)

It is possible your query results in large data but it could not return that data in the required timeslot of 10 seconds and your client program terminated the connection because of this timeout.

try that same query but use limit and see if it will still give the same error. then try the same by setting a longer timeout value.

Thx Sir , but i think it’s wrong with my code, cuz I connect for multiple times

It is then possible you have goroutine/waitGroup or async/await problem.

Initially, I thought it would be the size of the data to be returned. Now I noticed you moved your db logic to functions and use defer to close the connection.

I am not good at go, but most programming languages behave the same: if you run a function and it has an async feature in it, the function will still return without waiting for that operation to finish, but its return value will include a structure to indicate job is not finished yet.

outside that function, you need to process this structure accordingly or the program just exits and your process will be cut short. you need to define your functions as async, and use await in the calling lines.

the following is just a scratch to give an idea. I might have overused await :slight_smile: so check the language and driver manuals.

db , err := await functionConnection()
defer db.Disconnect(ctx1)
Collection := await functionCallCollection()
await Collection.insert(data)
async functionConnection(){ return await mongo.Connect()}
async functionCallCollection(){ return await db.getCollection()}