• Stars
    star
    7,508
  • Rank 5,134 (Top 0.2 %)
  • Language
    Go
  • License
    Apache License 2.0
  • Created over 8 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Efficient cache for gigabytes of data written in Go.

BigCache Build Status Coverage Status GoDoc Go Report Card

Fast, concurrent, evicting in-memory cache written to keep big number of entries without impact on performance. BigCache keeps entries on heap but omits GC for them. To achieve that, operations on byte slices take place, therefore entries (de)serialization in front of the cache will be needed in most use cases.

Requires Go 1.12 or newer.

Usage

Simple initialization

import (
	"fmt"
	"context"
	"github.com/allegro/bigcache/v3"
)

cache, _ := bigcache.New(context.Background(), bigcache.DefaultConfig(10 * time.Minute))

cache.Set("my-unique-key", []byte("value"))

entry, _ := cache.Get("my-unique-key")
fmt.Println(string(entry))

Custom initialization

When cache load can be predicted in advance then it is better to use custom initialization because additional memory allocation can be avoided in that way.

import (
	"log"

	"github.com/allegro/bigcache/v3"
)

config := bigcache.Config {
		// number of shards (must be a power of 2)
		Shards: 1024,

		// time after which entry can be evicted
		LifeWindow: 10 * time.Minute,

		// Interval between removing expired entries (clean up).
		// If set to <= 0 then no action is performed.
		// Setting to < 1 second is counterproductive — bigcache has a one second resolution.
		CleanWindow: 5 * time.Minute,

		// rps * lifeWindow, used only in initial memory allocation
		MaxEntriesInWindow: 1000 * 10 * 60,

		// max entry size in bytes, used only in initial memory allocation
		MaxEntrySize: 500,

		// prints information about additional memory allocation
		Verbose: true,

		// cache will not allocate more memory than this limit, value in MB
		// if value is reached then the oldest entries can be overridden for the new ones
		// 0 value means no size limit
		HardMaxCacheSize: 8192,

		// callback fired when the oldest entry is removed because of its expiration time or no space left
		// for the new entry, or because delete was called. A bitmask representing the reason will be returned.
		// Default value is nil which means no callback and it prevents from unwrapping the oldest entry.
		OnRemove: nil,

		// OnRemoveWithReason is a callback fired when the oldest entry is removed because of its expiration time or no space left
		// for the new entry, or because delete was called. A constant representing the reason will be passed through.
		// Default value is nil which means no callback and it prevents from unwrapping the oldest entry.
		// Ignored if OnRemove is specified.
		OnRemoveWithReason: nil,
	}

cache, initErr := bigcache.New(context.Background(), config)
if initErr != nil {
	log.Fatal(initErr)
}

cache.Set("my-unique-key", []byte("value"))

if entry, err := cache.Get("my-unique-key"); err == nil {
	fmt.Println(string(entry))
}

LifeWindow & CleanWindow

  1. LifeWindow is a time. After that time, an entry can be called dead but not deleted.

  2. CleanWindow is a time. After that time, all the dead entries will be deleted, but not the entries that still have life.

Three caches were compared: bigcache, freecache and map. Benchmark tests were made using an i7-6700K CPU @ 4.00GHz with 32GB of RAM on Ubuntu 18.04 LTS (5.2.12-050212-generic).

Benchmarks source code can be found here

Writes and reads

go version
go version go1.13 linux/amd64

go test -bench=. -benchmem -benchtime=4s ./... -timeout 30m
goos: linux
goarch: amd64
pkg: github.com/allegro/bigcache/v3/caches_bench
BenchmarkMapSet-8                     	12999889	       376 ns/op	     199 B/op	       3 allocs/op
BenchmarkConcurrentMapSet-8           	 4355726	      1275 ns/op	     337 B/op	       8 allocs/op
BenchmarkFreeCacheSet-8               	11068976	       703 ns/op	     328 B/op	       2 allocs/op
BenchmarkBigCacheSet-8                	10183717	       478 ns/op	     304 B/op	       2 allocs/op
BenchmarkMapGet-8                     	16536015	       324 ns/op	      23 B/op	       1 allocs/op
BenchmarkConcurrentMapGet-8           	13165708	       401 ns/op	      24 B/op	       2 allocs/op
BenchmarkFreeCacheGet-8               	10137682	       690 ns/op	     136 B/op	       2 allocs/op
BenchmarkBigCacheGet-8                	11423854	       450 ns/op	     152 B/op	       4 allocs/op
BenchmarkBigCacheSetParallel-8        	34233472	       148 ns/op	     317 B/op	       3 allocs/op
BenchmarkFreeCacheSetParallel-8       	34222654	       268 ns/op	     350 B/op	       3 allocs/op
BenchmarkConcurrentMapSetParallel-8   	19635688	       240 ns/op	     200 B/op	       6 allocs/op
BenchmarkBigCacheGetParallel-8        	60547064	        86.1 ns/op	     152 B/op	       4 allocs/op
BenchmarkFreeCacheGetParallel-8       	50701280	       147 ns/op	     136 B/op	       3 allocs/op
BenchmarkConcurrentMapGetParallel-8   	27353288	       175 ns/op	      24 B/op	       2 allocs/op
PASS
ok  	github.com/allegro/bigcache/v3/caches_bench	256.257s

Writes and reads in bigcache are faster than in freecache. Writes to map are the slowest.

GC pause time

go version
go version go1.13 linux/amd64

go run caches_gc_overhead_comparison.go

Number of entries:  20000000
GC pause for bigcache:  1.506077ms
GC pause for freecache:  5.594416ms
GC pause for map:  9.347015ms
go version
go version go1.13 linux/arm64

go run caches_gc_overhead_comparison.go
Number of entries:  20000000
GC pause for bigcache:  22.382827ms
GC pause for freecache:  41.264651ms
GC pause for map:  72.236853ms

Test shows how long are the GC pauses for caches filled with 20mln of entries. Bigcache and freecache have very similar GC pause time.

Memory usage

You may encounter system memory reporting what appears to be an exponential increase, however this is expected behaviour. Go runtime allocates memory in chunks or 'spans' and will inform the OS when they are no longer required by changing their state to 'idle'. The 'spans' will remain part of the process resource usage until the OS needs to repurpose the address. Further reading available here.

How it works

BigCache relies on optimization presented in 1.5 version of Go (issue-9477). This optimization states that if map without pointers in keys and values is used then GC will omit its content. Therefore BigCache uses map[uint64]uint32 where keys are hashed and values are offsets of entries.

Entries are kept in byte slices, to omit GC again. Byte slices size can grow to gigabytes without impact on performance because GC will only see single pointer to it.

Collisions

BigCache does not handle collisions. When new item is inserted and it's hash collides with previously stored item, new item overwrites previously stored value.

Bigcache vs Freecache

Both caches provide the same core features but they reduce GC overhead in different ways. Bigcache relies on map[uint64]uint32, freecache implements its own mapping built on slices to reduce number of pointers.

Results from benchmark tests are presented above. One of the advantage of bigcache over freecache is that you don’t need to know the size of the cache in advance, because when bigcache is full, it can allocate additional memory for new entries instead of overwriting existing ones as freecache does currently. However hard max size in bigcache also can be set, check HardMaxCacheSize.

HTTP Server

This package also includes an easily deployable HTTP implementation of BigCache, which can be found in the server package.

More

Bigcache genesis is described in allegro.tech blog post: writing a very fast cache service in Go

License

BigCache is released under the Apache 2.0 license (see LICENSE)

More Repositories

1

ralph

Ralph is the CMDB / Asset Management system for data center and back office hardware.
Python
2,200
star
2

tipboard

Tipboard - in-house, tasty, local dashboarding system
JavaScript
1,106
star
3

php-protobuf

PHP Protobuf - Google's Protocol Buffers for PHP
PHP
911
star
4

allRank

allRank is a framework for training learning-to-rank neural models based on PyTorch.
Python
842
star
5

hermes

Fast and reliable message broker built on top of Kafka.
Java
808
star
6

turnilo

Business intelligence, data exploration and visualization web application for Druid, formerly known as Swiv and Pivot
TypeScript
725
star
7

axion-release-plugin

Gradle release & version management plugin.
Groovy
556
star
8

node-worker-nodes

A node.js library to run cpu-intensive tasks in a separate processes and not block the event loop.
JavaScript
489
star
9

typescript-strict-plugin

Typescript plugin that allows turning on strict mode in specific files or directories.
TypeScript
337
star
10

json-avro-converter

JSON to Avro conversion tool designed to make migration to Avro easier.
Groovy
275
star
11

embedded-elasticsearch

Tool that ease up creation of integration tests with Elasticsearch
Java
269
star
12

vaas

VaaS
Python
229
star
13

grunt-maven-plugin

Grunt + Maven integration done right
Java
213
star
14

allegro-api

Issue tracker and wiki for Allegro REST API
212
star
15

tradukisto

A Java i18n library created to convert numbers to their word representations.
Groovy
203
star
16

marathon-consul

Integrates Marathon apps with Consul service discovery.
Go
190
star
17

restapi-guideline

Allegro REST API Guideline.
CSS
183
star
18

bigflow

A Python framework for data processing on GCP.
Python
116
star
19

handlebars-spring-boot-starter

Spring Boot auto-configuration for Handlebars
Groovy
109
star
20

envoy-control

Envoy Control is a platform-agnostic, production-ready Control Plane for Service Mesh based on Envoy Proxy.
Kotlin
98
star
21

akubra

Simple solution to keep a independent S3 storages in sync
Go
86
star
22

elasticsearch-analysis-morfologik

Morfologik Polish Lemmatizer plugin for Elasticsearch
Java
83
star
23

ecto-cursor-based-stream

Elixir library that allows for cursor-based streaming of Ecto records, that does not require database transaction.
Elixir
81
star
24

allms

A versatile and powerful library designed to streamline the process of querying LLMs
Python
70
star
25

opel

OPEL - asynchronous expression language
Java
68
star
26

HerBERT

HerBERT is a BERT-based Language Model trained on Polish Corpora using only MLM objective with dynamic masking of whole words.
64
star
27

fogger

Fogger - a library to create blurred background under Android's UI elements
Java
60
star
28

mesos-executor

Customizable Apache Mesos task executor
Go
49
star
29

json-logic-kmp

Kotlin multiplatform JsonLogic expressions evaluation engine. Targets iOS and JVM (also Android).
Kotlin
49
star
30

elasticsearch-reindex-tool

Elasticsearch reindexing tool.
Java
45
star
31

selena

SELENA is a tool used to test website performance by measuring response times or verifying the content of replies.
JavaScript
45
star
32

kafka-offset-monitor-graphite

Graphite reporter for Kafka Offset Monitor.
Scala
44
star
33

dotnet-utils

C#
37
star
34

cassandra-modeling-kata

Cassandra Modeling Kata
Java
36
star
35

mongo-migration-stream

Tool for online migrations of MongoDB databases.
Kotlin
33
star
36

swift-junit

A Swift library for creating JUnit XML test results that can be interpreted by tools such as Bamboo or Jenkins. Macos and Linux ready.
Swift
29
star
37

slinger

Slinger - deep linking library for Android
Java
29
star
38

django-powerdns-dnssec

Django application managing PowerDNS database
Python
27
star
39

ralph-cli

Command-line interface for the Ralph system.
Go
26
star
40

allegro.tech

TypeScript
23
star
41

hacktoberfest-dashboard

Allegro Hactoberfest activity dashboard
TypeScript
23
star
42

klejbenchmark-baselines

Fine-tuning scripts for evaluating transformer-based models on KLEJ benchmark.
Python
23
star
43

quanta

Fast image optimization as a service, based on mozjpeg, written in Swift
C
21
star
44

bigcache-bench

Benchmarks for BigCache project
Go
20
star
45

pyhermes

The Python interface to the Hermes message broker.
Python
19
star
46

swiftbox

SwiftBox is a package that helps building Swift/Vapor microservices.
Swift
19
star
47

consul-registration-hook

Hook that can be used for synchronous registration and deregistration in Consul discovery service on Kubernetes or Mesos cluster with Allegro executor
Go
18
star
48

marathon-appcop

Marathon applications law enforcement
Go
18
star
49

leader-only-spring-boot-starter

Java
17
star
50

newrelic-gradle-plugin

Newrelic Gradle plugin.
Groovy
17
star
51

map-with-indifferent-access

Elixir
17
star
52

grunt-maven-npm

npm tasks for grunt-maven-plugin 1.2+
JavaScript
16
star
53

redux-storage-decorator-engines

Composing decorator for redux-storage to use different storage types
JavaScript
15
star
54

spunit

Spunit – Spock elegance in Kotlin JUnit 5 tests
Kotlin
14
star
55

cosmosdb-utils

A collection of useful Azure CosmosDb SDK v3 extensions and utilities, developed as part of Allegro Pay product.
C#
13
star
56

envoy-perf-pprof

Convenient Envoy on-CPU performance analysis with perf and pprof.
Dockerfile
13
star
57

dotnet-sdk

C#
12
star
58

prometheus-net-metrics

C#
12
star
59

camus-compressor

Camus Compressor merges files created by Camus and saves them in a compressed format.
Java
12
star
60

blog

HTML
11
star
61

consul-recipes

Java library for interacting with Consul.
Java
11
star
62

ralph_pricing

A pricing module for Ralph
Python
11
star
63

solr-fast-collapsing-query-parser

Java
9
star
64

klejbenchmark-allegroreviews

Allegro Reviews is a sentiment analysis dataset, consisting of 11,588 product reviews written in Polish and extracted from Allegro.pl - a popular e-commerce marketplace.
9
star
65

inkpy-jinja

Generate PDF documents from ODT templates.
Python
8
star
66

allegro-tech-labs-microservices

Allegro Tech Labs Microservices workshop materials
Java
8
star
67

TypedListAdapter

Kotlin
7
star
68

logextractx

Python
7
star
69

django-bob

Django bob is a set of django helpers, widgets and form filters for Ralph DCIM/CMDB project .
JavaScript
7
star
70

solr-ids-export-plugin

Java
6
star
71

toper

PHP Rest client based on popular Guzzle Rest Client.
PHP
6
star
72

atm-event-app

ATM event application
JavaScript
5
star
73

application-insights

5
star
74

graphql-extended-audit-intstrumentation

Java
5
star
75

votakvot

Python
5
star
76

banana-split

JavaScript
5
star
77

conformal-prediction-wut

Jupyter Notebook
5
star
78

AlleNoise

Python
4
star
79

warsztaty-podstawy-ml-03-2019

Machine learning basics workshop
Jupyter Notebook
4
star
80

selena-agent

Agent for Selena
Python
4
star
81

json-cache

Java
3
star
82

swiftbox-config

Swift
3
star
83

vaas-registration-hook

Go
3
star
84

braincode

HTML
3
star
85

oauth-mock

Kotlin
3
star
86

parallel-test-execution-workshop

Resources for Parallel test execution workshop
Groovy
3
star
87

swiftbox-metrics-statsd

Swift
2
star
88

atm-hero-generator

JavaScript
2
star
89

client-side-logic-dsl

Kotlin
2
star
90

eslint-plugin-test-comments

TypeScript
2
star
91

couchbase-commons

Kotlin
1
star
92

hermes-page

Hermes OpenSource page.
HTML
1
star
93

ml

TypeScript
1
star
94

swiftbox-logging

Swift
1
star
95

podcast.allegro.tech

CSS
1
star
96

axion-release-example

Kotlin
1
star
97

jobs-conf

allegro.tech jobs postings
HTML
1
star
98

allegro-tech-labs-iot

Allegro Tech Labs IoT workshop materials
Python
1
star
99

versionlens.nvim

1
star