You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

957 lines
37 KiB

  1. bbolt
  2. =====
  3. [![Go Report Card](https://goreportcard.com/badge/github.com/etcd-io/bbolt?style=flat-square)](https://goreportcard.com/report/github.com/etcd-io/bbolt)
  4. [![Coverage](https://codecov.io/gh/etcd-io/bbolt/branch/master/graph/badge.svg)](https://codecov.io/gh/etcd-io/bbolt)
  5. [![Build Status Travis](https://img.shields.io/travis/etcd-io/bboltlabs.svg?style=flat-square&&branch=master)](https://travis-ci.com/etcd-io/bbolt)
  6. [![Godoc](http://img.shields.io/badge/go-documentation-blue.svg?style=flat-square)](https://godoc.org/github.com/etcd-io/bbolt)
  7. [![Releases](https://img.shields.io/github/release/etcd-io/bbolt/all.svg?style=flat-square)](https://github.com/etcd-io/bbolt/releases)
  8. [![LICENSE](https://img.shields.io/github/license/etcd-io/bbolt.svg?style=flat-square)](https://github.com/etcd-io/bbolt/blob/master/LICENSE)
  9. bbolt is a fork of [Ben Johnson's][gh_ben] [Bolt][bolt] key/value
  10. store. The purpose of this fork is to provide the Go community with an active
  11. maintenance and development target for Bolt; the goal is improved reliability
  12. and stability. bbolt includes bug fixes, performance enhancements, and features
  13. not found in Bolt while preserving backwards compatibility with the Bolt API.
  14. Bolt is a pure Go key/value store inspired by [Howard Chu's][hyc_symas]
  15. [LMDB project][lmdb]. The goal of the project is to provide a simple,
  16. fast, and reliable database for projects that don't require a full database
  17. server such as Postgres or MySQL.
  18. Since Bolt is meant to be used as such a low-level piece of functionality,
  19. simplicity is key. The API will be small and only focus on getting values
  20. and setting values. That's it.
  21. [gh_ben]: https://github.com/benbjohnson
  22. [bolt]: https://github.com/boltdb/bolt
  23. [hyc_symas]: https://twitter.com/hyc_symas
  24. [lmdb]: http://symas.com/mdb/
  25. ## Project Status
  26. Bolt is stable, the API is fixed, and the file format is fixed. Full unit
  27. test coverage and randomized black box testing are used to ensure database
  28. consistency and thread safety. Bolt is currently used in high-load production
  29. environments serving databases as large as 1TB. Many companies such as
  30. Shopify and Heroku use Bolt-backed services every day.
  31. ## Project versioning
  32. bbolt uses [semantic versioning](http://semver.org).
  33. API should not change between patch and minor releases.
  34. New minor versions may add additional features to the API.
  35. ## Table of Contents
  36. - [Getting Started](#getting-started)
  37. - [Installing](#installing)
  38. - [Opening a database](#opening-a-database)
  39. - [Transactions](#transactions)
  40. - [Read-write transactions](#read-write-transactions)
  41. - [Read-only transactions](#read-only-transactions)
  42. - [Batch read-write transactions](#batch-read-write-transactions)
  43. - [Managing transactions manually](#managing-transactions-manually)
  44. - [Using buckets](#using-buckets)
  45. - [Using key/value pairs](#using-keyvalue-pairs)
  46. - [Autoincrementing integer for the bucket](#autoincrementing-integer-for-the-bucket)
  47. - [Iterating over keys](#iterating-over-keys)
  48. - [Prefix scans](#prefix-scans)
  49. - [Range scans](#range-scans)
  50. - [ForEach()](#foreach)
  51. - [Nested buckets](#nested-buckets)
  52. - [Database backups](#database-backups)
  53. - [Statistics](#statistics)
  54. - [Read-Only Mode](#read-only-mode)
  55. - [Mobile Use (iOS/Android)](#mobile-use-iosandroid)
  56. - [Resources](#resources)
  57. - [Comparison with other databases](#comparison-with-other-databases)
  58. - [Postgres, MySQL, & other relational databases](#postgres-mysql--other-relational-databases)
  59. - [LevelDB, RocksDB](#leveldb-rocksdb)
  60. - [LMDB](#lmdb)
  61. - [Caveats & Limitations](#caveats--limitations)
  62. - [Reading the Source](#reading-the-source)
  63. - [Other Projects Using Bolt](#other-projects-using-bolt)
  64. ## Getting Started
  65. ### Installing
  66. To start using Bolt, install Go and run `go get`:
  67. ```sh
  68. $ go get go.etcd.io/bbolt/...
  69. ```
  70. This will retrieve the library and install the `bolt` command line utility into
  71. your `$GOBIN` path.
  72. ### Importing bbolt
  73. To use bbolt as an embedded key-value store, import as:
  74. ```go
  75. import bolt "go.etcd.io/bbolt"
  76. db, err := bolt.Open(path, 0666, nil)
  77. if err != nil {
  78. return err
  79. }
  80. defer db.Close()
  81. ```
  82. ### Opening a database
  83. The top-level object in Bolt is a `DB`. It is represented as a single file on
  84. your disk and represents a consistent snapshot of your data.
  85. To open your database, simply use the `bolt.Open()` function:
  86. ```go
  87. package main
  88. import (
  89. "log"
  90. bolt "go.etcd.io/bbolt"
  91. )
  92. func main() {
  93. // Open the my.db data file in your current directory.
  94. // It will be created if it doesn't exist.
  95. db, err := bolt.Open("my.db", 0600, nil)
  96. if err != nil {
  97. log.Fatal(err)
  98. }
  99. defer db.Close()
  100. ...
  101. }
  102. ```
  103. Please note that Bolt obtains a file lock on the data file so multiple processes
  104. cannot open the same database at the same time. Opening an already open Bolt
  105. database will cause it to hang until the other process closes it. To prevent
  106. an indefinite wait you can pass a timeout option to the `Open()` function:
  107. ```go
  108. db, err := bolt.Open("my.db", 0600, &bolt.Options{Timeout: 1 * time.Second})
  109. ```
  110. ### Transactions
  111. Bolt allows only one read-write transaction at a time but allows as many
  112. read-only transactions as you want at a time. Each transaction has a consistent
  113. view of the data as it existed when the transaction started.
  114. Individual transactions and all objects created from them (e.g. buckets, keys)
  115. are not thread safe. To work with data in multiple goroutines you must start
  116. a transaction for each one or use locking to ensure only one goroutine accesses
  117. a transaction at a time. Creating transaction from the `DB` is thread safe.
  118. Transactions should not depend on one another and generally shouldn't be opened
  119. simultaneously in the same goroutine. This can cause a deadlock as the read-write
  120. transaction needs to periodically re-map the data file but it cannot do so while
  121. any read-only transaction is open. Even a nested read-only transaction can cause
  122. a deadlock, as the child transaction can block the parent transaction from releasing
  123. its resources.
  124. #### Read-write transactions
  125. To start a read-write transaction, you can use the `DB.Update()` function:
  126. ```go
  127. err := db.Update(func(tx *bolt.Tx) error {
  128. ...
  129. return nil
  130. })
  131. ```
  132. Inside the closure, you have a consistent view of the database. You commit the
  133. transaction by returning `nil` at the end. You can also rollback the transaction
  134. at any point by returning an error. All database operations are allowed inside
  135. a read-write transaction.
  136. Always check the return error as it will report any disk failures that can cause
  137. your transaction to not complete. If you return an error within your closure
  138. it will be passed through.
  139. #### Read-only transactions
  140. To start a read-only transaction, you can use the `DB.View()` function:
  141. ```go
  142. err := db.View(func(tx *bolt.Tx) error {
  143. ...
  144. return nil
  145. })
  146. ```
  147. You also get a consistent view of the database within this closure, however,
  148. no mutating operations are allowed within a read-only transaction. You can only
  149. retrieve buckets, retrieve values, and copy the database within a read-only
  150. transaction.
  151. #### Batch read-write transactions
  152. Each `DB.Update()` waits for disk to commit the writes. This overhead
  153. can be minimized by combining multiple updates with the `DB.Batch()`
  154. function:
  155. ```go
  156. err := db.Batch(func(tx *bolt.Tx) error {
  157. ...
  158. return nil
  159. })
  160. ```
  161. Concurrent Batch calls are opportunistically combined into larger
  162. transactions. Batch is only useful when there are multiple goroutines
  163. calling it.
  164. The trade-off is that `Batch` can call the given
  165. function multiple times, if parts of the transaction fail. The
  166. function must be idempotent and side effects must take effect only
  167. after a successful return from `DB.Batch()`.
  168. For example: don't display messages from inside the function, instead
  169. set variables in the enclosing scope:
  170. ```go
  171. var id uint64
  172. err := db.Batch(func(tx *bolt.Tx) error {
  173. // Find last key in bucket, decode as bigendian uint64, increment
  174. // by one, encode back to []byte, and add new key.
  175. ...
  176. id = newValue
  177. return nil
  178. })
  179. if err != nil {
  180. return ...
  181. }
  182. fmt.Println("Allocated ID %d", id)
  183. ```
  184. #### Managing transactions manually
  185. The `DB.View()` and `DB.Update()` functions are wrappers around the `DB.Begin()`
  186. function. These helper functions will start the transaction, execute a function,
  187. and then safely close your transaction if an error is returned. This is the
  188. recommended way to use Bolt transactions.
  189. However, sometimes you may want to manually start and end your transactions.
  190. You can use the `DB.Begin()` function directly but **please** be sure to close
  191. the transaction.
  192. ```go
  193. // Start a writable transaction.
  194. tx, err := db.Begin(true)
  195. if err != nil {
  196. return err
  197. }
  198. defer tx.Rollback()
  199. // Use the transaction...
  200. _, err := tx.CreateBucket([]byte("MyBucket"))
  201. if err != nil {
  202. return err
  203. }
  204. // Commit the transaction and check for error.
  205. if err := tx.Commit(); err != nil {
  206. return err
  207. }
  208. ```
  209. The first argument to `DB.Begin()` is a boolean stating if the transaction
  210. should be writable.
  211. ### Using buckets
  212. Buckets are collections of key/value pairs within the database. All keys in a
  213. bucket must be unique. You can create a bucket using the `Tx.CreateBucket()`
  214. function:
  215. ```go
  216. db.Update(func(tx *bolt.Tx) error {
  217. b, err := tx.CreateBucket([]byte("MyBucket"))
  218. if err != nil {
  219. return fmt.Errorf("create bucket: %s", err)
  220. }
  221. return nil
  222. })
  223. ```
  224. You can also create a bucket only if it doesn't exist by using the
  225. `Tx.CreateBucketIfNotExists()` function. It's a common pattern to call this
  226. function for all your top-level buckets after you open your database so you can
  227. guarantee that they exist for future transactions.
  228. To delete a bucket, simply call the `Tx.DeleteBucket()` function.
  229. ### Using key/value pairs
  230. To save a key/value pair to a bucket, use the `Bucket.Put()` function:
  231. ```go
  232. db.Update(func(tx *bolt.Tx) error {
  233. b := tx.Bucket([]byte("MyBucket"))
  234. err := b.Put([]byte("answer"), []byte("42"))
  235. return err
  236. })
  237. ```
  238. This will set the value of the `"answer"` key to `"42"` in the `MyBucket`
  239. bucket. To retrieve this value, we can use the `Bucket.Get()` function:
  240. ```go
  241. db.View(func(tx *bolt.Tx) error {
  242. b := tx.Bucket([]byte("MyBucket"))
  243. v := b.Get([]byte("answer"))
  244. fmt.Printf("The answer is: %s\n", v)
  245. return nil
  246. })
  247. ```
  248. The `Get()` function does not return an error because its operation is
  249. guaranteed to work (unless there is some kind of system failure). If the key
  250. exists then it will return its byte slice value. If it doesn't exist then it
  251. will return `nil`. It's important to note that you can have a zero-length value
  252. set to a key which is different than the key not existing.
  253. Use the `Bucket.Delete()` function to delete a key from the bucket.
  254. Please note that values returned from `Get()` are only valid while the
  255. transaction is open. If you need to use a value outside of the transaction
  256. then you must use `copy()` to copy it to another byte slice.
  257. ### Autoincrementing integer for the bucket
  258. By using the `NextSequence()` function, you can let Bolt determine a sequence
  259. which can be used as the unique identifier for your key/value pairs. See the
  260. example below.
  261. ```go
  262. // CreateUser saves u to the store. The new user ID is set on u once the data is persisted.
  263. func (s *Store) CreateUser(u *User) error {
  264. return s.db.Update(func(tx *bolt.Tx) error {
  265. // Retrieve the users bucket.
  266. // This should be created when the DB is first opened.
  267. b := tx.Bucket([]byte("users"))
  268. // Generate ID for the user.
  269. // This returns an error only if the Tx is closed or not writeable.
  270. // That can't happen in an Update() call so I ignore the error check.
  271. id, _ := b.NextSequence()
  272. u.ID = int(id)
  273. // Marshal user data into bytes.
  274. buf, err := json.Marshal(u)
  275. if err != nil {
  276. return err
  277. }
  278. // Persist bytes to users bucket.
  279. return b.Put(itob(u.ID), buf)
  280. })
  281. }
  282. // itob returns an 8-byte big endian representation of v.
  283. func itob(v int) []byte {
  284. b := make([]byte, 8)
  285. binary.BigEndian.PutUint64(b, uint64(v))
  286. return b
  287. }
  288. type User struct {
  289. ID int
  290. ...
  291. }
  292. ```
  293. ### Iterating over keys
  294. Bolt stores its keys in byte-sorted order within a bucket. This makes sequential
  295. iteration over these keys extremely fast. To iterate over keys we'll use a
  296. `Cursor`:
  297. ```go
  298. db.View(func(tx *bolt.Tx) error {
  299. // Assume bucket exists and has keys
  300. b := tx.Bucket([]byte("MyBucket"))
  301. c := b.Cursor()
  302. for k, v := c.First(); k != nil; k, v = c.Next() {
  303. fmt.Printf("key=%s, value=%s\n", k, v)
  304. }
  305. return nil
  306. })
  307. ```
  308. The cursor allows you to move to a specific point in the list of keys and move
  309. forward or backward through the keys one at a time.
  310. The following functions are available on the cursor:
  311. ```
  312. First() Move to the first key.
  313. Last() Move to the last key.
  314. Seek() Move to a specific key.
  315. Next() Move to the next key.
  316. Prev() Move to the previous key.
  317. ```
  318. Each of those functions has a return signature of `(key []byte, value []byte)`.
  319. When you have iterated to the end of the cursor then `Next()` will return a
  320. `nil` key. You must seek to a position using `First()`, `Last()`, or `Seek()`
  321. before calling `Next()` or `Prev()`. If you do not seek to a position then
  322. these functions will return a `nil` key.
  323. During iteration, if the key is non-`nil` but the value is `nil`, that means
  324. the key refers to a bucket rather than a value. Use `Bucket.Bucket()` to
  325. access the sub-bucket.
  326. #### Prefix scans
  327. To iterate over a key prefix, you can combine `Seek()` and `bytes.HasPrefix()`:
  328. ```go
  329. db.View(func(tx *bolt.Tx) error {
  330. // Assume bucket exists and has keys
  331. c := tx.Bucket([]byte("MyBucket")).Cursor()
  332. prefix := []byte("1234")
  333. for k, v := c.Seek(prefix); k != nil && bytes.HasPrefix(k, prefix); k, v = c.Next() {
  334. fmt.Printf("key=%s, value=%s\n", k, v)
  335. }
  336. return nil
  337. })
  338. ```
  339. #### Range scans
  340. Another common use case is scanning over a range such as a time range. If you
  341. use a sortable time encoding such as RFC3339 then you can query a specific
  342. date range like this:
  343. ```go
  344. db.View(func(tx *bolt.Tx) error {
  345. // Assume our events bucket exists and has RFC3339 encoded time keys.
  346. c := tx.Bucket([]byte("Events")).Cursor()
  347. // Our time range spans the 90's decade.
  348. min := []byte("1990-01-01T00:00:00Z")
  349. max := []byte("2000-01-01T00:00:00Z")
  350. // Iterate over the 90's.
  351. for k, v := c.Seek(min); k != nil && bytes.Compare(k, max) <= 0; k, v = c.Next() {
  352. fmt.Printf("%s: %s\n", k, v)
  353. }
  354. return nil
  355. })
  356. ```
  357. Note that, while RFC3339 is sortable, the Golang implementation of RFC3339Nano does not use a fixed number of digits after the decimal point and is therefore not sortable.
  358. #### ForEach()
  359. You can also use the function `ForEach()` if you know you'll be iterating over
  360. all the keys in a bucket:
  361. ```go
  362. db.View(func(tx *bolt.Tx) error {
  363. // Assume bucket exists and has keys
  364. b := tx.Bucket([]byte("MyBucket"))
  365. b.ForEach(func(k, v []byte) error {
  366. fmt.Printf("key=%s, value=%s\n", k, v)
  367. return nil
  368. })
  369. return nil
  370. })
  371. ```
  372. Please note that keys and values in `ForEach()` are only valid while
  373. the transaction is open. If you need to use a key or value outside of
  374. the transaction, you must use `copy()` to copy it to another byte
  375. slice.
  376. ### Nested buckets
  377. You can also store a bucket in a key to create nested buckets. The API is the
  378. same as the bucket management API on the `DB` object:
  379. ```go
  380. func (*Bucket) CreateBucket(key []byte) (*Bucket, error)
  381. func (*Bucket) CreateBucketIfNotExists(key []byte) (*Bucket, error)
  382. func (*Bucket) DeleteBucket(key []byte) error
  383. ```
  384. Say you had a multi-tenant application where the root level bucket was the account bucket. Inside of this bucket was a sequence of accounts which themselves are buckets. And inside the sequence bucket you could have many buckets pertaining to the Account itself (Users, Notes, etc) isolating the information into logical groupings.
  385. ```go
  386. // createUser creates a new user in the given account.
  387. func createUser(accountID int, u *User) error {
  388. // Start the transaction.
  389. tx, err := db.Begin(true)
  390. if err != nil {
  391. return err
  392. }
  393. defer tx.Rollback()
  394. // Retrieve the root bucket for the account.
  395. // Assume this has already been created when the account was set up.
  396. root := tx.Bucket([]byte(strconv.FormatUint(accountID, 10)))
  397. // Setup the users bucket.
  398. bkt, err := root.CreateBucketIfNotExists([]byte("USERS"))
  399. if err != nil {
  400. return err
  401. }
  402. // Generate an ID for the new user.
  403. userID, err := bkt.NextSequence()
  404. if err != nil {
  405. return err
  406. }
  407. u.ID = userID
  408. // Marshal and save the encoded user.
  409. if buf, err := json.Marshal(u); err != nil {
  410. return err
  411. } else if err := bkt.Put([]byte(strconv.FormatUint(u.ID, 10)), buf); err != nil {
  412. return err
  413. }
  414. // Commit the transaction.
  415. if err := tx.Commit(); err != nil {
  416. return err
  417. }
  418. return nil
  419. }
  420. ```
  421. ### Database backups
  422. Bolt is a single file so it's easy to backup. You can use the `Tx.WriteTo()`
  423. function to write a consistent view of the database to a writer. If you call
  424. this from a read-only transaction, it will perform a hot backup and not block
  425. your other database reads and writes.
  426. By default, it will use a regular file handle which will utilize the operating
  427. system's page cache. See the [`Tx`](https://godoc.org/go.etcd.io/bbolt#Tx)
  428. documentation for information about optimizing for larger-than-RAM datasets.
  429. One common use case is to backup over HTTP so you can use tools like `cURL` to
  430. do database backups:
  431. ```go
  432. func BackupHandleFunc(w http.ResponseWriter, req *http.Request) {
  433. err := db.View(func(tx *bolt.Tx) error {
  434. w.Header().Set("Content-Type", "application/octet-stream")
  435. w.Header().Set("Content-Disposition", `attachment; filename="my.db"`)
  436. w.Header().Set("Content-Length", strconv.Itoa(int(tx.Size())))
  437. _, err := tx.WriteTo(w)
  438. return err
  439. })
  440. if err != nil {
  441. http.Error(w, err.Error(), http.StatusInternalServerError)
  442. }
  443. }
  444. ```
  445. Then you can backup using this command:
  446. ```sh
  447. $ curl http://localhost/backup > my.db
  448. ```
  449. Or you can open your browser to `http://localhost/backup` and it will download
  450. automatically.
  451. If you want to backup to another file you can use the `Tx.CopyFile()` helper
  452. function.
  453. ### Statistics
  454. The database keeps a running count of many of the internal operations it
  455. performs so you can better understand what's going on. By grabbing a snapshot
  456. of these stats at two points in time we can see what operations were performed
  457. in that time range.
  458. For example, we could start a goroutine to log stats every 10 seconds:
  459. ```go
  460. go func() {
  461. // Grab the initial stats.
  462. prev := db.Stats()
  463. for {
  464. // Wait for 10s.
  465. time.Sleep(10 * time.Second)
  466. // Grab the current stats and diff them.
  467. stats := db.Stats()
  468. diff := stats.Sub(&prev)
  469. // Encode stats to JSON and print to STDERR.
  470. json.NewEncoder(os.Stderr).Encode(diff)
  471. // Save stats for the next loop.
  472. prev = stats
  473. }
  474. }()
  475. ```
  476. It's also useful to pipe these stats to a service such as statsd for monitoring
  477. or to provide an HTTP endpoint that will perform a fixed-length sample.
  478. ### Read-Only Mode
  479. Sometimes it is useful to create a shared, read-only Bolt database. To this,
  480. set the `Options.ReadOnly` flag when opening your database. Read-only mode
  481. uses a shared lock to allow multiple processes to read from the database but
  482. it will block any processes from opening the database in read-write mode.
  483. ```go
  484. db, err := bolt.Open("my.db", 0666, &bolt.Options{ReadOnly: true})
  485. if err != nil {
  486. log.Fatal(err)
  487. }
  488. ```
  489. ### Mobile Use (iOS/Android)
  490. Bolt is able to run on mobile devices by leveraging the binding feature of the
  491. [gomobile](https://github.com/golang/mobile) tool. Create a struct that will
  492. contain your database logic and a reference to a `*bolt.DB` with a initializing
  493. constructor that takes in a filepath where the database file will be stored.
  494. Neither Android nor iOS require extra permissions or cleanup from using this method.
  495. ```go
  496. func NewBoltDB(filepath string) *BoltDB {
  497. db, err := bolt.Open(filepath+"/demo.db", 0600, nil)
  498. if err != nil {
  499. log.Fatal(err)
  500. }
  501. return &BoltDB{db}
  502. }
  503. type BoltDB struct {
  504. db *bolt.DB
  505. ...
  506. }
  507. func (b *BoltDB) Path() string {
  508. return b.db.Path()
  509. }
  510. func (b *BoltDB) Close() {
  511. b.db.Close()
  512. }
  513. ```
  514. Database logic should be defined as methods on this wrapper struct.
  515. To initialize this struct from the native language (both platforms now sync
  516. their local storage to the cloud. These snippets disable that functionality for the
  517. database file):
  518. #### Android
  519. ```java
  520. String path;
  521. if (android.os.Build.VERSION.SDK_INT >=android.os.Build.VERSION_CODES.LOLLIPOP){
  522. path = getNoBackupFilesDir().getAbsolutePath();
  523. } else{
  524. path = getFilesDir().getAbsolutePath();
  525. }
  526. Boltmobiledemo.BoltDB boltDB = Boltmobiledemo.NewBoltDB(path)
  527. ```
  528. #### iOS
  529. ```objc
  530. - (void)demo {
  531. NSString* path = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,
  532. NSUserDomainMask,
  533. YES) objectAtIndex:0];
  534. GoBoltmobiledemoBoltDB * demo = GoBoltmobiledemoNewBoltDB(path);
  535. [self addSkipBackupAttributeToItemAtPath:demo.path];
  536. //Some DB Logic would go here
  537. [demo close];
  538. }
  539. - (BOOL)addSkipBackupAttributeToItemAtPath:(NSString *) filePathString
  540. {
  541. NSURL* URL= [NSURL fileURLWithPath: filePathString];
  542. assert([[NSFileManager defaultManager] fileExistsAtPath: [URL path]]);
  543. NSError *error = nil;
  544. BOOL success = [URL setResourceValue: [NSNumber numberWithBool: YES]
  545. forKey: NSURLIsExcludedFromBackupKey error: &error];
  546. if(!success){
  547. NSLog(@"Error excluding %@ from backup %@", [URL lastPathComponent], error);
  548. }
  549. return success;
  550. }
  551. ```
  552. ## Resources
  553. For more information on getting started with Bolt, check out the following articles:
  554. * [Intro to BoltDB: Painless Performant Persistence](http://npf.io/2014/07/intro-to-boltdb-painless-performant-persistence/) by [Nate Finch](https://github.com/natefinch).
  555. * [Bolt -- an embedded key/value database for Go](https://www.progville.com/go/bolt-embedded-db-golang/) by Progville
  556. ## Comparison with other databases
  557. ### Postgres, MySQL, & other relational databases
  558. Relational databases structure data into rows and are only accessible through
  559. the use of SQL. This approach provides flexibility in how you store and query
  560. your data but also incurs overhead in parsing and planning SQL statements. Bolt
  561. accesses all data by a byte slice key. This makes Bolt fast to read and write
  562. data by key but provides no built-in support for joining values together.
  563. Most relational databases (with the exception of SQLite) are standalone servers
  564. that run separately from your application. This gives your systems
  565. flexibility to connect multiple application servers to a single database
  566. server but also adds overhead in serializing and transporting data over the
  567. network. Bolt runs as a library included in your application so all data access
  568. has to go through your application's process. This brings data closer to your
  569. application but limits multi-process access to the data.
  570. ### LevelDB, RocksDB
  571. LevelDB and its derivatives (RocksDB, HyperLevelDB) are similar to Bolt in that
  572. they are libraries bundled into the application, however, their underlying
  573. structure is a log-structured merge-tree (LSM tree). An LSM tree optimizes
  574. random writes by using a write ahead log and multi-tiered, sorted files called
  575. SSTables. Bolt uses a B+tree internally and only a single file. Both approaches
  576. have trade-offs.
  577. If you require a high random write throughput (>10,000 w/sec) or you need to use
  578. spinning disks then LevelDB could be a good choice. If your application is
  579. read-heavy or does a lot of range scans then Bolt could be a good choice.
  580. One other important consideration is that LevelDB does not have transactions.
  581. It supports batch writing of key/values pairs and it supports read snapshots
  582. but it will not give you the ability to do a compare-and-swap operation safely.
  583. Bolt supports fully serializable ACID transactions.
  584. ### LMDB
  585. Bolt was originally a port of LMDB so it is architecturally similar. Both use
  586. a B+tree, have ACID semantics with fully serializable transactions, and support
  587. lock-free MVCC using a single writer and multiple readers.
  588. The two projects have somewhat diverged. LMDB heavily focuses on raw performance
  589. while Bolt has focused on simplicity and ease of use. For example, LMDB allows
  590. several unsafe actions such as direct writes for the sake of performance. Bolt
  591. opts to disallow actions which can leave the database in a corrupted state. The
  592. only exception to this in Bolt is `DB.NoSync`.
  593. There are also a few differences in API. LMDB requires a maximum mmap size when
  594. opening an `mdb_env` whereas Bolt will handle incremental mmap resizing
  595. automatically. LMDB overloads the getter and setter functions with multiple
  596. flags whereas Bolt splits these specialized cases into their own functions.
  597. ## Caveats & Limitations
  598. It's important to pick the right tool for the job and Bolt is no exception.
  599. Here are a few things to note when evaluating and using Bolt:
  600. * Bolt is good for read intensive workloads. Sequential write performance is
  601. also fast but random writes can be slow. You can use `DB.Batch()` or add a
  602. write-ahead log to help mitigate this issue.
  603. * Bolt uses a B+tree internally so there can be a lot of random page access.
  604. SSDs provide a significant performance boost over spinning disks.
  605. * Try to avoid long running read transactions. Bolt uses copy-on-write so
  606. old pages cannot be reclaimed while an old transaction is using them.
  607. * Byte slices returned from Bolt are only valid during a transaction. Once the
  608. transaction has been committed or rolled back then the memory they point to
  609. can be reused by a new page or can be unmapped from virtual memory and you'll
  610. see an `unexpected fault address` panic when accessing it.
  611. * Bolt uses an exclusive write lock on the database file so it cannot be
  612. shared by multiple processes.
  613. * Be careful when using `Bucket.FillPercent`. Setting a high fill percent for
  614. buckets that have random inserts will cause your database to have very poor
  615. page utilization.
  616. * Use larger buckets in general. Smaller buckets causes poor page utilization
  617. once they become larger than the page size (typically 4KB).
  618. * Bulk loading a lot of random writes into a new bucket can be slow as the
  619. page will not split until the transaction is committed. Randomly inserting
  620. more than 100,000 key/value pairs into a single new bucket in a single
  621. transaction is not advised.
  622. * Bolt uses a memory-mapped file so the underlying operating system handles the
  623. caching of the data. Typically, the OS will cache as much of the file as it
  624. can in memory and will release memory as needed to other processes. This means
  625. that Bolt can show very high memory usage when working with large databases.
  626. However, this is expected and the OS will release memory as needed. Bolt can
  627. handle databases much larger than the available physical RAM, provided its
  628. memory-map fits in the process virtual address space. It may be problematic
  629. on 32-bits systems.
  630. * The data structures in the Bolt database are memory mapped so the data file
  631. will be endian specific. This means that you cannot copy a Bolt file from a
  632. little endian machine to a big endian machine and have it work. For most
  633. users this is not a concern since most modern CPUs are little endian.
  634. * Because of the way pages are laid out on disk, Bolt cannot truncate data files
  635. and return free pages back to the disk. Instead, Bolt maintains a free list
  636. of unused pages within its data file. These free pages can be reused by later
  637. transactions. This works well for many use cases as databases generally tend
  638. to grow. However, it's important to note that deleting large chunks of data
  639. will not allow you to reclaim that space on disk.
  640. For more information on page allocation, [see this comment][page-allocation].
  641. [page-allocation]: https://github.com/boltdb/bolt/issues/308#issuecomment-74811638
  642. ## Reading the Source
  643. Bolt is a relatively small code base (<5KLOC) for an embedded, serializable,
  644. transactional key/value database so it can be a good starting point for people
  645. interested in how databases work.
  646. The best places to start are the main entry points into Bolt:
  647. - `Open()` - Initializes the reference to the database. It's responsible for
  648. creating the database if it doesn't exist, obtaining an exclusive lock on the
  649. file, reading the meta pages, & memory-mapping the file.
  650. - `DB.Begin()` - Starts a read-only or read-write transaction depending on the
  651. value of the `writable` argument. This requires briefly obtaining the "meta"
  652. lock to keep track of open transactions. Only one read-write transaction can
  653. exist at a time so the "rwlock" is acquired during the life of a read-write
  654. transaction.
  655. - `Bucket.Put()` - Writes a key/value pair into a bucket. After validating the
  656. arguments, a cursor is used to traverse the B+tree to the page and position
  657. where they key & value will be written. Once the position is found, the bucket
  658. materializes the underlying page and the page's parent pages into memory as
  659. "nodes". These nodes are where mutations occur during read-write transactions.
  660. These changes get flushed to disk during commit.
  661. - `Bucket.Get()` - Retrieves a key/value pair from a bucket. This uses a cursor
  662. to move to the page & position of a key/value pair. During a read-only
  663. transaction, the key and value data is returned as a direct reference to the
  664. underlying mmap file so there's no allocation overhead. For read-write
  665. transactions, this data may reference the mmap file or one of the in-memory
  666. node values.
  667. - `Cursor` - This object is simply for traversing the B+tree of on-disk pages
  668. or in-memory nodes. It can seek to a specific key, move to the first or last
  669. value, or it can move forward or backward. The cursor handles the movement up
  670. and down the B+tree transparently to the end user.
  671. - `Tx.Commit()` - Converts the in-memory dirty nodes and the list of free pages
  672. into pages to be written to disk. Writing to disk then occurs in two phases.
  673. First, the dirty pages are written to disk and an `fsync()` occurs. Second, a
  674. new meta page with an incremented transaction ID is written and another
  675. `fsync()` occurs. This two phase write ensures that partially written data
  676. pages are ignored in the event of a crash since the meta page pointing to them
  677. is never written. Partially written meta pages are invalidated because they
  678. are written with a checksum.
  679. If you have additional notes that could be helpful for others, please submit
  680. them via pull request.
  681. ## Other Projects Using Bolt
  682. Below is a list of public, open source projects that use Bolt:
  683. * [Algernon](https://github.com/xyproto/algernon) - A HTTP/2 web server with built-in support for Lua. Uses BoltDB as the default database backend.
  684. * [Bazil](https://bazil.org/) - A file system that lets your data reside where it is most convenient for it to reside.
  685. * [bolter](https://github.com/hasit/bolter) - Command-line app for viewing BoltDB file in your terminal.
  686. * [boltcli](https://github.com/spacewander/boltcli) - the redis-cli for boltdb with Lua script support.
  687. * [BoltHold](https://github.com/timshannon/bolthold) - An embeddable NoSQL store for Go types built on BoltDB
  688. * [BoltStore](https://github.com/yosssi/boltstore) - Session store using Bolt.
  689. * [Boltdb Boilerplate](https://github.com/bobintornado/boltdb-boilerplate) - Boilerplate wrapper around bolt aiming to make simple calls one-liners.
  690. * [BoltDbWeb](https://github.com/evnix/boltdbweb) - A web based GUI for BoltDB files.
  691. * [bleve](http://www.blevesearch.com/) - A pure Go search engine similar to ElasticSearch that uses Bolt as the default storage backend.
  692. * [btcwallet](https://github.com/btcsuite/btcwallet) - A bitcoin wallet.
  693. * [buckets](https://github.com/joyrexus/buckets) - a bolt wrapper streamlining
  694. simple tx and key scans.
  695. * [cayley](https://github.com/google/cayley) - Cayley is an open-source graph database using Bolt as optional backend.
  696. * [ChainStore](https://github.com/pressly/chainstore) - Simple key-value interface to a variety of storage engines organized as a chain of operations.
  697. * [Consul](https://github.com/hashicorp/consul) - Consul is service discovery and configuration made easy. Distributed, highly available, and datacenter-aware.
  698. * [DVID](https://github.com/janelia-flyem/dvid) - Added Bolt as optional storage engine and testing it against Basho-tuned leveldb.
  699. * [dcrwallet](https://github.com/decred/dcrwallet) - A wallet for the Decred cryptocurrency.
  700. * [drive](https://github.com/odeke-em/drive) - drive is an unofficial Google Drive command line client for \*NIX operating systems.
  701. * [event-shuttle](https://github.com/sclasen/event-shuttle) - A Unix system service to collect and reliably deliver messages to Kafka.
  702. * [Freehold](http://tshannon.bitbucket.org/freehold/) - An open, secure, and lightweight platform for your files and data.
  703. * [Go Report Card](https://goreportcard.com/) - Go code quality report cards as a (free and open source) service.
  704. * [GoWebApp](https://github.com/josephspurrier/gowebapp) - A basic MVC web application in Go using BoltDB.
  705. * [GoShort](https://github.com/pankajkhairnar/goShort) - GoShort is a URL shortener written in Golang and BoltDB for persistent key/value storage and for routing it's using high performent HTTPRouter.
  706. * [gopherpit](https://github.com/gopherpit/gopherpit) - A web service to manage Go remote import paths with custom domains
  707. * [gokv](https://github.com/philippgille/gokv) - Simple key-value store abstraction and implementations for Go (Redis, Consul, etcd, bbolt, BadgerDB, LevelDB, Memcached, DynamoDB, S3, PostgreSQL, MongoDB, CockroachDB and many more)
  708. * [Gitchain](https://github.com/gitchain/gitchain) - Decentralized, peer-to-peer Git repositories aka "Git meets Bitcoin".
  709. * [InfluxDB](https://influxdata.com) - Scalable datastore for metrics, events, and real-time analytics.
  710. * [ipLocator](https://github.com/AndreasBriese/ipLocator) - A fast ip-geo-location-server using bolt with bloom filters.
  711. * [ipxed](https://github.com/kelseyhightower/ipxed) - Web interface and api for ipxed.
  712. * [Ironsmith](https://github.com/timshannon/ironsmith) - A simple, script-driven continuous integration (build - > test -> release) tool, with no external dependencies
  713. * [Kala](https://github.com/ajvb/kala) - Kala is a modern job scheduler optimized to run on a single node. It is persistent, JSON over HTTP API, ISO 8601 duration notation, and dependent jobs.
  714. * [Key Value Access Langusge (KVAL)](https://github.com/kval-access-language) - A proposed grammar for key-value datastores offering a bbolt binding.
  715. * [LedisDB](https://github.com/siddontang/ledisdb) - A high performance NoSQL, using Bolt as optional storage.
  716. * [lru](https://github.com/crowdriff/lru) - Easy to use Bolt-backed Least-Recently-Used (LRU) read-through cache with chainable remote stores.
  717. * [mbuckets](https://github.com/abhigupta912/mbuckets) - A Bolt wrapper that allows easy operations on multi level (nested) buckets.
  718. * [MetricBase](https://github.com/msiebuhr/MetricBase) - Single-binary version of Graphite.
  719. * [MuLiFS](https://github.com/dankomiocevic/mulifs) - Music Library Filesystem creates a filesystem to organise your music files.
  720. * [NATS](https://github.com/nats-io/nats-streaming-server) - NATS Streaming uses bbolt for message and metadata storage.
  721. * [Operation Go: A Routine Mission](http://gocode.io) - An online programming game for Golang using Bolt for user accounts and a leaderboard.
  722. * [photosite/session](https://godoc.org/bitbucket.org/kardianos/photosite/session) - Sessions for a photo viewing site.
  723. * [Prometheus Annotation Server](https://github.com/oliver006/prom_annotation_server) - Annotation server for PromDash & Prometheus service monitoring system.
  724. * [reef-pi](https://github.com/reef-pi/reef-pi) - reef-pi is an award winning, modular, DIY reef tank controller using easy to learn electronics based on a Raspberry Pi.
  725. * [Request Baskets](https://github.com/darklynx/request-baskets) - A web service to collect arbitrary HTTP requests and inspect them via REST API or simple web UI, similar to [RequestBin](http://requestb.in/) service
  726. * [Seaweed File System](https://github.com/chrislusf/seaweedfs) - Highly scalable distributed key~file system with O(1) disk read.
  727. * [stow](https://github.com/djherbis/stow) - a persistence manager for objects
  728. backed by boltdb.
  729. * [Storm](https://github.com/asdine/storm) - Simple and powerful ORM for BoltDB.
  730. * [SimpleBolt](https://github.com/xyproto/simplebolt) - A simple way to use BoltDB. Deals mainly with strings.
  731. * [Skybox Analytics](https://github.com/skybox/skybox) - A standalone funnel analysis tool for web analytics.
  732. * [Scuttlebutt](https://github.com/benbjohnson/scuttlebutt) - Uses Bolt to store and process all Twitter mentions of GitHub projects.
  733. * [tentacool](https://github.com/optiflows/tentacool) - REST api server to manage system stuff (IP, DNS, Gateway...) on a linux server.
  734. * [torrent](https://github.com/anacrolix/torrent) - Full-featured BitTorrent client package and utilities in Go. BoltDB is a storage backend in development.
  735. * [Wiki](https://github.com/peterhellberg/wiki) - A tiny wiki using Goji, BoltDB and Blackfriday.
  736. If you are using Bolt in a project please send a pull request to add it to the list.