FastAPICache.Clear(namespace...) does not work with custom key_builder · Issue #571 · long2ice/fastapi-cache · GitHub
Skip to content

FastAPICache.Clear(namespace...) does not work with custom key_builder #571

Open

Description

@Nickopusan13

Hello,
I'm having an issue with FastAPICache.clear() when using a custom key_builder.

The caching itself works perfectly:

@cache(expire=300, key_builder=create_client_key_builder("clients:single"))
async def get_single_client(...):
    ...

The key appears correctly in Redis like this:

clients:single:user:3:client_id:3:no-params

But when I try to clear it, nothing happens:

await FastAPICache.clear(
    namespace=f"clients:single:user:{current_user.id}:client_id:{client_id}:no-params"
)

Even though the string I'm passing is exactly the same as the key in Redis.

Right now I'm doing this and it works:

await redis_client.delete(
    f"clients:single:user:{current_user.id}:client_id:{client_id}:no-params"
)

Key Builder

def create_client_key_builder(namespace: str):
    def builder(func, *args, **kwargs):
        request = kwargs.get("request")
        current_user = getattr(request.state, "user", None)
        user_id = getattr(current_user, "id", "anonymous")
        client_id = kwargs.get("client_id") or request.path_params.get("client_id")
        query_params = request.url.query or "no-params"
        return f"{namespace}:user:{user_id}:client_id:{client_id}:{query_params}"
    return builder

Activity

  1. hosamk92 commented on Jul 28, 2026

    @hosamk92

    Hello @Nickopusan13

    I don't think this is a bug, clear(namespace=...) works a bit differently than it might seem. It doesn't match your literal key string, it clears based on a prefix + namespace pattern, which is meant for clearing groups of keys that share a generated prefix, like when you're using the default key builder.

    Since your custom key_builder returns the exact literal key, the simpler fix is to clear it directly by key instead:

    await FastAPICache.clear(
        key=f"clients:single:user:{current_user.id}:client_id:{client_id}:no-params"
    )

    That should give you the same result as your redis_client.delete(...) workaround.

    If you would like to use it with namespace you could use the following:

    await FastAPICache.clear(namespace="clients:single:") // clear all keys stored by the custom builder as it uses this namespace
    
    // or use this 
    await FastAPICache.clear(namespace="clients:single:user:3:") // to clear all keys for specific user

    When using namespace in clear it woul clear all keys that starts by the namespace.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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