Message Routing

Message Routing

Message routing is a core concept in the Matrix Framework that determines how messages flow through your application. The framework uses a tree-based routing system that allows for flexible and powerful message handling.

Tree-Based Routing

The routing system is built on a tree structure where:

  • Each node in the tree represents a potential message destination
  • Messages flow down the tree based on routing rules
  • Multiple paths can be active simultaneously

Key Components

  1. Route Nodes

    • Represent destinations in your message flow
    • Can contain middleware handlers
    • Support both synchronous and asynchronous processing
  2. Routing Rules

    • Define how messages are directed through the tree
    • Can be based on message content, type, or custom logic
    • Support pattern matching and wildcards
  3. Message Context

    • Carries the message and metadata through the routing tree
    • Maintains state during message processing
    • Accessible to all middleware in the route

Example

Here’s a basic example of how routing works:

// Create a router
const router = new Router();

// Define routes
router.route("app/users/*")
      .use(authMiddleware)
      .use(async (ctx, next) => {
        // Handle user-related messages
        await next();
      });

router.route("app/admin/*")
      .use(adminAuthMiddleware)
      .use(async (ctx, next) => {
        // Handle admin-related messages
        await next();
      });

Best Practices

  1. Route Organization

    • Group related routes together
    • Use consistent naming patterns
    • Keep route handlers focused and single-purpose
  2. Error Handling

    • Implement error middleware at appropriate levels
    • Use try-catch blocks in async handlers
    • Provide meaningful error messages
  3. Performance

    • Minimize route nesting depth
    • Use route caching when appropriate
    • Consider message payload size

Next Steps

Learn more about specific routing features in the Tree-based Routing section.