8000 Using old cache while new data is being fetched · Issue #233 · jaemk/cached · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content
Using old cache while new data is being fetched #233
Open
@NCura

Description

@NCura

Hi there!

I’ve been using the cached crate for caching database calls in my project, and I’ve encountered a situation where I need to manually refresh the cache. Specifically, I have a function that is cached with cached and doesn't expire automatically. What I’d like to achieve is to manually refresh the cache while still serving the old cache data to users during the refresh process.

Here’s an example of how the cache is used in my project:

#[cached(
    ty = "UnboundCache<String, Vec<Tour>>",
    create = r##"{ UnboundCache::new() }"##,
    key = "String",
    convert = r##"{ "tours_cache_key".to_string() }"##,
    result = true
)]
pub async fn get_tours() -> Result<Vec<Tour>> {...}

Thanks to cached, the first time get_tours() is called, it fetches the data from the database and sets it in the cache. If the cache exists, the function simply returns the cached data.

I also have a separate function (clear_cache) that clears the cache and manually fetches the updated data:

async fn clear_cache() {
    use cached::Cached;

    GET_TOURS.lock().await.cache_clear();
    _ = get_tours().await;

    // Or use get_tours_prime_cache().await directly without clearing the cache
}

The issue is that once the cache is cleared, users have to wait for the fresh data to be fetched before receiving a response, which isn't ideal.

What I’m hoping to do is to continue serving the old cache while the new data is being fetched. Once the new data is fetched, I want to update the cache and serve the updated data on the next request.

Is there already a way to achieve this in the cached crate, or is it something I should implement myself?

Thanks in advance for your help!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0