Can I create multiple badger.db instances in multiple go routines?

What version of Go are you using (go version)?

$ go version
go version go1.16.4 darwin/amd6

Does this issue reproduce with the latest master?

Yes.

Hi,

I’m new to BadgerDB. As it’s not mentioned in the documentation, is it possible or recommended to open multiple badger.db instances in multiple go routines? Can read-write transactions from different badger.db instances work properly with each other?

Thank you for your help in advance.

Jonathan Xu

When you open a DB, it acquire lock over the data directory. Hence, you cannot open the multiple instances of same underlying DB. There is an option BypassLockGuard badger/options.go at baadc01dca6e349820ed63fb444ea14fd87cb8b5 · dgraph-io/badger · GitHub that allows skipping taking that lock.
This option is not recommended and should only be used when opening all the instances in ReadOnly mode.

@Naman Thanks for your answer. So if I need to use the same db instance with multiple go routines, I should implement some kind of reference counting on it. Is there any pitfall if I just don’t close a db instance and use it in a long running daemon?

Closing the DB after usage is recommended. Badger can survive process crashes but not power failure. I would have to check how the daemons are stopped, I hope that stopping a daemon abruptly should be equivalent to stopping a process.

Does this mean Badger may lose data if the DB is not closed when power failure happens? I read the code a bit and find that the changes to memtables are saved to WAL first. Does this help with power failure?