I've swapped an endpoint from our PHP 7 app to a new Go service. The service takes a geographic bounding box and returns properties from a mongo database. The problem is that it's currently taking 4-5 times as long as the old PHP service took to do the same thing. ~90% of the time is spent in the GetProps function below.
var session *mgo.Session
func connectToDB() *mgo.Session {
dialInfo := &mgo.DialInfo{
Addrs: []string{"xxx1.mongodb.net:27017", "xxx2.mongodb.net:27017", "xxx3.mongodb.net:27017"},
Database: "admin",
Username: "me",
Password: "xxx",
DialServer: func(addr *mgo.ServerAddr) (net.Conn, error) {
return tls.Dial("tcp", addr.String(), &tls.Config{})
},
Timeout: time.Second * 10,
}
session, err := mgo.DialWithInfo(dialInfo)
if err != nil {
log.Panic(err)
}
session.SetMode(mgo.Monotonic, true)
return session
}
func GetProps(propRequest Request) []Property {
results := make([]Property, 0)
sessionCopy := session.Copy()
defer sessionCopy.Close()
props := sessionCopy.DB("mapov").C("properties")
props.Find(bson.M{
"geo": bson.M{
"$geoWithin": bson.M{
"$geometry": bson.M{
"type": "Polygon",
"coordinates": propRequest.BoundingPoly,
},
},
},
}).Sort("-rank").Limit(propRequest.CpPropsRequired).All(&results)
return results
}
func init() {
session = connectToDB()
}
The PHP 7 service does pretty much the same thing -
$collection = $mapovdb->properties;
$query = ['geo' => [
'$geoWithin' => [
'$geometry' => [
'type' => 'Polygon',
'coordinates' => $boundingPoly
]
]
]];
$cursor = $collection->find( $query, $queryOptions); // $queryOptions includes the matching sort and limit
But it's way quicker (I ran the two services next to each other for 12 hours randomising the traffic).
I tried changing my property struct so it just takes a single field, but that didn't seem to affect the performance.
type Property struct {
Name string `bson:"name" json:"name"`
}
What am I doing wrong? Surely I should be able to match the performance of the php7 driver?
UPDATE
I've swapped out the builtin http library for fasthttp. This seems to have made everything faster. I haven't had time to work out why yet (but will come back here when I do). My current theory is that the builtin http library creates a new goroutine for each new tcp connection not each new http connection and this is causing my db queries to queue - either because the load balancer is reusing tcp connections, or because the client is reusing them (http/2?).