Background Work, Caching & Rate Limiting¶
Work that runs after the response, the cache interface, rate-limit strategies, and runtime instrumentation.
BackgroundTasks
¶
Cache
¶
Result-cache backend interface.
A backend stores opaque bytes under a string key with a per-entry TTL in
seconds. The methods are async so a network-backed store does not block the
event loop. cached serialises and deserialises the values, so a backend
only moves bytes.
InMemoryCache
¶
Bases: Cache
A process-local, size-bounded result cache with per-entry TTL.
Fine for a single process and tests. It does not share state across workers,
so a multi-worker deployment needs a shared backend such as
veloce.contrib.redis.RedisCache. TTLs use a monotonic clock, so a wall-clock
change cannot prematurely expire or extend an entry.
Usage::
from veloce import InMemoryCache
cache = InMemoryCache(max_entries=2048)
cached
¶
cached(cache: Cache, *, ttl: int, key: Callable[..., str] | None = None) -> Callable[[Callable[..., Any]], Callable[..., Any]]
Memoise an async function's JSON-serialisable return in cache.
The key defaults to the function's qualified name plus a digest of its
arguments (arguments that are not JSON-serialisable, such as an injected
Request, are ignored), so a handler is cached by its scalar inputs. Pass
key= a callable taking the same arguments for full control.
The result must be JSON-serialisable (a Pydantic model is dumped in JSON
mode); a non-serialisable result raises TypeError. A cache hit returns
the JSON-decoded value, so cache results you will re-serialise (handler
returns, API payloads) rather than rich objects you need back by type. Only
async functions are supported.
rate_limit
¶
rate_limit(strategy: RateLimitStrategy) -> Callable[[T_handler], T_handler]
Attach a per-route rate-limit strategy to a handler.
A decorated handler is limited by strategy with its own per-client counter,
overriding the RateLimitMiddleware default. Place it below the route
decorator so the route registers the tagged handler.
Usage::
from veloce import TokenBucket, rate_limit
@app.post("/login")
@rate_limit(TokenBucket(rate=5, per=60))
async def login(request): ...
RateLimitBackend
¶
Where per-client rate-limit state lives, and the atomic read-modify-write.
evaluate loads the state for key, runs strategy.evaluate, persists the
next state with its TTL, and returns the decision - all atomically, so two
concurrent requests for the same client cannot both read a stale count.
Subclasses must declare __slots__ (even __slots__ = ()).
evaluate
async
¶
evaluate(key: str, strategy: RateLimitStrategy, now: float) -> RateLimitResult
Load, run strategy.evaluate and persist for key, atomically.
InMemoryRateLimitBackend
¶
Bases: RateLimitBackend
Process-local rate-limit state - the default backend.
Not shared across workers, so a multi-worker deployment enforces roughly
N x the limit; use veloce.contrib.redis.RedisRateLimitBackend for one
shared limit. State is size-bounded to cap memory across many client keys.
evaluate
async
¶
evaluate(key: str, strategy: RateLimitStrategy, now: float) -> RateLimitResult
Load, run strategy.evaluate and persist for key in this process.
RateLimitResult
dataclass
¶
The outcome of evaluating one request against a strategy.
RateLimitStrategy
¶
A rate-limit algorithm as a pure state transition.
evaluate takes the client's prior state (None on the first request or
after expiry) and the current wall-clock time, and returns the decision, the
next state to persist, and a TTL in seconds. It performs no I/O, so a backend
can run it under its own atomicity.
Subclasses must declare __slots__ (even __slots__ = ()).
evaluate
¶
evaluate(state: RateLimitState | None, now: float) -> tuple[RateLimitResult, RateLimitState, int]
Decide on this request, returning (result, next state, TTL seconds).
FixedWindow
¶
Bases: RateLimitStrategy
Allow limit requests per fixed window seconds.
Simple and cheap, but a burst straddling a window boundary can admit up to
2 x limit briefly - use SlidingWindow or TokenBucket when that
matters.
evaluate
¶
evaluate(state: RateLimitState | None, now: float) -> tuple[RateLimitResult, RateLimitState, int]
Count this request against the fixed window now falls in.
SlidingWindow
¶
Bases: RateLimitStrategy
Allow limit requests per rolling window seconds.
Weights the previous window's count by how far the current window has
progressed, so the boundary burst FixedWindow allows is smoothed away while
keeping only two counters of state.
evaluate
¶
evaluate(state: RateLimitState | None, now: float) -> tuple[RateLimitResult, RateLimitState, int]
Weight the previous window's count by how much of it still overlaps.
TokenBucket
¶
Bases: RateLimitStrategy
Refill rate tokens per per seconds, allowing bursts up to burst.
Each request spends one token; an empty bucket rejects until it refills. The
bucket tolerates a short burst (up to burst, default rate) while holding
the long-run average to rate/per. A leaky-bucket-style strict limiter is
TokenBucket(rate, per, burst=1).
evaluate
¶
evaluate(state: RateLimitState | None, now: float) -> tuple[RateLimitResult, RateLimitState, int]
Refill the bucket for the elapsed time, then spend one token.
EventLoopWatchdog
¶
Detects event-loop stalls and reports the blocked stack.
A heartbeat callback re-arms itself on the loop every interval seconds
while a daemon thread measures the gap since the last beat; a gap over
stall_threshold is logged with the loop thread's stack and a hint. Each
distinct stall is reported once, since the beat counter is frozen for its
whole duration.
RequestMetrics
dataclass
¶
A finished HTTP request, as seen by an instrumentation hook.
route is the matched path template (/items/{id}), safe as a metric
label; it is None for both a 404 and a 405, so group by
(route, status_code) to keep those apart. path is high-cardinality.
streamed marks a response whose body is a streaming iterator: the hook
fires before the body is emitted, so duration_ms and status_code
exclude draining the stream and any mid-stream failure.
end_time_ns is the time.time_ns() instant dispatch returned, captured
before any hook runs, so a slow earlier hook cannot shift a span past the
real request boundary.
error_type is type(exc).__qualname__ for an unhandled exception that
became a 5xx, and None for every other outcome - including a 5xx
returned deliberately without a raised exception. The class name only is
carried, never the message, which may hold sensitive text.
instrument_access_log
¶
instrument_access_log(app: Veloce, *, logger: Logger | None = None, json: bool = False, include_streamed: bool = True) -> Callable[[RequestMetrics], None]
Register the unified access-log hook (text or JSON), route-keyed.
log_requests_as_json
¶
log_requests_as_json(app: Veloce, *, logger: Logger | None = None, level: int = INFO, include_path: bool = False) -> Callable[[RequestMetrics], None]
Register a hook emitting one JSON access-log record per request.