@@ -110,6 +110,59 @@ async def protected_endpoint():
110110# 3. Checks Redis counter
111111# 4. Allows or blocks the request
112112```
113+ #### Example Dependency Implementation
114+
115+ To make the rate limiting dependency functional, you must implement how user tiers and paths resolve to actual rate limits.
116+ Below is a complete example using Redis and the database to determine per-tier and per-path restrictions.
117+
118+ ``` python
119+ async def rate_limiter_dependency (
120+ request : Request,
121+ db : AsyncSession = Depends(async_get_db),
122+ user = Depends(get_current_user_optional),
123+ ):
124+ """
125+ Enforces rate limits per user tier and API path.
126+
127+ - Identifies user (or defaults to IP-based anonymous rate limit)
128+ - Finds tier-specific limit for the request path
129+ - Checks Redis counter to determine if request should be allowed
130+ """
131+ path = sanitize_path(request.url.path)
132+ user_id = getattr (user, " id" , None ) or request.client.host or " anonymous"
133+
134+ # Determine user tier (default to "free" or anonymous)
135+ if user and getattr (user, " tier_id" , None ):
136+ tier = await crud_tiers.get(db = db, id = user.tier_id)
137+ else :
138+ tier = await crud_tiers.get(db = db, name = " free" )
139+
140+ if not tier:
141+ raise RateLimitException(" Tier configuration not found" )
142+
143+ # Find specific rate limit rule for this path + tier
144+ rate_limit_rule = await crud_rate_limits.get_by_path_and_tier(
145+ db = db, path = path, tier_id = tier.id
146+ )
147+
148+ # Use default limits if no specific rule is found
149+ limit = getattr (rate_limit_rule, " limit" , 100 )
150+ period = getattr (rate_limit_rule, " period" , 3600 )
151+
152+ # Check rate limit in Redis
153+ is_limited = await rate_limiter.is_rate_limited(
154+ db = db,
155+ user_id = user_id,
156+ path = path,
157+ limit = limit,
158+ period = period,
159+ )
160+
161+ if is_limited:
162+ raise RateLimitException(
163+ f " Rate limit exceeded for path ' { path} '. Try again later. "
164+ )
165+ ```
113166
114167### Redis-Based Counting
115168
0 commit comments