aiogram 3 middleware tutorial — DI, logging, auth, throttling
Four middleware patterns every production aiogram 3 bot ends up with. Working code, the gotchas that bite in week 3, and why middleware beats decorators for bot-wide concerns.
In aiogram 3, middleware is where "I need this on every handler" lives — dependency injection, request logging, auth gates, rate limits, error reporting. The docs show one toy example and move on. This covers the four patterns I use on every production bot, with code you can lift.
What middleware actually is in aiogram 3
A middleware is a class that subclasses BaseMiddleware and implements an async __call__. aiogram wraps every handler with every registered middleware, in registration order. Your middleware can inspect the event, mutate the data dict handlers see, short-circuit the call, or wrap it in try/except.
from aiogram import BaseMiddleware
from aiogram.types import TelegramObject
from typing import Any, Awaitable, Callable
class MyMiddleware(BaseMiddleware):
async def __call__(
self,
handler: Callable[[TelegramObject, dict], Awaitable[Any]],
event: TelegramObject,
data: dict,
) -> Any:
# pre — before handler runs
try:
return await handler(event, data)
finally:
# post — after handler finished or raised
pass
Register per event type on the dispatcher:
dp.message.middleware(MyMiddleware())
dp.callback_query.middleware(MyMiddleware())
Pattern 1 — Dependency injection (the one you'll use every day)
Instead of importing shared services into every handler file, inject them via middleware. Handlers declare what they want as named kwargs — aiogram pulls them from the data dict.
class DepsMiddleware(BaseMiddleware):
"""Inject shared services into every handler."""
def __init__(self, **deps: Any):
super().__init__()
self._deps = deps
async def __call__(self, handler, event, data):
data.update(self._deps)
return await handler(event, data)
Wire it up:
deps = DepsMiddleware(
catalog=catalog,
carts=carts,
orders=orders,
sheets=sheets,
admin_ids=settings.admin_ids,
shop_name=settings.shop_name,
)
dp.message.middleware(deps)
dp.callback_query.middleware(deps)
Then handlers just declare what they need:
@router.message(Command("cart"))
async def show_cart(
message: Message,
catalog: ProductCatalog,
carts: CartStore,
):
text, rendered = _render_cart(message.from_user.id, catalog, carts)
await message.answer(text, reply_markup=cart_kb(rendered))
No module globals, no get_db() singletons. Testing a handler = call it with mock services passed as kwargs. Clean.
Pattern 2 — Request logging with latency
Log every incoming update with user ID, event type, and handler latency. Plug it in first so it wraps everything downstream.
import logging, time
from aiogram.types import Message, CallbackQuery
logger = logging.getLogger(__name__)
class LoggingMiddleware(BaseMiddleware):
async def __call__(self, handler, event, data):
start = time.perf_counter()
user_id = None
label = type(event).__name__
if isinstance(event, Message):
user_id = event.from_user.id if event.from_user else None
text = event.text or ""
if text.startswith("/"):
label = f"msg:{text.split()[0]}"
elif text:
label = f"msg:len={len(text)}"
else:
label = "msg"
elif isinstance(event, CallbackQuery):
user_id = event.from_user.id if event.from_user else None
label = f"cb:{event.data!r}"
try:
return await handler(event, data)
finally:
elapsed_ms = (time.perf_counter() - start) * 1000
logger.info("[%s] user=%s %.1fms", label, user_id, elapsed_ms)
Register before DepsMiddleware so the timer wraps everything:
dp.message.middleware(LoggingMiddleware())
dp.message.middleware(DepsMiddleware(...))
Pattern 3 — Admin auth gate
Instead of writing if message.from_user.id not in admin_ids: return at the top of every admin handler, make auth a middleware scoped to a router that only has admin handlers.
class AdminOnlyMiddleware(BaseMiddleware):
def __init__(self, admin_ids: list[int]):
super().__init__()
self._admin_ids = set(admin_ids)
async def __call__(self, handler, event, data):
uid = None
if isinstance(event, (Message, CallbackQuery)):
uid = event.from_user.id if event.from_user else None
if uid not in self._admin_ids:
# silently drop non-admin events to the admin router
if isinstance(event, CallbackQuery):
await event.answer("Not authorized", show_alert=True)
return
return await handler(event, data)
# wire to a specific router, not the whole dispatcher
admin_router.message.middleware(AdminOnlyMiddleware(settings.admin_ids))
admin_router.callback_query.middleware(AdminOnlyMiddleware(settings.admin_ids))
Handlers inside admin_router can now assume the user is an admin. One less line per handler, one less place to forget the check.
Pattern 4 — Per-user throttle (prevent spam)
A user mashing a button 20 times in a second will crash your cart's edit_text flood protection. Throttle per user with a simple in-memory TTL dict.
import time
from collections import defaultdict
class ThrottleMiddleware(BaseMiddleware):
"""Drop events from a user that fire within <cooldown> of the last one."""
def __init__(self, cooldown: float = 0.5):
super().__init__()
self._cooldown = cooldown
self._last: dict[int, float] = defaultdict(float)
async def __call__(self, handler, event, data):
uid = getattr(getattr(event, "from_user", None), "id", None)
if uid is None:
return await handler(event, data)
now = time.monotonic()
if now - self._last[uid] < self._cooldown:
if isinstance(event, CallbackQuery):
await event.answer() # dismiss the spinner, no action
return
self._last[uid] = now
return await handler(event, data)
Good enough for 99% of bots. For a multi-instance deploy, swap the in-memory dict for Redis: same interface, await redis.set(f"throttle:{uid}", "1", ex=1) with a get check.
Order of registration matters
aiogram runs middlewares in registration order, outer-first. For most bots:
- Logging first — wraps everything, times every call including middlewares below.
- Throttle second — fast short-circuit before DI loading matters.
- DI last — only pays the cost of injecting deps for events that got through.
dp.message.middleware(LoggingMiddleware())
dp.message.middleware(ThrottleMiddleware(cooldown=0.3))
dp.message.middleware(DepsMiddleware(**services))
dp.callback_query.middleware(LoggingMiddleware())
dp.callback_query.middleware(ThrottleMiddleware(cooldown=0.3))
dp.callback_query.middleware(DepsMiddleware(**services))
Three gotchas
- Outer middleware vs inner middleware. aiogram 3 has both
.middleware()(inner, runs after update filtering) and.outer_middleware()(runs before, sees all updates even dropped). Use inner for most things — outer is only needed if you want to log/count rejected updates. - Middleware on router vs dispatcher. Router-scoped middleware only runs for handlers in that router. Dispatcher-scoped runs for all. The admin auth example above is router-scoped on purpose.
- Returning None short-circuits the handler. If your middleware's
__call__doesn'treturn await handler(event, data), the handler never fires. Useful for throttle/auth; a footgun if you forget.
A working reference
The three middleware patterns above (DI + logging + a stub for throttling) are implemented in the open-source lite template (middlewares.py in the full version). The full production template adds admin auth scoping and a Redis-backed throttle.
Related
- aiogram 3 FSM checkout example — where DI middleware pays off most (services passed to 4 state handlers).
- Admin notifications pattern — uses admin_ids injected by DepsMiddleware.
- aiogram 3 vs python-telegram-bot — middleware is one of aiogram 3's biggest ergonomic wins.
Want the full middleware + router + FSM stack?
Lite MIT on GitHub (single file, catalog + cart + checkout). Full version adds all four middleware patterns + Sheets + admin router. $9 (48h flash: $5 with LAUNCH5).