#cache #ttl #expire #expiring

ttl_cache_with_purging

A time-to-live (TTL) cache implementation with optional background purging for expired entries

1 unstable release

0.1.0 May 16, 2023

#155 in Caching

Download history 20/week @ 2023-12-17 13/week @ 2023-12-31 19/week @ 2024-01-07 108/week @ 2024-01-14 71/week @ 2024-01-21 68/week @ 2024-01-28 16/week @ 2024-02-04 45/week @ 2024-02-11 135/week @ 2024-02-18 98/week @ 2024-02-25 87/week @ 2024-03-03 115/week @ 2024-03-10 13/week @ 2024-03-17 75/week @ 2024-03-24 115/week @ 2024-03-31

322 downloads per month

MIT/Apache

11KB
155 lines

ttl_cache_with_purging

A time-to-live (TTL) cache implementation with optional background purging for expired entries.

Motivation

We needed a caching implementation that would not return expired entries, while also preventing expired entries from unnecessarily inflating the cache size.

Approach

This TTL cache includes a background purge thread that will remove expired cache entries on a specified interval. The purge thread uses tokio to take advantage of its write-preferring RwLock.

Example

use std::{
    sync::Arc,
    time::{Duration, SystemTime},
};

use tokio::{sync::RwLock, time::interval};
use ttl_cache_with_purging::{cache::TtlCache, purging::start_periodic_purge};

const MIN_IN_SECS: u64 = 60;
const HOUR_IN_SECS: u64 = 60 * MIN_IN_SECS;

#[tokio::main(flavor = "current_thread")]
async fn main() {
    // Cache setup
    let cache = Arc::new(RwLock::new(TtlCache::new()));
    let purge_interval = interval(Duration::from_secs(MIN_IN_SECS));
    start_periodic_purge(cache.clone(), purge_interval);

    // Add entries
    let key = "key1";
    let val = "val1";

    let expires_at = SystemTime::now()
        .checked_add(Duration::from_secs(HOUR_IN_SECS))
        .unwrap();
    cache.write().await.insert(key, val, expires_at);

    // Read entries
    let _cached_val = cache.read().await.get(key).unwrap();
    let (_cached_val, _expires_at) = cache.read().await.get_value_and_expiration(key).unwrap();
}

License

Licensed under either of

at your option.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

Code of Conduct

All behavior is governed by the Rust Code of Conduct.

Dependencies

~2.3–4MB
~65K SLoC