Skip to content

Login throttling

Protect a login endpoint against brute-force and credential-stuffing attacks without penalizing legitimate sign-ins by layering three limits:

  1. Overall attempt cap per IP: bounds concurrent bursts (since failure limits are only charged after execution).
  2. Failed attempts per (account, IP): locks out password guessing against a specific account from one IP without locking out the legitimate user elsewhere.
  3. Failed attempts per IP: catches password spraying (trying one password across many accounts).
class Credentials(BaseModel):
    username: str = Field(max_length=255)  # longer than any real name is not a name
    password: str


def folded(username: str) -> str:
    # One rule for which spellings are one account, used to count and to look up.
    return username.strip().casefold()


async def account(credentials: Credentials) -> str:
    return "account:" + folded(credentials.username)
# Every attempt from an address counts against this one, whatever comes of it.
attempts = limiter.limit("20/minute")
# Five wrong passwords for one account from one address in fifteen
# minutes, and that address has to wait before it tries that account
# again. A login that works counts for nothing.
wrong_for_an_account = limiter.limit(
    "5/15 minutes", count="failures", failures={401}, key=combine(account, client_ip)
)
# Thirty wrong passwords from one address in an hour, whichever accounts
# they were for, and that address has to wait.
wrong_from_an_address = limiter.limit("30/hour", count="failures", failures={401})

@app.post(
    "/login",
    dependencies=[
        Depends(attempts),
        Depends(wrong_for_an_account),
        Depends(wrong_from_an_address),
    ],
)
async def login(credentials: Credentials) -> dict[str, str]:
    name = folded(credentials.username)
    if PASSWORDS.get(name) != credentials.password:
        raise HTTPException(status_code=401, detail="Wrong username or password.")
    return {"signed in as": name}

Production considerations

  • Key trade-offs:
    • (account, IP) prevents attackers from locking out legitimate users remotely while limiting per-IP guessing to 5 tries per account.
    • IP-only failure limits catch spraying, though shared office NATs share the 30/hour ceiling—tune for your traffic profile.
    • Account-only failure limits (omitted here) stop distributed guessing but enable denial-of-service lockouts against known usernames.
  • Normalize usernames identically in key and lookup: Use the same normalization helper for both, otherwise Unicode/case variants yield fresh allowances. If your DB lookup uses looser matching, perform the lookup in the key dependency and key on the canonical user ID.
  • Match body parameter names: FastAPI parses the JSON body once and shares it between account_at_ip and the endpoint only when both parameters share the exact name (credentials). Different names cause FastAPI to expect two bodies and return 422.
  • Store visibility: Usernames appear in bucket keys inside your store for the duration of the window.
  • Restrict failures={401}: Avoid counting 422 validation errors or 500 server errors against users. Place the limits before any dependency that raises 401 (see FastAPI dependency visibility).
  • Proxies and multi-worker deployments: Configure ClientIP(trusted_proxies=...) behind load balancers (Keys) and RedisStore across multiple workers (Stores).

Full source: examples/login_attempts.py.

Apps with custom exceptions

count="failures" observes the exception the endpoint raises, before any exception handler maps it to a status. A login that raises an app-defined exception (answered 401 by a handler) is seen as 500, so failures={401} never counts it. Charge a meter where the failure is known instead, and keep the overall per-IP attempt cap: a meter charges after the check, so concurrent guesses all pass its entry check.

# Caps every attempt per IP. A meter charges after the check, so concurrent guesses
# all pass its entry check; this bounds how many can do that at once.
attempts = limiter.limit("20/minute")
# A meter admits callers with remaining budget and charges only what the endpoint reports.
guesses = limiter.meter("5/15 minutes", key=combine(account, client_ip))

@app.post("/login", dependencies=[Depends(attempts)])
async def login(
    credentials: Credentials, meter: Annotated[Meter, Depends(guesses)]
) -> dict[str, str]:
    name = credentials.username.strip().casefold()
    if not await right_password(name, credentials.password):
        # Charge here, where the failure is known. `count="failures"` would see
        # `WrongPasswordError` as a 500, before the handler maps it to 401.
        await meter.charge(1)
        raise WrongPasswordError
    return {"signed in as": name}

Full source: examples/login_own_errors.py.