Skip to content

Commit

Permalink
Faster shutdown of pgxpool.Pool background goroutines
Browse files Browse the repository at this point in the history
When a pool is closed, some background goroutines may be left open,
particularly for health checks as detailed in #1641. Two specific
examples have been refactored here to avoid a blocking sleep and instead
also select on the pool being closed to potentially return/continue
sooner.
  • Loading branch information
bgentry committed Jun 14, 2023
1 parent 461b9fa commit d2d8635
Showing 1 changed file with 16 additions and 4 deletions.
20 changes: 16 additions & 4 deletions pgxpool/pool.go
Original file line number Diff line number Diff line change
Expand Up @@ -384,10 +384,19 @@ func (p *Pool) triggerHealthCheck() {
go func() {
// Destroy is asynchronous so we give it time to actually remove itself from
// the pool otherwise we might try to check the pool size too soon
time.Sleep(500 * time.Millisecond)
t := time.NewTimer(500 * time.Millisecond)

select {
case p.healthCheckChan <- struct{}{}:
default:
case <-p.closeChan:
// If the pool is already closed, stop the timer and return:
if !t.Stop() {
<-t.C
}
case <-t.C:
select {
case p.healthCheckChan <- struct{}{}:
default:
}
}
}()
}
Expand All @@ -408,6 +417,9 @@ func (p *Pool) backgroundHealthCheck() {
}

func (p *Pool) checkHealth() {
ticker := time.NewTicker(500 * time.Millisecond)
defer ticker.Stop()

for {
// If checkMinConns failed we don't destroy any connections since we couldn't
// even get to minConns
Expand All @@ -424,7 +436,7 @@ func (p *Pool) checkHealth() {
select {
case <-p.closeChan:
return
case <-time.After(500 * time.Millisecond):
case <-ticker.C:
}
}
}
Expand Down

0 comments on commit d2d8635

Please sign in to comment.