Skip to content

Commit 2cbb312

Browse files
authored
Fix HTTP keep-alive for CouchDB connections (#4497)
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.
2 parents e0e948f + 71f05bb commit 2cbb312

File tree

1 file changed

+5
-3
lines changed

1 file changed

+5
-3
lines changed

pkg/couchdb/couchdb.go

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -311,7 +311,11 @@ func makeRequest(db prefixer.Prefixer, doctype, method, path string, reqbody int
311311
log.Error(err.Error())
312312
return err
313313
}
314-
defer resp.Body.Close()
314+
defer func() {
315+
// Flush the body, so that the connection can be reused by keep-alive
316+
_, _ = io.Copy(io.Discard, resp.Body)
317+
_ = resp.Body.Close()
318+
}()
315319

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

0 commit comments

Comments
 (0)