Repository navigation
Description
Hi Go Devs,
I've noticed a strange memory leak when running my Go program with the Race Detector. The program is an ad-hit tracker, it receives data from RabbitMQ and writes them down to the database. When there are errors in the DB, the program leaks memory (the RES mem usage grows unchecked until the machine runs out of RAM).
Run the program (below) with and without the -race detector to see the difference.
What version of Go are you using (go version)?
go version go1.10.3 linux/amd64
Does this issue reproduce with the latest release?
Yes
What operating system and processor architecture are you using (go env)?
GOARCH="amd64"
GOBIN=""
GOCACHE="/home/adil/.cache/go-build"
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOOS="linux"
GOPATH="/home/adil/go"
GORACE=""
GOROOT="/snap/go/2130"
GOTMPDIR=""
GOTOOLDIR="/snap/go/2130/pkg/tool/linux_amd64"
GCCGO="gccgo"
CC="gcc"
CXX="g++"
CGO_ENABLED="1"
CGO_CFLAGS="-g -O2"
CGO_CPPFLAGS=""
CGO_CXXFLAGS="-g -O2"
CGO_FFLAGS="-g -O2"
CGO_LDFLAGS="-g -O2"
PKG_CONFIG="pkg-config"
GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0 -fdebug-prefix-map=/tmp/go-build049513405=/tmp/go-build -gno-record-gcc-switches"
What did you do?
Run this program without the race detector:
> go build -o race experimental/rabbitmqmemoryleak.go && ./race
Observe the memory usage in top. It should flatline. Then, run it with the -race detector
> go build -race -o race experimental/rabbitmqmemoryleak.go && ./race
The memory usage grows unchecked.
package main
import (
"database/sql"
"log"
"github.com/go-errors/errors"
_ "github.com/lib/pq"
"github.com/streadway/amqp"
)
// This program demonstrates a memory leak in Go's built-in race detector.
// You will need RabbitMQ and Postgres installed on your machine.
// First, run the program like this:
// > go build -o race experimental/rabbitmqmemoryleak.go && ./race
// Observe the 'RES' memory in `top`. It should level after a bit
//
// Then, run the program like this:
// > go build -race -o race experimental/rabbitmqmemoryleak.go && ./race
// Watch as RAM usage counts unchecked
// Strangely running `go run -race experimental/rabbitmqmemoryleak.go` does not leak memory.
func main() {
var err error
conn, err := amqp.Dial("amqp://guest:guest@localhost:5672")
if err != nil {
log.Fatal(err)
}
defer conn.Close()
channel, err := conn.Channel()
if err != nil {
log.Fatal(err)
}
defer channel.Close()
queue := "testing-memory-leak"
// 1. Create the queue
var args amqp.Table
_, err = channel.QueueDeclare(queue, false, true, false, false, args)
defer channel.QueueDelete(queue, false, false, true)
// 2. Fill in messages
cnt := 100000
log.Printf("Inserting %d messages", cnt)
for index := 0; index < cnt; index++ {
msg := `{"date":"2018-07-17 08:44:30.202358+02","campaignID":18275,"affiliateSiteID":70002,"materialID":969206,"referenceID":0,"referenceHash":null,"referenceName":null,"isUnique":true,"merchantCommission":"0","affiliateCommission":"0","IP":"37.74.164.6","postImpressionHash":"0ebdd4720ef7eba5f09a84b8c68367c6","universalFingerprintHash":"c47e486da2ff1a4695b1499052b09807","pushToDynamoDB":true,"timestamp":"1531809870","handlerType":"impression","host":"snipped","pid":7962,"userAgentID":null,"userAgentHash":"08ac6aeb466ccd8f05ad37a144afe0f8","userAgentName":"Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/58.0.3029.110 Safari\/537.36 Edge\/16.16299","requestHash":"29c2363878fee77174d0b1e2491ea93b"}`
err := channel.Publish("", queue, true, false, amqp.Publishing{ContentType: "application/json", Body: []byte(msg), DeliveryMode: 2})
if err != nil {
log.Panic(err)
}
}
log.Printf("Done")
pgb, err := sql.Open("postgres", "host=localhost user=user password=pass dbname=db sslmode=disable")
if err != nil {
log.Fatal(err)
}
defer pgb.Close()
// 2. Listen on the messages
forever := make(chan bool)
for i := 0; i < 10; i++ {
go handler(queue, pgb)
}
<-forever
}
func handler(queue string, pgb *sql.DB) {
conn, err := amqp.Dial("amqp://guest:guest@localhost:5672")
if err != nil {
log.Fatal(err)
}
channel, err := conn.Channel()
if err != nil {
log.Fatal(err)
}
for {
message, ok, err := channel.Get(queue, false)
if err != nil {
log.Fatal(err)
}
if !ok {
continue
}
log.Printf("%+v", message)
err = someErroneousSQLTransaction(pgb)
if err != nil {
log.Printf("ERROR: %s", err)
message.Nack(false, true)
} else {
message.Ack(false)
}
}
}
func someErroneousSQLTransaction(pgb *sql.DB) error {
refTx, err := pgb.Begin()
if err != nil {
return errors.Wrap(err, 0)
}
defer func() {
if err != nil {
refTx.Rollback()
} else {
refTx.Commit()
}
}()
_, err = refTx.Exec(`set transaction isolation level repeatable read`)
if err != nil {
return err
}
var referenceID int64
switch err = pgb.QueryRow(`SELECT "ID" FROM public.blah LIMIT 1`).Scan(&referenceID); err {
case sql.ErrNoRows:
break
case nil:
break
default:
return err
}
return nil
}
What did you expect to see?
Flatline memory usage, as measured with top when running with -race. I expect it to take more memory to maintain internal data structures, but it should flatline at some point.
What did you see instead?
Constantly growing RES mem usage in top.
Strangely running go run -race experimental/rabbitmqmemoryleak.go does not leak memory.
Activity
[-]Go's race detector is leaking memory on RabbitMQ and Postgres[/-][+]runtime: Go's race detector is leaking memory on RabbitMQ and Postgres[/+]ianlancetaylor commentedon Aug 5, 2018
CC @dvyukov
dvyukov commentedon Aug 6, 2018
Difference between
go buildandgo runlooks strange. Do we have any known precedent of differences?dvyukov commentedon Aug 6, 2018
@adilbaig can you provide a step-by-step repro instructions?
agnivade commentedon Aug 6, 2018
It is there in the code comments I believe -
Did you want anything specific ?
dvyukov commentedon Aug 6, 2018
Something that I can copy-paste into my console.
adilbaig commentedon Aug 6, 2018
@dvyukov How about this.
You don't actually need to create Postgres tables. I see the leaks when the SQL errors out (for example due to bad login credentials).
dvyukov commentedon Aug 6, 2018
Can reproduce it now.
The problem is that the program grows infinite stack with infinite recursion:
So it will crash without race detector sooner or later too, makes GC slow, crash messages unreadable, etc.
It's just that race detector is more sensitive to thousands of unique stacks as it memorizes tons of contextual information about the program as it runs. In this case it memorizes several variations of the stack per recursion frame, which is quadratic memory consumption.
adilbaig commentedon Aug 6, 2018
@dvnagorny
I haven't seen that happen, as I ran it without the race detector over the weekend. Can you confirm that it's stable without
-race?I'm a novice at Go, but, given your explanation, am i right to think this will be an issue for any evented system (that errors out on events).?
dvyukov commentedon Aug 6, 2018
no.
I don't know about these libraries, but what first comes to my mind is that there is a way to use them without infinite recursion. You both have an infinite loop in handler and call it recursively. I would expect that you need to do only 1 of these things, but not both. Have you looked at other usage examples of these libraries? Do all of them use it in the same way?
adilbaig commentedon Aug 7, 2018
I guess it only looks recursive in the dump, but it isn't, it's just running in a loop one message after another erroring out at every message. So I'm guessing with the race detector on, a reference to something in the
sqlpackage is still being bandied around. I tried replacing thesqlerror with a plainfmt.Errorf, memory usage remained flat. So it isn't any error that causes the leak, but something specific to the sql library. That's my guess.Yep, it's largely just fetching and processing a message in a loop. Here's a canonical example from the site: https://www.rabbitmq.com/tutorials/tutorial-one-go.html (Code is at https://github.com/rabbitmq/rabbitmq-tutorials/blob/master/go/receive.go)
@dvnagorny
dvyukov commentedon Aug 8, 2018
No, it calls someErroneousSQLTransaction which calls sql.(*DB).Begin which calls handler again.
19 remaining items
gopherbot commentedon Feb 24, 2020
Change https://golang.org/cl/220586 mentions this issue:
doc/articles: mention memory leak in race detector docsdoc/articles/race_detector: mention memory leak potential
gopherbot commentedon Feb 25, 2020
Change https://golang.org/cl/221019 mentions this issue:
[release-branch.go1.14] doc/articles/race_detector: mention memory leak potential[release-branch.go1.14] doc/articles/race_detector: mention memory le…
edaniels commentedon Jul 15, 2020
We just realized we were hitting this for many months in our dev and qa environments where we are running a server compiled with the race defector enabled. Ultimately disabling it kept the resident memory stable and not leaking to the point of being OOM killed over the course of the day. We however were not seeing 8 bytes of leakage at a time as opposed to many MB. When I core dumped the process and ran
stringson it, I saw many duplicates of a record we pull from the database although we cache that value in a go map internally.I eventually ran strace -k filtering for mmap calls since malloc can call mmap if the size requested is over a threshold. Doing this showed a lot of calls into tsan/sanitizer library shadow methods. I’m wondering if the shadow variables maintained end up making wholesale copies of certain values or regions of memory?
Either way, the detector is too useful and we will keep it on, but getting it to not leak memory would excise a lot of noise from our development and testing processes.
dvyukov commentedon Jul 15, 2020
No, the additional regions allocated by the race runtime should only hold internal metadata and never user data, or copies of user data.
edaniels commentedon Jul 15, 2020
I see. So around 7/15 02:00 is when we turned off the detector and as soon as we turned it back on today we started leaking again.

We've had that type of trend for at least 3 months now and not running it for a 12 hour period showed no kind of abnormal leakage of memory. So maybe something else is going on that is causing a ton of 8 byte leakages?
Keeping in mind that this is mostly HTTP traffic load that stays consistent day over day.
anacrolix commentedon Feb 8, 2021
I've had users report this when using https://github.com/anacrolix/stm with the race detector enabled. Per other comments above, there is a lot of defer/recover, and very long call stacks that don't look correct.
gopherbot commentedon Feb 9, 2023
Change https://go.dev/cl/458218 mentions this issue:
runtime: implement traceback iteratoraclements commentedon Feb 13, 2023
Once this is fixed, we should unwind the documentation change in CL 221019
runtime: implement traceback iterator
mdempsky commentedon Aug 8, 2023
FYI, @dvyukov 's test case no longer reproduces for me.
I also tried forcing baz to use stack-allocated defers (by adding a named result parameter) and heap-allocated defers (by adding a
for { ...; break }wrapper around the defer statement).I also tried adding a
runtime.Gosched()call after thego func() { x++ }()statement, to ensure the "Read at" and "Previous write at" match the same goroutines as in @dvyukov 's output.anacrolix commentedon Aug 8, 2023
Could something have changed in recent versions is Go (I presume 1.21 @mdempsky ?) that could have fixed this issue?