Distributed cache and in-memory key/value data store. It can be used both as an embedded Go library and as a language-independent service.
With Olric, you can instantly create a fast, scalable, shared pool of RAM across a cluster of computers.
See Docker and Sample Code sections to get started!
At a glance
- Designed to share some transient, approximate, fast-changing data between servers,
- Embeddable but can be used as a language-independent service with olricd,
- Supports different eviction algorithms,
- Fast binary protocol,
- Highly available and horizontally scalable,
- Provides best-effort consistency guarantees without being a complete CP (indeed PA/EC) solution,
- Supports replication by default (with sync and async options),
- Quorum-based voting for replica control (Read/Write quorums),
- Supports atomic operations,
- Provides a plugin interface for service discovery daemons,
- Provides a locking primitive which inspired by SETNX of Redis.
Possible Use Cases
With this feature set, Olric is suitable to use as a distributed cache. But it also provides data replication, failure detection and simple anti-entropy services. So it can be used as an ordinary key/value data store to scale your cloud application.
Project Status
Olric is in early stages of development. The package API and client protocol may change without notification.
Table of Contents
Features
- Designed to share some transient, approximate, fast-changing data between servers,
- Accepts arbitrary types as value,
- Only in-memory,
- Implements a fast and simple binary protocol,
- Embeddable but can be used as a language-independent service with olricd,
- GC-friendly storage engine,
- O(1) running time for lookups,
- Supports atomic operations,
- Provides a lock implementation which can be used for non-critical purposes,
- Different eviction policies: LRU, MaxIdleDuration and Time-To-Live (TTL),
- Highly available,
- Horizontally scalable,
- Provides best-effort consistency guarantees without being a complete CP (indeed PA/EC) solution,
- Distributes load fairly among cluster members with a consistent hash function,
- Supports replication by default (with sync and async options),
- Quorum-based voting for replica control,
- Thread-safe by default,
- Provides a plugin interface for service discovery daemons and cloud providers,
- Provides a command-line-interface to access the cluster directly from the terminal,
- Supports different serialization formats. Gob, JSON and MessagePack are supported out of the box,
- Provides a locking primitive which inspired by SETNX of Redis.
See Architecture section to see details.
Planned Features
- Distributed queries over keys and values,
- Database backend for persistence,
- Anti-entropy system to repair inconsistencies in DMaps,
- Publish/Subscribe for messaging,
- Eviction listeners by using Publish/Subscribe,
- Memcached interface,
- Client implementations for different languages: Java, Python and JavaScript,
- Expose DMap API via HTTP.
Support
You feel free to ask any questions about Olric and possible integration problems.
You also feel free to open an issue on GitHub to report bugs and share feature requests.
Installing
With a correctly configured Golang environment:
go get -u github.com/buraksezer/olric
Then, install olricd and its siblings:
go install -v ./cmd/*
Now you should access olricd, olric-stats, olric-cli and olric-load on your path. You can just run olricd to start experimenting:
olricd -c cmd/olricd/olricd.yaml
See Configuration section to create your cluster properly.
Docker
You can launch olricd Docker container by running the following command.
33203322
Now you should access the olricd instance by using olric-cli. So you can build olric-cli by using the following command:
Now you are able to connect the olricd server:
help
Kubernetes
Olric is able to discover peers automatically on Kubernetes platform via olric-cloud-plugin. We have a very simple Kubernetes setup right now. In the near future, this will be a major development/improvement area for Olric.
If you have a running Kubernetes cluster, you can use the following command to deploy a new Olric cluster with 3 nodes:
If everything goes well, you should see something like that:
Now we have an Olric cluster on Kubernetes with 3 nodes. One of them is the cluster coordinator and manages the routing table for rest of the cluster.
olric-debug
olric-debug
Get a shell to the running container:
olric-cliolric-loadolric-stats
Congrats!
Bringing Olric into Kubernetes will be a major development area in the next releases.
Operation Modes
Olric has two different operation modes.
Embedded Member
In Embedded Member Mode, members include both the application and Olric data and services. The advantage of the Embedded Member Mode is having a low-latency data access and locality.
Client-Server
In the Client-Server deployment, Olric data and services are centralized in one or more server members and they are accessed by the application through clients. You can have a cluster of server members that can be independently created and scaled. Your clients communicate with these members to reach to Olric data and services on them.
Client-Server deployment has advantages including more predictable and reliable performance, easier identification of problem causes and, most importantly, better scalability. When you need to scale in this deployment type, just add more Olric server members. You can address client and server scalability concerns separately.
See olricd section to get started.
Currently we only have the official Golang client. A possible Python implementation is on the way. After stabilizing the Olric Binary Protocol, the others may appear quickly.
Tooling
Olric comes with some useful tools to interact with the cluster.
olricd
With olricd, you can create an Olric cluster with a few commands. This is how to install olricd:
Let's create a cluster with the following:
olricd -c <YOUR_CONFIG_FILE_PATH>
OLRICD_CONFIG
OLRICD_CONFIG=<YOUR_CONFIG_FILE_PATH> olricd
olricd.yaml
cmd/olricd/olricd.yaml
See Client-Server section to get more information about this deployment scenario.
olric-cli
olric-cli is the Olric command line interface, a simple program that allows to send commands to Olric, and read the replies sent by the server, directly from the terminal.
olric-cli
redis-cli
olric-cli
[127.0.0.1:3320] >> use mydmap
use mydmap
[127.0.0.1:3320] >> get mykey
myvalue
[127.0.0.1:3320] >>
The interactive mode also keeps command history. It's possible to send protocol commands as command line arguments:
olric-cli -d mydmap -c "put mykey myvalue"
Then, retrieve the key:
olric-cli -d mydmap -c "get mykey"
myvalue
olric-cli -h
olric-stats
Stats
olric-stats
Statistics about a partition:
olric-stats -p 69
PartID: 69
Owner: olric.node:3320
Previous Owners: not found
Backups: not found
DMap count: 1
DMaps:
Name: olric-load-test
Length: 1374
Allocated: 1048576
Inuse: 47946
Garbage: 0
olric-stats -a
-r
olric-stats -h
olric-load
olric-load simulates running commands done by N clients at the same time sending M total queries. It measures response time.
olric-load
Put127.0.0.1:3320msgpack
olric-load -c put -s msgpack -k 100000
### STATS FOR COMMAND: PUT ###
Serializer is msgpack
100000 requests completed in 1.209334678s
50 parallel clients
93% <= 1 milliseconds
5% <= 2 milliseconds
olric-load -h
Usage
Olric is designed to work efficiently with the minimum amount of configuration. So the default configuration should be enough for experimenting:
This creates an Olric object without running any server at background. In order to run Olric, you need to call Start method.
When you call Start method, your process joins the cluster and will be responsible for some parts of the data. This call blocks indefinitely. So you may need to run it in a goroutine. Of course, this is just a single-node instance, because you didn't give any configuration.
Create a DMap object to access the cluster:
DMap object has Put, PutEx, PutIf, PutIfEx, Get, Delete, Expire, LockWithTimeout and Destroy methods to access and modify data in Olric. We may add more methods for finer control but first, I'm willing to stabilize this set of features.
When you want to leave the cluster, just need to call Shutdown method:
This will stop background tasks and servers. Finally purges in-memory data and quits.
Please note that this section aims to document DMap API in embedded member mode. If you prefer to use Olric in Client-Server mode, please jump to Golang Client section.
Put
Put sets the value for the given key. It overwrites any previous value for that key and it's thread-safe.
string
PutIf
PutIf sets the value for the given key. It overwrites any previous value for that key and it's thread-safe.
string
Flag argument currently has two different options:
ErrFoundErrKeyNotFound
Sample use:
PutEx
PutEx sets the value for the given key with TTL. It overwrites any previous value for that key. It's thread-safe.
string
PutIfEx
PutIfEx sets the value for the given key with TTL. It overwrites any previous value for that key. It's thread-safe.
string
Flag argument currently has two different options:
ErrFoundErrKeyNotFound
Sample use:
Get
ErrKeyNotFound
It is safe to modify the contents of the returned value. It is safe to modify the contents of the argument after Get returns.
Expire
ErrKeyNotFound
stringtime.Duration
Delete
Delete deletes the value for the given key. Delete will not return error if key doesn't exist. It's thread-safe.
It is safe to modify the contents of the argument after Delete returns.
LockWithTimeout
LockWithTimeout sets a lock for the given key. If the lock is still unreleased the end of given period of time, it automatically releases the lock. Acquired lock is only for the key in this DMap.
LockContext
Creating a seperated DMap to keep locks may be a good idea.
You should know that the locks are approximate, and only to be used for non-critical purposes.
Please take a look at Lock Implementation section for implementation details.
Lock
Lock sets a lock for the given key. Acquired lock is only for the key in this DMap.
LockContext
You should know that the locks are approximate, and only to be used for non-critical purposes.
Unlock
ErrNoSuchLock
Destroy
Destroy flushes the given DMap on the cluster. You should know that there is no global lock on DMaps. So if you call Put/PutEx and Destroy methods concurrently on the cluster, Put/PutEx calls may set new values to the DMap.
Stats
Stats exposes some useful metrics to monitor an Olric node. It includes memory allocation metrics from partitions and the Go runtime metrics.
stats/stats.go
Ping
Ping sends a dummy protocol messsage to the given host. This is useful to measure RTT between hosts. It also can be used as aliveness check.
Query
Query runs a distributed query on a DMap instance. Olric supports a very simple query DSL and now, it only scans keys. The query DSL has very few keywords:
- $onKey: Runs the given query on keys or manages options on keys for a given query.
- $onValue: Runs the given query on values or manages options on values for a given query.
- $options: Useful to modify data returned from a query
Keywords for $options:
- $ignore: Ignores a value.
A distributed query looks like the following:
This query finds the keys starts with even:, drops the values and returns only keys. If you also want to retrieve the values, just remove the $options directive:
In order to iterate over all the keys:
This is how you call a distributed query over the cluster:
RangeCloseRange
Cursor
RangeClose
Range
ffalse
Close
CloseCursor
Atomic Operations
internal/lockerIncr
GetPut
PutGetPut
internal/locker
Important note about consistency:
You should know that Olric is a PA/EC (see Consistency and Replication Model) product. So if your network is stable, all the operations on key/value pairs are performed by a single cluster member. It means that you can be sure about the consistency when the cluster is stable. It's important to know that computer networks fail occasionally, processes crash and random GC pauses may happen. Many factors can lead a network partitioning. If you cannot tolerate losing strong consistency under network partitioning, you need to use a different tool for atomic operations.
See Hazelcast and the Mythical PA/EC System and Jepsen Analysis on Hazelcast 3.8.3 for more insight on this topic.
Incr
Incr atomically increments key by delta. The return value is the new value after being incremented or an error.
int
Decr
Decr atomically decrements key by delta. The return value is the new value after being decremented or an error.
int
GetPut
GetPut atomically sets key to value and returns the old value stored at key.
The returned value is an arbitrary type.
Pipelining
Olric Binary Protocol(OBP) supports pipelining. All protocol commands can be pushed to a remote Olric server through a pipeline in a single write call. A sample use looks like the following:
KeepAlive
Flush
Golang Client
This repo contains the official Golang client for Olric. It implements Olric Binary Protocol(OBP). With this client, you can access to Olric clusters in your Golang programs. In order to create a client instance:
round-robin
The official Golang client has its dedicated documentation. Please take a look at this.
Configuration
You should feel free to ask any questions about configuration and integration. Please see Support section.
Embedded-Member Mode
Olric provides a function to generate default configuration to use in embedded-member mode:
Newenv
See Sample Code section for an introduction.
Client-Server Mode
olricd.yaml
Network Configuration
BindAddr
BindAddrlocalhost127.0.0.1::1BindAddr0.0.0.0BindAddrBindAddrConfig.InterfaceConfig.MemberlistInterfaceBindAddrBindAddr
BindAddr0.0.0.0
Service Discovery
Olric provides a service discovery interface which can be used to implement plugins.
We currently have a bunch of service discovery plugins for automatic peer discovery on cloud environments:
In order to get more info about installation and configuration of the plugins, see their GitHub page.
Architecture
Overview
Olric uses:
- hashicorp/memberlist for cluster membership and failure detection,
- buraksezer/consistent for consistent hashing and load balancing,
- Different alternatives for serialization:
Olric distributes data among partitions. Every partition is being owned by a cluster member and may have one or more backups for redundancy. When you read or write a DMap entry, you transparently talk to the partition owner. Each request hits the most up-to-date version of a particular data entry in a stable cluster.
In order to find the partition which the key belongs to, Olric hashes the key and mod it with the number of partitions:
partID = MOD(hash result, partition count)
The partitions are being distributed among cluster members by using a consistent hashing algorithm. In order to get details, please see buraksezer/consistent.
When a new cluster is created, one of the instances is elected as the cluster coordinator. It manages the partition table:
- When a node joins or leaves, it distributes the partitions and their backups among the members again,
- Removes empty previous owners from the partition owners list,
- Pushes the new partition table to all the members,
- Pushes the partition table to the cluster periodically.
Members propagate their birthdate(POSIX time in nanoseconds) to the cluster. The coordinator is the oldest member in the cluster. If the coordinator leaves the cluster, the second oldest member gets elected as the coordinator.
Olric has a component called rebalancer which is responsible for keeping underlying data structures consistent:
- Works on every node,
- When a node joins or leaves, the cluster coordinator pushes the new partition table. Then, the rebalancer runs immediately and moves the partitions and backups to their new hosts,
- Merges fragmented partitions.
Partitions have a concept called owners list. When a node joins or leaves the cluster, a new primary owner may be assigned by the coordinator. At any time, a partition may have one or more partition owners. If a partition has two or more owners, this is called fragmented partition. The last added owner is called primary owner. Write operation is only done by the primary owner. The previous owners are only used for read and delete.
When you read a key, the primary owner tries to find the key on itself, first. Then, queries the previous owners and backups, respectively. The delete operation works the same way.
The data(distributed map objects) in the fragmented partition is moved slowly to the primary owner by the rebalancer. Until the move is done, the data remains available on the previous owners. The DMap methods use this list to query data on the cluster.
Please note that, 'multiple partition owners' is an undesirable situation and the rebalancer component is designed to fix that in a short time.
Consistency and Replication Model
Olric is an AP product in the context of CAP theorem, which employs the combination of primary-copy and optimistic replication techniques. With optimistic replication, when the partition owner receives a write or delete operation for a key, applies it locally, and propagates it to the backup owners.
This technique enables Olric clusters to offer high throughput. However, due to temporary situations in the system, such as network failure, backup owners can miss some updates and diverge from the primary owner. If a partition owner crashes while there is an inconsistency between itself and the backups, strong consistency of the data can be lost.
Two types of backup replication are available: sync and async. Both types are still implementations of the optimistic replication model.
- sync: Blocks until write/delete operation is applied by backup owners.
- async: Just fire & forget.
Last-write-wins conflict resolution
Every time a piece of data is written to Olric, a timestamp is attached by the client. Then, when Olric has to deal with conflict data in the case of network partitioning, it simply chooses the data with the most recent timestamp. This called LWW conflict resolution policy.
PACELC Theorem
From Wikipedia:
In the context of PACELC theorem, Olric is a PA/EC product. It means that Olric is considered to be consistent data store if the network is stable. Because the key space is divided between partitions and every partition is controlled by its primary owner. All operations on DMaps are redirected to the partition owner.
In the case of network partitioning, Olric chooses availability over consistency. So that you can still access some parts of the cluster when the network is unreliable, but the cluster may return inconsistent results.
Olric implements read-repair and quorum based voting system to deal with inconsistencies in the DMaps.
Readings on PACELC theorem:
Read-Repair on DMaps
Read repair is a feature that allows for inconsistent data to be fixed at query time. Olric tracks every write operation with a timestamp value and assumes that the latest write operation is the valid one. When you want to access a key/value pair, the partition owner retrieves all available copies for that pair and compares the timestamp values. The latest one is the winner. If there is some outdated version of the requested pair, the primary owner propagates the latest version of the pair.
Read-repair is disabled by default for the sake of performance. If you have a use case that requires a more strict consistency control than a distributed caching scenario, you can enable read-repair via the configuration.
Quorum-based replica control
ErrWriteQuorumErrReadQuorum
Simple Split-Brain Protection
MemberCountQuorum1
When the network healed, the stopped nodes joins again the cluster and fragmented partitions is merged by their primary owners in accordance with LWW policy. Olric also implements an ownership report mechanism to fix inconsistencies in partition distribution after a partitioning event.
Eviction
Olric supports different policies to evict keys from distributed maps.
Expire with TTL
Olric implements TTL eviction policy. It shares the same algorithm with Redis:
Periodically Redis tests a few keys at random among keys with an expire set. All the keys that are already expired are deleted from the keyspace.
Specifically this is what Redis does 10 times per second:
- Test 20 random keys from the set of keys with an associated expire.
- Delete all the keys found expired.
- If more than 25% of keys were expired, start again from step 1.
This is a trivial probabilistic algorithm, basically the assumption is that our sample is representative of the whole key space, and we continue to expire until the percentage of keys that are likely to be expired is under 25%
ErrKeyNotFound
Expire with MaxIdleDuration
Maximum time for each entry to stay idle in the DMap. It limits the lifetime of the entries relative to the time of the last read or write access performed on them. The entries whose idle period exceeds this limit are expired and evicted automatically. An entry is idle if no Get, Put, PutEx, Expire, PutIf, PutIfEx on it. Configuration of MaxIdleDuration feature varies by preferred deployment method.
Expire with LRU
Olric implements LRU eviction method on DMaps. Approximated LRU algorithm is borrowed from Redis. The Redis authors proposes the following algorithm:
It is important to understand that the eviction process works like this:
- A client runs a new command, resulting in more data added.
- Redis checks the memory usage, and if it is greater than the maxmemory limit , it evicts keys according to the policy.
- A new command is executed, and so forth.
So we continuously cross the boundaries of the memory limit, by going over it, and then by evicting keys to return back under the limits.
If a command results in a lot of memory being used (like a big set intersection stored into a new key) for some time the memory limit can be surpassed by a noticeable amount.
Approximated LRU algorithm
Redis LRU algorithm is not an exact implementation. This means that Redis is not able to pick the best candidate for eviction, that is, the access that was accessed the most in the past. Instead it will try to run an approximation of the LRU algorithm, by sampling a small number of keys, and evicting the one that is the best (with the oldest access time) among the sampled keys.
Olric tracks access time for every DMap instance. Then it picks and sorts some configurable amount of keys to select keys for eviction. Every node runs this algorithm independently. The access log is moved along with the partition when a network partition is occured.
Configuration of eviction mechanisms
olricd.yaml
cache:
numEvictionWorkers: 1
maxIdleDuration: ""
ttlDuration: "100s"
maxKeys: 100000
maxInuse: 1000000 # in bytes
lRUSamples: 10
evictionPolicy: "LRU" # NONE/LRU
foobar
dmaps:
foobar:
maxIdleDuration: "60s"
ttlDuration: "300s"
maxKeys: 500000 # in-bytes
lRUSamples: 20
evictionPolicy: "NONE" # NONE/LRU
If you prefer embedded-member deployment scenario, please take a look at config#CacheConfig and config#DMapCacheConfig for the configuration.
Lock Implementation
The DMap implementation is already thread-safe to meet your thread safety requirements. When you want to have more control on the concurrency, you can use LockWithTimeout and Lock methods. Olric borrows the locking algorithm from Redis. Redis authors propose the following algorithm:
The command is a simple way to implement a locking system with Redis.
A client can acquire the lock if the above command returns OK (or retry after some time if the command returns Nil), and remove the lock just using DEL.
The lock will be auto-released after the expire time is reached.
It is possible to make this system more robust modifying the unlock schema as follows:
Instead of setting a fixed string, set a non-guessable large random string, called token. Instead of releasing the lock with DEL, send a script that only removes the key if the value matches. This avoids that a client will try to release the lock after the expire time deleting the key created by another client that acquired the lock later.
SETNXPutIf(key, value, IfNotFound)
You should know that this implementation is subject to the clustering algorithm. So there is no guarantee about reliability in the case of network partitioning. I recommend the lock implementation to be used for efficiency purposes in general, instead of correctness.
Important note about consistency:
You should know that Olric is a PA/EC (see Consistency and Replication Model) product. So if your network is stable, all the operations on key/value pairs are performed by a single cluster member. It means that you can be sure about the consistency when the cluster is stable. It's important to know that computer networks fail occasionally, processes crash and random GC pauses may happen. Many factors can lead a network partitioning. If you cannot tolerate losing strong consistency under network partitioning, you need to use a different tool for locking.
See Hazelcast and the Mythical PA/EC System and Jepsen Analysis on Hazelcast 3.8.3 for more insight on this topic.
Storage Engine
Olric implements an append-only log file, indexed with a builtin map (uint64 => uint64). It creates new tables and evacuates existing data to the new ones if it needs to shrink or expand.
Sample Code
The following snipped can be run on your computer directly. It's a single-node setup, of course:
Contributions
Please don't hesitate to fork the project and send a pull request or just e-mail me to ask questions and share ideas.
License
The Apache License, Version 2.0 - see LICENSE for more details.
About the name
The inner voice of Turgut Özben who is the main character of Oğuz Atay's masterpiece -The Disconnected-.