Skip to main content
This example demonstrates how to create and add custom middleware to your AgentOS application. We implement two common middleware types: rate limiting and request/response logging.

Code

custom_middleware.py

Usage

1

Set up your virtual environment

2

Set Environment Variables

3

Install dependencies

4

Setup PostgreSQL Database

5

Run Example

6

Test the Middleware

Basic Request (observe console logging):
Test Rate Limiting (trigger 429 errors after 10 requests):
Check Rate Limit Headers:

Middleware Features

Prevents API abuse by limiting requests per IP:
  • Configurable Limits: Set requests per minute and time window
  • Per-IP Tracking: Different limits for different IP addresses
  • Sliding Window: Uses a sliding time window for accurate limiting
  • Rate Limit Headers: Provides client information about limits
Headers Added:
  • X-RateLimit-Limit: Maximum requests allowed
  • X-RateLimit-Remaining: Requests remaining in current window
  • X-RateLimit-Reset: Timestamp when the window resets
Customization:

Developer Resources