Skip to content

Commit

Permalink
Fix HTTP keep-alive for CouchDB connections (#4497)
Browse files Browse the repository at this point in the history
Golang can reuse HTTP connections with keep alive, but the response body
must have been fully read and closed. In the couchdb package, we were
reading the body for sucessful response with a json.Decoder. It only
reads a JSON value, and most responses from CouchDB have an additional
\n after that JSON value. This last byte was not read from the response
body, and it prevents Golang from reusing the connection. So, we are
doing a new HTTP connection (with DNS resolution and TLS handshake) for
each request to CouchDB.
  • Loading branch information
nono authored Nov 28, 2024
2 parents e0e948f + 71f05bb commit 2cbb312
Showing 1 changed file with 5 additions and 3 deletions.
8 changes: 5 additions & 3 deletions pkg/couchdb/couchdb.go
Original file line number Diff line number Diff line change
Expand Up @@ -311,7 +311,11 @@ func makeRequest(db prefixer.Prefixer, doctype, method, path string, reqbody int
log.Error(err.Error())
return err
}
defer resp.Body.Close()
defer func() {
// Flush the body, so that the connection can be reused by keep-alive
_, _ = io.Copy(io.Discard, resp.Body)
_ = resp.Body.Close()
}()

if elapsed.Seconds() >= 10 {
log.Infof("slow request on %s %s (%s)", method, path, elapsed)
Expand All @@ -322,8 +326,6 @@ func makeRequest(db prefixer.Prefixer, doctype, method, path string, reqbody int
return err
}
if resbody == nil {
// Flush the body, so that the connection can be reused by keep-alive
_, _ = io.Copy(io.Discard, resp.Body)
return nil
}

Expand Down

0 comments on commit 2cbb312

Please sign in to comment.