badger README

The project's README from github.com/dgraph-io/badger. As one markdown file: README.md.

BadgerDB

Go Reference Go Report Card Sourcegraph ci-badger-tests ci-badger-bank-tests ci-badger-bank-tests-nightly

Badger mascot

BadgerDB is an embeddable, persistent and fast key-value (KV) database written in pure Go. It is the underlying database for Dgraph, a fast, distributed graph database. It's meant to be a performant alternative to non-Go-based key-value stores like RocksDB.

Project Status

Badger is stable and is being used to serve data sets worth hundreds of terabytes. Badger supports concurrent ACID transactions with serializable snapshot isolation (SSI) guarantees. A Jepsen-style bank test runs nightly for 8h, with --race flag and ensures the maintenance of transactional guarantees. Badger has also been tested to work with filesystem level anomalies, to ensure persistence and consistency. Badger is being used by a number of projects which includes Dgraph, Jaeger Tracing, UsenetExpress, and many more.

The list of projects using Badger can be found here.

Please consult the Changelog for more detailed information on releases.

Note: Badger is built with go 1.23 and we refrain from bumping this version to minimize downstream effects of those using Badger in applications built with older versions of Go.

Table of Contents

Getting Started

Installing

To start using Badger, install Go 1.23 or above. Badger v3 and above needs go modules. From your project, run the following command

go get github.com/dgraph-io/badger/v4

This will retrieve the library.

Installing Badger Command Line Tool

Badger provides a CLI tool which can perform certain operations like offline backup/restore. To install the Badger CLI, retrieve the repository and checkout the desired version. Then run

cd badger
go install .

This will install the badger command line utility into your $GOBIN path.

Badger Documentation

Badger Documentation is available at https://badger.dgraph.io

Resources

Blog Posts

  1. Introducing Badger: A fast key-value store written natively in Go
  2. Make Badger crash resilient with ALICE
  3. Badger vs LMDB vs BoltDB: Benchmarking key-value databases in Go
  4. Concurrent ACID Transactions in Badger

Design

Badger was written with these design goals in mind:

Badger’s design is based on a paper titled WiscKey: Separating Keys from Values in SSD-conscious Storage.

Comparisons

Feature Badger RocksDB BoltDB
Design LSM tree with value log LSM tree only B+ tree
High Read throughput Yes No Yes
High Write throughput Yes Yes No
Designed for SSDs Yes (with latest research 1) Not specifically 2 No
Embeddable Yes Yes Yes
Sorted KV access Yes Yes Yes
Pure Go (no Cgo) Yes No Yes
Transactions Yes, ACID, concurrent with SSI3 Yes (but non-ACID) Yes, ACID
Snapshots Yes Yes Yes
TTL support Yes Yes No
3D access (key-value-version) Yes4 No No

1 The WISCKEY paper (on which Badger is based) saw big wins with separating values from keys, significantly reducing the write amplification compared to a typical LSM tree.

2 RocksDB is an SSD optimized version of LevelDB, which was designed specifically for rotating disks. As such RocksDB's design isn't aimed at SSDs.

3 SSI: Serializable Snapshot Isolation. For more details, see the blog post Concurrent ACID Transactions in Badger

4 Badger provides direct access to value versions via its Iterator API. Users can also specify how many versions to keep per key via Options.

Benchmarks

We have run comprehensive benchmarks against RocksDB, Bolt and LMDB. The benchmarking code, and the detailed logs for the benchmarks can be found in the badger-bench repo. More explanation, including graphs can be found the blog posts (linked above).

Projects Using Badger

Below is a list of known projects that use Badger:

If you are using Badger in a project please send a pull request to add it to the list.

Platform Compatibility

Badger uses OS-specific implementations for directory locking and fsync operations. On POSIX-compliant systems (Linux, macOS, BSD), these work as expected.

For non-POSIX platforms, be aware of potential limitations:

Platform File Notes
AIX dir_aix.go Directory fsync not supported; durability on crash may be affected
Windows dir_windows.go Uses different locking mechanism
Plan9 dir_plan9.go No file locking support
WASM/JS dir_other.go No file locking support

If you encounter issues on these platforms, review the corresponding dir_*.go source file for implementation details.

Contributing

If you're interested in contributing to Badger see CONTRIBUTING.

Contact

badger (dgraph-io/badger)

Searching Database…

15.8K ·GitHub
Что это такое?BadgerDB — это встраиваемая, персистентная и быстрая key-value база данных, написанная на чистом Go. Она служит движком хранения для графовой базы данных Dgraph и представляет собой производительную альтернативу нереляционным хранилищам не на Go, таким как RocksDB.
Это библиотека, которую я встраиваю в своё Go-приложение, или отдельный сервер базы данных?Это библиотека, которую вы встраиваете в свой собственный Go-процесс — никакого сервера устанавливать и запускать не нужно. Такие проекты, как Dgraph, Jaeger и go-ipfs, используют её в качестве локального движка хранения.
Как добавить её в проект?Установите Go 1.23 или новее и подключите библиотеку через go modules из своего проекта. Также можно собрать утилиту командной строки badger для офлайн-бэкапа и восстановления — она попадёт в вашу $GOBIN.
Нужно ли что-то ещё, кроме Go, например C-компилятор или сторонние библиотеки?Нет — Badger написана на чистом Go без cgo, поэтому достаточно обычного Go-тулчейна. Это одно из её заявленных преимуществ перед хранилищами не на Go, такими как RocksDB.
Она одинаково работает на всех операционных системах?На POSIX-системах (Linux, macOS, BSD) блокировка каталогов и fsync работают как ожидается. В Windows используется другой механизм блокировки, а у сборок под AIX, Plan9 и WASM/JS есть ограничения — например, отсутствие файловой блокировки или более слабая защита от потери данных при сбоях.
Почему она быстрая?Её дизайн основан на исследовательской работе WiscKey: ключи отделены от значений и хранятся в отдельном value log, что значительно снижает write amplification по сравнению с обычным LSM-деревом, а сам движок оптимизирован специально под SSD.
Чем она отличается от RocksDB и BoltDB?Badger использует LSM-дерево с value log, тогда как RocksDB — обычное LSM-дерево, а BoltDB — B+ дерево. В отличие от RocksDB она написана на чистом Go без cgo, а в отличие от BoltDB обеспечивает высокую скорость записи и поддержку TTL.
Поддерживаются ли ключи с истекающим сроком действия или несколько версий значения?Да, и то и другое. Поддерживается TTL, а Iterator API даёт прямой доступ к версиям значений — через настройки можно управлять тем, сколько версий хранить для каждого ключа.
Можно ли доверить ей критически важные данные?В README Badger названа стабильной и обслуживающей наборы данных объёмом в сотни терабайт. Она поддерживает конкурентные ACID-транзакции с сериализуемой snapshot-изоляцией, которые еженощно проверяются восьмичасовым тестом в духе Jepsen (bank test) с детектором гонок, а также тестируется на аномалиях на уровне файловой системы.
Кто использует её в продакшене?Dgraph, Jaeger Tracing, go-ipfs, Pyroscope и TalariaDB от Grab, среди многих других — одна только UsenetExpress обслуживает с её помощью более 300 ТБ данных.
What are similar projects?bolt, rocksdb, surrealdb, FerretDB, gun, nedb, leveldb, dicedb
Creator
dgraph-io
Size
57.1 MB
Stars
15.8K
Age
9y
Commits · 90 Days