• Stars
    star
    7,122
  • Rank 5,214 (Top 0.2 %)
  • Language
    Go
  • License
    Apache License 2.0
  • Created about 8 years ago
  • Updated 2 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,121
star
2

tipboard

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

php-protobuf

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

hermes

Fast and reliable message broker built on top of Kafka.
Java
787
star
5

allRank

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

turnilo

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

axion-release-plugin

Gradle release & version management plugin.
Groovy
538
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
484
star
9

typescript-strict-plugin

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

json-avro-converter

JSON to Avro conversion tool designed to make migration to Avro easier.
Groovy
270
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
214
star
14

allegro-api

Issue tracker and wiki for Allegro REST API
206
star
15

tradukisto

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

marathon-consul

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

restapi-guideline

Allegro REST API Guideline.
CSS
174
star
18

bigflow

A Python framework for data processing on GCP.
Python
114
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
96
star
21

akubra

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

elasticsearch-analysis-morfologik

Morfologik Polish Lemmatizer plugin for Elasticsearch
Java
81
star
23

ecto-cursor-based-stream

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

opel

OPEL - asynchronous expression language
Java
66
star
25

HerBERT

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

fogger

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

mesos-executor

Customizable Apache Mesos task executor
Go
49
star
28

selena

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

elasticsearch-reindex-tool

Elasticsearch reindexing tool.
Java
44
star
30

kafka-offset-monitor-graphite

Graphite reporter for Kafka Offset Monitor.
Scala
44
star
31

cassandra-modeling-kata

Cassandra Modeling Kata
Java
37
star
32

dotnet-utils

C#
33
star
33

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
34

slinger

Slinger - deep linking library for Android
Java
28
star
35

django-powerdns-dnssec

Django application managing PowerDNS database
Python
27
star
36

ralph-cli

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

mongo-migration-stream

Tool for online migrations of MongoDB databases.
Kotlin
26
star
38

allms

A versatile and powerful library designed to streamline the process of querying LLMs
Python
26
star
39

allegro.tech

TypeScript
23
star
40

hacktoberfest-dashboard

Allegro Hactoberfest activity dashboard
TypeScript
21
star
41

quanta

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

klejbenchmark-baselines

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

bigcache-bench

Benchmarks for BigCache project
Go
20
star
44

pyhermes

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

swiftbox

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

json-logic-kmp

Kotlin multiplatform JsonLogic expressions evaluation engine. Targets iOS and JVM (also Android).
Kotlin
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

newrelic-gradle-plugin

Newrelic Gradle plugin.
Groovy
17
star
50

map-with-indifferent-access

Elixir
17
star
51

grunt-maven-npm

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

leader-only-spring-boot-starter

Java
15
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

prometheus-net-metrics

C#
12
star
58

dotnet-sdk

C#
12
star
59

camus-compressor

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

consul-recipes

Java library for interacting with Consul.
Java
12
star
61

blog

SCSS
11
star
62

ralph_pricing

A pricing module for Ralph
Python
11
star
63

solr-fast-collapsing-query-parser

Java
9
star
64

inkpy-jinja

Generate PDF documents from ODT templates.
Python
8
star
65

allegro-tech-labs-microservices

Allegro Tech Labs Microservices workshop materials
Java
8
star
66

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.
8
star
67

TypedListAdapter

Kotlin
7
star
68

logextractx

Python
7
star
69

solr-ids-export-plugin

Java
6
star
70

django-bob

Django bob is a set of django helpers, widgets and form filters for Ralph DCIM/CMDB project .
JavaScript
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

warsztaty-podstawy-ml-03-2019

Machine learning basics workshop
Jupyter Notebook
4
star
78

selena-agent

Agent for Selena
Python
4
star
79

vaas-registration-hook

Go
3
star
80

swiftbox-config

Swift
3
star
81

braincode

HTML
3
star
82

oauth-mock

Kotlin
3
star
83

atm-hero-generator

JavaScript
2
star
84

swiftbox-metrics-statsd

Swift
2
star
85

eslint-plugin-test-comments

TypeScript
2
star
86

client-side-logic-dsl

Kotlin
2
star
87

parallel-test-execution-workshop

Resources for Parallel test execution workshop
Groovy
2
star
88

couchbase-commons

Kotlin
1
star
89

ml

TypeScript
1
star
90

hermes-page

Hermes OpenSource page.
HTML
1
star
91

json-cache

Java
1
star
92

swiftbox-logging

Swift
1
star
93

podcast.allegro.tech

CSS
1
star
94

axion-release-example

Kotlin
1
star
95

jobs-conf

allegro.tech jobs postings
HTML
1
star
96

allegro-tech-labs-iot

Allegro Tech Labs IoT workshop materials
Python
1
star
97

versionlens.nvim

1
star