#2344·badger

DropPrefix / DropAll deadlock

Author: WildFire-StorageCreated Oct 1, 2026Updated Oct 1, 2026

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:

  • DropPrefix never returns;
  • every Get, View, Update and NewIterator call 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)

  1. A writer in Txn.commitAndSend holds orc.writeChLock, takes a commit timestamp (txnMark.Begin(commitTs)) and calls sendToWriteCh. There, the check db.blockWrites.Load() == 1 (db.go:884) passes.
  2. Concurrently, DropPrefix → prepareToDrop → blockWrite() sets blockWrites to 1 and stops doWrites (closers.writes.SignalAndWait, db.go:1628-1637). prepareToDrop then drains writeCh with a non-blocking select until it is empty (db.go:1655-1673).
  3. The writer from step 1 now executes db.writeCh <- req (db.go:904). writeCh is buffered, so the send succeeds, but doWrites has stopped and the drain loop has already finished. The request is orphaned in the channel.
  4. DropPrefix continues to filterPrefixesToDrop (db.go:1766), which calls db.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, because doWrites is only restarted by unblockWrite(), which runs after DropPrefix returns.
  5. The result is a cycle: DropPrefix waits for the orphaned commit, and the orphaned commit waits for DropPrefix to restart doWrites. Every other new transaction also blocks in WaitForMark.

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.Wait after sendToWriteCh.

Possible fix (suggestion)

Make the blockWrites check and the send to writeCh atomic with respect to blockWrite().

  • For transaction commits: commitAndSend already holds orc.writeChLock across the check and the send, so blockWrite() could take orc.writeChLock while setting blockWrites (and before draining). No committer can then be between the check and the send.
  • The other sendToWriteCh callers (batchSet/batchSetAsync, db.go:979/995) would need the same guard, or an RWMutex around check+send, with blockWrite taking the write side.
  • Alternatively, prepareToDrop could 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.

go
// 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.