Key-value cache RESP server with support for key expirations ⌛

Related tags

Caching bader-db
Overview

Unit Tests Crates.io

BADER-DB (بادِر)

Key-value cache RESP server with support for key expirations

Supported FeaturesGetting StartedBasic UsageCache EvictionTesting

This is a rust work-in-progress learning project and shouldn't be used in production.

Supported Feature

  • SET, GET and DELETE values — Set with or without an expiry date.
  • Expiry Format 🕰️ — Set your expiry in seconds (EX) or milliseconds (PX).
  • EXISTS 🏪 — Returns "true" if key exists or "false" otherwise.
  • Passive and Active Key Eviction — A memory-efficient probabilistic eviction algorithm similar to Redis.
  • Memory Safe 🛡️ — Ensures the latest value is always retrieved, handles race conditions.

Supported Commands

  • SET
  • GET
  • DEL
  • EXISTS

Getting Started

This crate is available on crates.io. The easiest way to use it is to add an entry to your Cargo.toml defining the dependency:

[dependencies]
bader-db = "0.1.5"

Basic Usage

The TCP server is built on Tokio to handle async connections, make sure you include it in your dependencies.

use bader_db::run_server;
use anyhow::Result;
use std::time::Duration;

#[tokio::main]
pub async fn main() -> Result<()> {
    env_logger::init();
    let port = std::env::var("PORT").unwrap_or("6379".to_string());
    let sample = 10;
    let threshold = 0.5;
    let frequency = Duration::from_millis(100);
    run_server(format!("127.0.0.1:{}", port).as_str(), sample, threshold, frequency).await;
    Ok(())
}

The run_server method will take the host and the eviction algorithm parameters.

Cache Eviction

The eviction algorithm parameters:

  • sample
  • frequency
  • threshold

Expiration of keys in the cache is performed at intervals, triggered every frequency and is done in the background. The approach for performing this task is based on the implementation in Redis, which is straightforward yet effective.

The following is a summary of the eviction process, explained in a clear way:

Wait for the next frequency tick.
Randomly select a batch of sample entries from the cache.
Check for and remove any expired entries found in the batch.
If the percentage of removed entries is greater than the threshold, go back to step 2; otherwise, go back to step 1.

This allows the user to control the aggressiveness of eviction by adjusting the values of threshold and frequency. It's important to keep in mind that the higher the threshold value, the more memory the cache will use on average.

Testing

There's a testing script to run the server, start the server in debug mode by running

$ RUST_LOG=debug cargo run --bin server_main 

You can use redis-cli to test the server. Simple install redis-cli and you can set a key using:

$ redis-cli set hello world

then you can get it using

$ redis-cli get hello

This should output world

You can also set with expiry in

  • Seconds using the EX flag
  • Milliseconds using the PX flag
$ redis-cli set hello world ex 100

This would make the value world live for 100 seconds being removed.

$ redis-cli set hello world px 100

This would make the value world live for 100 milliseconds being removed.

You can also run this simple script to set some values with different expirations and watch the logs as the eviction algorithm takes place.

use std::process::Command;
use std::{thread, time};

fn main() {
    println!("Started filling");

    for i in 10..7000 {
        let expiry = 10 * i;
        let sleep_time = time::Duration::from_nanos(100);
        thread::sleep(sleep_time);
        Command::new("redis-cli")
            .arg("set")
            .arg(i.to_string())
            .arg(i.to_string())
            .arg("PX")
            .arg(expiry.to_string())
            .spawn()
            .expect("ls command failed to start");
    }
    println!("Terminated.");
}
You might also like...
Turn your discord cache back to viewable images.

discache 🦀 Every time you view an Image in Discord, it gets saved in your cache folder as an unviewable file. Discache allows you to convert those fi

Non-volatile, distributed file cache backed by content-addressed storage

blobnet A low-latency file server that responds to requests for chunks of file data. This acts as a non-volatile, over-the-network content cache. Inte

Rust type wrapper to cache hash of potentially large structures.

CachedHash For a type T, CachedHashT wraps T and implements Hash in a way that caches T's hash value. This is useful when T is expensive to hash (fo

A generational arena based LRU Cache implementation in 100% safe rust.

generational-lru Crate providing a 100% safe, generational arena based LRU cache implementation. use generational_lru::lrucache::{LRUCache, CacheError

This is a Rust implementation for popular caches (support no_std).

Caches This is a Rust implementation for popular caches (support no_std). See Introduction, Installation and Usages for more details. English | 简体中文 I

Solana JSON-RPC caching server

Solana JSON-RPC caching server Disclaimer: This project is an early stage Work-In-Progress and is not ready for production use. This cache server impl

General basic key-value structs for Key-Value based storages

General basic key-value structs for Key-Value based storages

Easy c̵̰͠r̵̛̠ö̴̪s̶̩̒s̵̭̀-t̶̲͝h̶̯̚r̵̺͐e̷̖̽ḁ̴̍d̶̖̔ ȓ̵͙ė̶͎ḟ̴͙e̸̖͛r̶̖͗ë̶̱́ṉ̵̒ĉ̷̥e̷͚̍ s̷̹͌h̷̲̉a̵̭͋r̷̫̊ḭ̵̊n̷̬͂g̵̦̃ f̶̻̊ơ̵̜ṟ̸̈́ R̵̞̋ù̵̺s̷̖̅ţ̸͗!̸̼͋

Rust S̵̓i̸̓n̵̉ I̴n̴f̶e̸r̵n̷a̴l mutability! Howdy, friendly Rust developer! Ever had a value get m̵̯̅ð̶͊v̴̮̾ê̴̼͘d away right under your nose just when

Key-Value based in-memory cache library which supports Custom Expiration Policies

Endorphin Key-Value based in-memory cache library which supports Custom Expiration Policies with standard HashMap, HashSet interface. use endorphin::H

A lightweight key-value cache system developed for experimental purposes

A lightweight key-value cache system developed for experimental purposes. It can also include distributed systems setup if I can.

Fast turbo remote cache server written in Rust

Fast turbo remote cache server written in Rust. if you are using turbo and you want to have a self hosted remote cache server this is for you.

Immutable Ordered Key-Value Database Engine

PumpkinDB Build status (Linux) Build status (Windows) Project status Usable, between alpha and beta Production-readiness Depends on your risk toleranc

Distributed transactional key-value database, originally created to complement TiDB
Distributed transactional key-value database, originally created to complement TiDB

Website | Documentation | Community Chat TiKV is an open-source, distributed, and transactional key-value database. Unlike other traditional NoSQL sys

PickleDB-rs is a lightweight and simple key-value store. It is a Rust version for Python's PickleDB

PickleDB PickleDB is a lightweight and simple key-value store written in Rust, heavily inspired by Python's PickleDB PickleDB is fun and easy to use u

CLI tool to work with Sled key-value databases.

sledtool CLI tool to work with Sled key-value databases. $ sledtool --help Usage: sledtool dbpath command [args] CLI tool to work with Sled da

AgateDB is an embeddable, persistent and fast key-value (KV) database written in pure Rust

AgateDB is an embeddable, persistent and fast key-value (KV) database written in pure Rust. It is designed as an experimental engine for the TiKV project, and will bring aggressive optimizations for TiKV specifically.

Pure rust embeddable key-value store database.

MHdb is a pure Rust database implementation, based on dbm. See crate documentation. Changelog v1.0.3 Update Cargo.toml v1.0.2 Update Cargo.toml v1.0.1

LevelDB is a fast key-value storage library written at Google that provides an ordered mapping from string keys to string values.

LevelDB is a fast key-value storage library written at Google that provides an ordered mapping from string keys to string values. Authors: Sanjay Ghem

ForestDB - A Fast Key-Value Storage Engine Based on Hierarchical B+-Tree Trie

ForestDB is a key-value storage engine developed by Couchbase Caching and Storage Team, and its main index structure is built from Hierarchic

Releases(v0.1.5)
Owner
Mahmoud Salem
Software Engineer
Mahmoud Salem
A lightweight key-value cache system developed for experimental purposes

A lightweight key-value cache system developed for experimental purposes. It can also include distributed systems setup if I can.

Burak Selim Senyurt 8 Jul 23, 2022
Rust cache structures and easy function memoization

cached Caching structures and simplified function memoization cached provides implementations of several caching structures as well as a handy macro f

James Kominick 996 Jan 7, 2023
This is a Rust implementation for HashiCorp's golang-lru. This crate contains three LRU based cache, LRUCache, TwoQueueCache and AdaptiveCache.

This is a Rust implementation for HashiCorp's golang-lru. This crate contains three LRU based cache, LRUCache, TwoQueueCache and AdaptiveCache.

Al Liu 84 Jan 3, 2023
A native stateless cache implementation.

fBNC fBNC, Blockchain Native Cache. A native stateless storage library for block chain. Its value is to improve the stability and security of online s

Findora Foundation 1 Jan 12, 2022
Stretto is a Rust implementation for ristretto. A high performance memory-bound Rust cache.

Stretto is a Rust implementation for ristretto. A high performance memory-bound Rust cache.

Al Liu 310 Dec 29, 2022
A general-purpose distributed memory cache system compatible with Memcached

memcrsd memcached server implementation in Rust memcrsd is a key value store implementation in Rust. It is compatible with binary protocol of memcache

null 274 Dec 14, 2022
ConstDB - an in-memory cache store which aims at master-master replications

A redis-like cache store that implements CRDTs and active-active replications.

null 27 Aug 15, 2022
A set of safe Least Recently Used (LRU) map/cache types for Rust

LruMap A set of safe Least-Recently-Used (LRU) cache types aimed at providing flexible map-like structures that automatically evict the least recently

Khonsu Labs 4 Sep 24, 2022
Read-optimized cache of Cardano on-chain entities

Read-optimized cache of Cardano on-chain entities Intro Scrolls is a tool for building and maintaining read-optimized collections of Cardano's on-chai

TxPipe 58 Dec 2, 2022
A read-only, memory-mapped cache.

mmap-cache A low-level API for a memory-mapped cache of a read-only key-value store. Design The [Cache] index is an [fst::Map], which maps from arbitr

Duncan 3 Jun 28, 2022