DropPrefix / DropAll deadlock
Sorry for my AI agent's long winded explanation. I am happy to reply as a human.
GitHub issue for github.com/dgraph-io/badger
Title: DropPrefix (and DropAll) can deadlock the DB when a transaction commits concurrently
What version of Badger are you using?
v4.9.1 (github.com/dgraph-io/badger/v4 v4.9.1), Go 1.25, Linux x86_64. Default options (DefaultOptions(dir)), not
managed mode.
What happened?
Calling DB.DropPrefix while other goroutines are committing transactions (db.Update / Txn.Commit) can hang the
whole DB permanently:
DropPrefixnever returns;- every
Get,View,UpdateandNewIteratorcall blocks; - the process has to be killed.
It is intermittent. With the reproducer below (4 writer goroutines committing small transactions non-stop, the main
goroutine writing 100 keys under a fresh prefix and calling DropPrefix on it, in a loop), 3 of 4 runs deadlocked,
after 198, 396 and 1,396 DropPrefix calls (10-20 s). With a single writer at ~2,000 commits/s it hit about once in
400 DropPrefix calls.
What did you expect?
DropPrefix returns. Concurrent commits either succeed or fail with ErrBlockedWrites.
Analysis (line numbers are v4.9.1)
- A writer in
Txn.commitAndSendholdsorc.writeChLock, takes a commit timestamp (txnMark.Begin(commitTs)) and callssendToWriteCh. There, the checkdb.blockWrites.Load() == 1(db.go:884) passes. - Concurrently,
DropPrefix→prepareToDrop→blockWrite()setsblockWritesto 1 and stopsdoWrites(closers.writes.SignalAndWait, db.go:1628-1637).prepareToDropthen drainswriteChwith a non-blocking select until it is empty (db.go:1655-1673). - The writer from step 1 now executes
db.writeCh <- req(db.go:904).writeChis buffered, so the send succeeds, butdoWriteshas stopped and the drain loop has already finished. The request is orphaned in the channel. DropPrefixcontinues tofilterPrefixesToDrop(db.go:1766), which callsdb.View(db.go:1810).View→NewTransaction→oracle.readTs()→txnMark.WaitForMark(readTs)(txn.go:93). That waits for the orphaned transaction's commit timestamp to be marked done. It never is, becausedoWritesis only restarted byunblockWrite(), which runs afterDropPrefixreturns.- The result is a cycle:
DropPrefixwaits for the orphaned commit, and the orphaned commit waits forDropPrefixto restartdoWrites. Every other new transaction also blocks inWaitForMark.
DropAll uses the same prepareToDrop / blockWrite sequence, so it should be affected too; this was not separately
tested.
Goroutine stacks at the hang:
DropPrefix→filterPrefixesToDrop→View→NewTransaction→readTs→WaitForMark(txn.go:93);- the writers parked in
request.WaitaftersendToWriteCh.
Possible fix (suggestion)
Make the blockWrites check and the send to writeCh atomic with respect to blockWrite().
- For transaction commits:
commitAndSendalready holdsorc.writeChLockacross the check and the send, soblockWrite()could takeorc.writeChLockwhile settingblockWrites(and before draining). No committer can then be between the check and the send. - The other
sendToWriteChcallers (batchSet/batchSetAsync, db.go:979/995) would need the same guard, or anRWMutexaround check+send, withblockWritetaking the write side. - Alternatively,
prepareToDropcould wait for an in-flight-senders counter to reach zero before its final drain.
Reproducer
go run . -writers 4 -iters 3000. Exit code 3 means it deadlocked; it prints the relevant stacks.
// DropPrefix with concurrent writers can orphan a write request and deadlock
// the DB. Writers commit small txns non-stop; the main loop writes a few keys
// under a fresh prefix and DropPrefix-es it, over and over. A call that does
// not return within -hang is reported as a deadlock.
package main
import (
"errors"
"flag"
"fmt"
"os"
"runtime"
"strings"
"sync/atomic"
"time"
badger "github.com/dgraph-io/badger/v4"
)
func main() {
dir := flag.String("dir", "/tmp/badger-dropprefix-race", "db dir (wiped)")
writers := flag.Int("writers", 4, "concurrent writer goroutines")
iters := flag.Int("iters", 2000, "DropPrefix calls")
hang := flag.Duration("hang", 10*time.Second, "a call longer than this = deadlock")
flag.Parse()
os.RemoveAll(*dir)
db, err := badger.Open(badger.DefaultOptions(*dir).WithLogger(nil))
if err != nil {
panic(err)
}
var stop atomic.Bool
var ok, blocked atomic.Int64
for w := 0; w < *writers; w++ {
go func(w int) {
for i := 0; !stop.Load(); i++ {
k := []byte(fmt.Sprintf("o/other/%d/%d", w, i))
err := db.Update(func(txn *badger.Txn) error { return txn.Set(k, []byte("v")) })
switch {
case err == nil:
ok.Add(1)
case errors.Is(err, badger.ErrBlockedWrites):
blocked.Add(1)
default:
panic(err)
}
}
}(w)
}
start := time.Now()
for it := 0; it < *iters; it++ {
p := []byte(fmt.Sprintf("o/big%d/", it))
wb := db.NewWriteBatch()
for j := 0; j < 100; j++ {
wb.Set(append(append([]byte{}, p...), fmt.Sprint(j)...), []byte("x"))
}
if err := wb.Flush(); err != nil && !errors.Is(err, badger.ErrBlockedWrites) {
panic(err)
}
done := make(chan error, 1)
go func() { done <- db.DropPrefix(p) }()
select {
case err := <-done:
if err != nil {
panic(err)
}
case <-time.After(*hang):
buf := make([]byte, 1<<22)
n := runtime.Stack(buf, true)
var keep []string
for _, g := range strings.Split(string(buf[:n]), "\n\n") {
if strings.Contains(g, "DropPrefix") || strings.Contains(g, "request).Wait") {
keep = append(keep, g)
}
}
fmt.Printf("DEADLOCK at DropPrefix call %d after %v (writes ok %d, blocked %d)\n\n%s\n",
it, time.Since(start).Round(time.Millisecond), ok.Load(), blocked.Load(), strings.Join(keep, "\n\n"))
os.Exit(3)
}
}
stop.Store(true)
fmt.Printf("no deadlock in %d DropPrefix calls, %v (writes ok %d, blocked %d)\n",
*iters, time.Since(start).Round(time.Millisecond), ok.Load(), blocked.Load())
db.Close()
os.RemoveAll(*dir)
}Workaround we use
We never call DropPrefix while any goroutine can be inside a Badger write: an RWMutex where every write path holds
the read side and the drop holds the write side.
Source: dgraph-io/badger