Dynamic Router Loading

RouteMQ automatically discovers and loads route files from your application directory, enabling modular route organization and hot-swappable routing configurations.

Overview

The RouterRegistry class provides automatic route discovery and loading capabilities:

  • Auto-discovery: Scans app/routers/ directory for route files

  • Dynamic import: Loads route modules at runtime

  • Route merging: Combines routes from multiple files into a single router

  • Error handling: Graceful handling of missing or broken route files

  • Worker synchronization: Ensures workers load the same route configuration

How Dynamic Loading Works

Discovery Process

from core.router_registry import RouterRegistry

# Create registry with default directory
registry = RouterRegistry("app.routers")

# Discover and load all routes
main_router = registry.discover_and_load_routers()

The discovery process follows these steps:

  1. Package Import: Imports the router package (app.routers)

  2. Module Scanning: Uses pkgutil.iter_modules() to find all Python files

  3. Module Loading: Dynamically imports each discovered module

  4. Router Extraction: Looks for a router variable in each module

  5. Route Merging: Combines all routes into a single master router

File Structure Requirements

Router Module Format

Each router file must export a router variable:

Configuration Options

Custom Router Directory

Environment-Based Loading

Route File Organization

Modular Organization

Organize routes by functional domain:

Feature-Based Organization

Advanced Features

Conditional Route Loading

Dynamic Route Generation

Plugin System Integration

Error Handling and Debugging

Logging and Diagnostics

The RouterRegistry provides comprehensive logging:

Log output example:

Common Issues and Solutions

Missing Router Variable

Import Errors

Circular Imports

Testing Dynamic Loading

Unit Testing

Integration Testing

Production Considerations

Performance Optimization

Hot Reloading (Development)

Deployment Strategies

Best Practices

File Organization

  • One domain per file: Group related routes in single files

  • Consistent naming: Use descriptive file names (user_management.py, not users.py)

  • Logical grouping: Use route groups for shared prefixes and middleware

Route Definition

  • Export router variable: Always name your router instance router

  • Import at module level: Import controllers and middleware at the top

  • Avoid side effects: Don't perform actions during module import

Error Handling

  • Graceful degradation: Handle missing dependencies gracefully

  • Comprehensive logging: Use appropriate log levels for debugging

  • Validation: Validate routes during development and deployment

Performance

  • Lazy loading: Only import what you need

  • Caching: Cache loaded routes in production

  • Monitoring: Monitor route loading performance

Next Steps

Last updated