Axum Realtime Kit
A toolkit for building scalable, real-time applications with Axum, WebSockets, and Redis Pub/Sub. This crate provides the architectural building blocks to handle connection management, state synchronization, and authentication, letting you focus on your application's business logic.
When to Use This Crate?
This crate is a great fit if you are building:
- Real-time Chat Applications: Scale your chat rooms across multiple server instances without worrying about which user is connected to which server.
- Live Data Dashboards: Push live metrics, logs, or financial data to thousands of connected clients simultaneously.
- Notifications Systems: Broadcast real-time notifications to users subscribed to specific topics (e.g., "user:123", "project:456").
- Collaborative Applications: Build tools like collaborative whiteboards or document editors where actions from one user must be reflected instantly for others.
- Multiplayer Game Lobbies: Manage players in lobbies and broadcast game state changes.
Core Concepts
The kit is designed around a few key abstractions:
WebsocketService: The central engine. It manages all active connections on a server instance, communicates with Redis, and drives the entire lifecycle. You create one instance of this and share it across your Axum state.MessageHandlerTrait: This is where your application's logic lives. You implement this trait to define your message and event types, handle incoming messages, and react to connections/disconnections.upgrade_handlerFunction: A generic Axum handler that orchestrates authentication and topic validation before upgrading an HTTP request to a WebSocket connection.
Getting Started
The core pattern for using this crate involves four main steps.
1. Dependencies
Add axum-realtime-kit to your Cargo.toml.
[]
= { = "0.1.0", = ["auth"] }
# ... other dependencies like tokio, serde, uuid ...
2. Define Your Models
Define the structs and enums that model your application's data flow, such as your User identity, the ClientMessages you expect, and the ServerEvents you will broadcast.
// Your authenticated user identity
// Messages clients send to the server
// Events the server broadcasts to clients
3. Implement the Core Traits
Plug your logic into the WebsocketService by implementing two traits on your application's state and a handler struct.
TokenValidator: Implement this on your shared Axum state to define how a string token from a request is validated and turned into yourUserstruct.MessageHandler: Implement this on a dedicated handler struct. This is where you'll write the logic for what happens when a client sends a message.
// In your state implementation
// In your handler implementation
4. Wire It Up in Axum
In your main function, create the WebsocketService, wrap it in your Axum state, and create a route that uses the upgrade_handler to bring it all together.
📝 For a complete, runnable implementation of these steps, please see the
basic_chatexample in the/examplesdirectory.
Running the Example
You can run the included basic_chat example to see the kit in action.
-
Clone the repository:
-
Set up Redis: Make sure you have a Redis server running. Create a
.envfile in the project root and add your Redis connection URL:# .env REDIS_URL="redis://127.0.0.1/" -
Run the server:
The server will start listening on
127.0.0.1:3000. -
Connect with WebSocket clients: Open two separate terminals and use a tool like
websocat.-
Terminal 1 (Alice): Connect to the
generalroom. -
Terminal 2 (Bob): Connect to the same room and send a message.
# Connect # Type this and press Enter to send a message >
-
You will see Bob's message broadcast and appear in Alice's terminal.
Feature Flags
auth(default): Enables theWsAuthextractor andTokenValidatortrait for authenticating WebSocket upgrade requests.coalescing: Enables theCoalescingService, a utility for preventing duplicate concurrent executions of an expensive asynchronous operation.
License
This project is licensed under either of
- Apache License, Version 2.0, (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
- MIT license (LICENSE-MIT or http://opensource.org/licenses/MIT)
at your option.