Skip to content

Cache Module

forge.cache — Decorator-based caching with in-memory LRU and Redis backends.

Overview

The Cache module provides a simple, decorator-based caching API with pluggable backends. Cache function results with a single decorator, and switch between in-memory and Redis backends by changing configuration.

Installation

pip install forge-kaif
# For Redis backend:
pip install forge-kaif[redis]

Quick Start

from forge.cache import cached

@cached(ttl=300)  # Cache for 5 minutes
async def get_user(user_id: int):
    return await db.fetch_user(user_id)

Key Features

Configurable TTL

@cached(ttl=60)       # 60 seconds
@cached(ttl=3600)     # 1 hour
@cached(ttl=86400)    # 24 hours

Custom Cache Keys

@cached(key="user:{user_id}")
async def get_user(user_id: int):
    ...

Backend Selection

@cached(backend="memory")   # In-memory LRU (default)
@cached(backend="redis")    # Redis-backed

Invalidation

from forge.cache import invalidate

await invalidate("user:42")  # Remove a specific entry

Manual Cache Operations

from forge.cache import CacheModule

cache = CacheModule()
await cache.set("key", value, ttl=300)
value = await cache.get("key")
exists = await cache.has("key")
await cache.delete("key")
await cache.clear()

API Reference

Classes

CacheBackendError

Raised when a cache backend operation fails or is unavailable.

CacheError

Base exception for all cache-related errors.

CacheModule

Manages caching services and pluggable storage backends for the forge runtime.

Attributes

backend property
backend: CacheBackend

Get the active cache backend.

Methods:

clear async
clear() -> None

Clear all cache values.

delete async
delete(key: str) -> bool

Delete a key from cache.

get async
get(key: str) -> Any | None

Get a value from cache and emit hit/miss event.

has async
has(key: str) -> bool

Check if a key exists in cache.

health_check
health_check() -> HealthResult

Check the health status of the caching backend.

set async
set(key: str, value: Any, ttl: int | None = None) -> None

Set a cache value and emit set event.

setup async
setup(runtime: ForgeRuntime) -> None

Initialize cache module and configure settings.

teardown async
teardown() -> None

Teardown the cache module.

Functions:

cached

cached(ttl: int | None = None, key: str | None = None, namespace: str | None = None, backend: CacheBackend | None = None) -> Callable[[F], F]

Decorator for caching async function results.

Parameters:

Name Type Description Default
ttl int | None

Time-to-live in seconds. Defaults to cache module default_ttl.

None
key str | None

Cache key template. Supports {arg_name} interpolation from function args.

None
namespace str | None

Optional namespace prefix for the cache key.

None
backend CacheBackend | None

Optional custom backend to use instead of the active module.

None

invalidate async

invalidate(key: str) -> bool

Convenience helper to invalidate a cache key in the active cache module.