skip to content

In FastAPI, how do Depends(RateLimiter) and Depends(RateLimiter(limit=10)) differ when RateLimiter is a class with __init__ and __call__?

level: middleimportance: should knowfreq 45%

answer

  1. which signature FastAPI reads
  2. class is called per request
  3. instance built once, at import
  4. who controls the limit

basics

~10 s

Depends(RateLimiter) makes FastAPI call the class per request, so init's limit becomes a client-supplied query parameter. Depends(RateLimiter(limit=10)) passes a configured instance; FastAPI reads and calls call and never touches init.

solid answer

~40 s

A class is a callable, so `Depends(RateLimiter)` (or the shortcut `Annotated[RateLimiter, Depends()]`) makes FastAPI analyse `__init__` and call the class on every request. Here that turns `limit: int` into a required query parameter: a request without it gets a 422, and a client can send `?limit=100000` and choose its own limit. Passing an instance, `Depends(RateLimiter(limit=10))`, is the **parameterised dependency** pattern: you set `limit` once in code, and FastAPI inspects and calls the instance's `__call__`, whose parameters (a header, a sub-dependency) are the request inputs. The instance is created once and shared by every request and thread, so any state on it needs to be safe for concurrent use.

code

python · 34 lines
python
from typing import Annotated

from fastapi import Depends, FastAPI, Header
from fastapi.testclient import TestClient


class RateLimiter:
    def __init__(self, limit: int):
        self.limit = limit

    def __call__(self, x_client_id: Annotated[str | None, Header()] = None) -> int:
        return self.limit


app = FastAPI()


@app.get("/class-form")
def class_form(limiter: Annotated[RateLimiter, Depends()]):
    return {"limit": limiter.limit}


search_limit = RateLimiter(limit=10)


@app.get("/instance-form")
def instance_form(limit: Annotated[int, Depends(search_limit)]):
    return {"limit": limit}


client = TestClient(app)
print(client.get("/class-form").status_code)
print(client.get("/class-form?limit=100000").json())
print(client.get("/instance-form?limit=100000").json())

go deeper

for a junior

Recall that FastAPI calls whatever you pass to Depends: a class gets constructed, an instance gets its call invoked.

for a middle

Explain which signature FastAPI reads in each form, what is injected, and why the instance form is the way to parameterise a dependency.

for a senior

Catch a class dependency leaking configuration such as limits into client-controlled query parameters, and treat state on a shared instance as concurrent state.

for a principal

Set a team rule for when dependencies are classes of inputs versus configured instances, and where cross-process state like rate counters must live.

## Two callables that look alike `fastapi.Depends` accepts any callable. Both of these are callables, but they are different objects: - `RateLimiter`, the **class**. Calling it runs `__init__` and returns a new instance. - `RateLimiter(limit=10)`, an **instance** whose class defines `__call__`. Calling it runs `__call__`. FastAPI always does the same thing with a dependable: it reads the signature of *what will be called* and calls it per request. Which signature that is depends on what you passed. ## Passing the class ```python def handler(limiter: Annotated[RateLimiter, Depends()]): ... ``` `Depends()` with no argument is FastAPI's shortcut for "the dependable is the annotated class", the same as `Depends(RateLimiter)`. FastAPI now: 1. Reads `RateLimiter.__init__`'s parameters and treats them as request inputs. 2. Calls the class for each request (in the thread pool, as for any non-async callable), producing a new instance. 3. Injects that instance; `__call__` is never invoked by FastAPI. This is the right tool when the class *is* a bundle of request inputs, the classic `CommonQueryParams` with `q`, `skip` and `limit`. It is the wrong tool for configuration. With `def __init__(self, limit: int)`, `limit` becomes a **required query parameter**: a request without it gets a 422, and any client can send `?limit=100000` and set its own rate limit. The limit you meant to fix in code is now public and attacker-controlled, and it appears in `/docs` as an ordinary parameter. ## Passing an instance ```python search_limit = RateLimiter(limit=10) def handler(limit: Annotated[int, Depends(search_limit)]): ... ``` Now FastAPI: 1. Ignores `__init__` completely; you already ran it. 2. Reads `__call__`'s parameters, for example `x_client_id: Annotated[str | None, Header()] = None`, as request inputs. 3. Calls `search_limit(...)` per request and injects whatever `__call__` returns. The docs call this a **parameterised dependency**: one class, several configured instances (`RateLimiter(limit=10)` for search, `RateLimiter(limit=100)` for reads), each usable in `Depends`. FastAPI's own security utilities are built the same way: an instance configured in code whose `__call__` reads the request. | | `Depends(RateLimiter)` | `Depends(RateLimiter(limit=10))` | |---|---|---| | Signature FastAPI reads | `__init__` | `__call__` | | Object created | a new instance per request | one instance, at import time | | What is injected | the instance | `__call__`'s return value | | Who sets `limit` | the client, as a query parameter | your code | | Cache key within a request | the class | that instance | ## Consequences of sharing one instance Because the instance lives for the whole process: - Every request, and every thread-pool thread running a `def __call__`, sees the same attributes. A counter stored on `self` is shared state and needs a lock or an external store; with several worker processes each has its own copy, so per-process counters undercount a global limit. - `async def __call__` is awaited on the event loop; `def __call__` runs in the thread pool. Choose by what the body does. - Keep `__init__` arguments to configuration. Anything per request belongs in `__call__`'s signature so FastAPI validates it. ## Choosing - The class holds **request inputs** you want grouped and typed: pass the class, often with `Depends()`. - The class holds **configuration** and checks the request: create instances in code and pass them. - Review rule: any `Depends(SomeClass)` whose `__init__` takes security-relevant settings (limits, roles, allowed values) is exposing them to the client. ## Reviewing it from the defender's side When you review a pull request that adds a class-based dependency, check three things: 1. **What FastAPI will read.** Open `/docs` for the affected route. If a parameter you consider configuration (`limit`, `role`, `max_size`) is listed as a query parameter, the class was passed instead of an instance. 2. **What a client can send.** Try the route with that parameter set to an extreme value. With the class form the value is accepted as long as it validates as the declared type. 3. **What is shared.** For the instance form, look at every attribute `__call__` writes. Anything written per request is shared across requests and threads. The fix for the first two is always the same: construct the instance in code with the configuration, pass the instance to `Depends`, and keep only true request inputs in `__call__`'s signature.

  • In FastAPI, what does Annotated[CommonQueryParams, Depends()] mean, and when is the empty Depends() shortcut allowed?
    An empty `Depends()` tells FastAPI to use the annotated type itself as the dependable. It is meant for classes: FastAPI calls `CommonQueryParams`, reading its `__init__` parameters as request inputs, and injects the instance. It is the same as `Depends(CommonQueryParams)`, so both declarations share one cache entry within a request.
  • A FastAPI dependency instance keeps a request counter on self and its __call__ is a plain def. What can go wrong?
    The one instance is shared by all requests, and a `def __call__` runs in the thread pool, so several threads update the counter concurrently and increments can be lost. Under several worker processes each holds its own instance, so the count is per process. Use a lock for in-process state, or an external store when the limit must hold across processes.

  • Passes a configurable class to Depends and assumes __init__ arguments stay server-side.
  • Thinks FastAPI calls __init__ again on an instance passed to Depends.
  • Believes a callable instance is recreated for every request.
  • Says FastAPI calls __call__ on the instance it builds from a class dependency.
  • Stores per-request data on a shared dependency instance's attributes.