Middleware Chains

Learn how to combine multiple middleware components to create powerful processing pipelines for your RouteMQ applications.

Understanding Middleware Chains

Middleware in RouteMQ executes in a chain pattern where each middleware can:

  • Process the request before passing it to the next middleware

  • Modify the context that flows through the chain

  • Process the response after receiving it from subsequent middleware

  • Stop the chain by not calling the next handler

Chain Execution Flow

Request → Middleware 1 → Middleware 2 → Middleware 3 → Handler
           ↓              ↓              ↓           ↓
        Pre-process    Pre-process    Pre-process  Execute
           ↑              ↑              ↑           ↑
       Post-process   Post-process   Post-process  Return
Response ← Middleware 1 ← Middleware 2 ← Middleware 3 ← Handler

Basic Chain Example

from core.router import Router
from app.middleware.logging import LoggingMiddleware
from app.middleware.auth import AuthenticationMiddleware
from app.middleware.rate_limit import RateLimitMiddleware

router = Router()

# Middleware executes in order: Logging → Auth → RateLimit → Handler
router.on("api/{endpoint}",
          ApiController.handle_request,
          middleware=[
              LoggingMiddleware(),           # 1st: Log the request
              AuthenticationMiddleware(),    # 2nd: Authenticate user
              RateLimitMiddleware(),        # 3rd: Check rate limits
          ])

Execution Order:

  1. LoggingMiddleware logs incoming request

  2. AuthenticationMiddleware validates credentials

  3. RateLimitMiddleware checks request limits

  4. Handler executes business logic

  5. RateLimitMiddleware can log rate limit status

  6. AuthenticationMiddleware can log auth success

  7. LoggingMiddleware logs final response and timing

Chain Design Patterns

1. Security-First Chain

Place security middleware at the beginning to fail fast:

2. Performance-Optimized Chain

Order middleware by execution cost (fastest first):

3. IoT Device Chain

Specialized chain for IoT devices:

Context Flow Through Chains

Context Modification Example

Context Dependencies

Conditional Chain Execution

Skip Middleware Based on Conditions

Dynamic Chain Modification

Error Handling in Chains

Early Termination

Error Recovery

Chain Composition Patterns

Reusable Chain Components

Conditional Stack Assembly

Advanced Chain Patterns

Parallel Middleware Execution

Middleware with State Sharing

Testing Middleware Chains

Unit Testing Chains

Integration Testing

Performance Optimization

Middleware Ordering for Performance

Lazy Loading in Middleware

Middleware Caching

Best Practices

1. Design for Composability

2. Handle Dependencies Explicitly

3. Document Chain Requirements

4. Implement Graceful Degradation

Next Steps

Last updated