Skip to content

Rate limiting with fastapi-users

Compose paceapi key dependencies directly with fastapi-users current_user() dependencies:

# These two lines are fastapi-users' own.
current_active_user = fastapi_users.current_user(active=True)
current_user_if_any = fastapi_users.current_user(active=True, optional=True)


async def user_key(user: Annotated[User, Depends(current_active_user)]) -> str:
    # The id is a UUID with one database and something else with another.
    return f"user:{user.id}"


async def user_key_if_any(
    user: Annotated[User | None, Depends(current_user_if_any)],
) -> str | None:
    return None if user is None else f"user:{user.id}"
per_user = limiter.limit("3/minute", key=user_key)
# Someone who is signed in is counted as that user, and anyone else by address.
per_caller = limiter.limit("3/minute", key=first_of(user_key_if_any, client_ip))

@app.get("/me", dependencies=[Depends(per_user)])
async def me(user: Annotated[User, Depends(current_active_user)]) -> dict[str, str]:
    return {"email": user.email}

@app.get("/articles", dependencies=[Depends(per_caller)])
async def articles() -> list[str]:
    return ["On counting", "On waiting"]

Key details

  • Single auth check per request: FastAPI deduplicates current_user across the key dependency and endpoint; unauthenticated callers get fastapi-users's 401 before any quota is consumed.
  • Stringify user IDs: Format f"user:{user.id}" so UUID, integer, and string primary keys all work uniformly.
  • Mixed anonymous/authenticated routes: Use current_user(active=True, optional=True) with first_of to fall back to client_ip for unauthenticated callers.
  • Auth routers (/auth/register, /auth/login): Attach IP-based limits when calling app.include_router(..., dependencies=[Depends(...)]). Note that in fastapi-users 15, login accepts form data (not JSON), returns 400 on invalid credentials (use failures={400}), and shares a router with logout (handle requests without a username field gracefully).
  • Self-contained example: examples/fastapi_users.py uses a lightweight stub matching fastapi-users's current_user(active=..., optional=...) signature so it runs in CI without installing fastapi-users.