Tito
⚠️ WARNING: This project is in early development and NOT PRODUCTION READY. Use at your own risk. The API may change without notice, and there may be bugs and performance issues. Not recommended for critical applications.
Tito is a powerful, flexible database layer built on top of TiKV, providing robust indexing strategies, relationship modeling, and transaction management capabilities for Rust applications.
Features
- Powerful Indexing Strategies: Define custom indexes with conditional logic for efficient querying
- Relationship Modeling: Create and manage embedded relationships between data models
- Transaction Management: Full ACID-compliant transaction support
- Event-Driven Queue: Built-in persistent event queue with FIFO ordering and partition-based parallelism
- Async Workers: Tokio-powered workers for concurrent event processing with per-event-type isolation
- Type Safety: Leverages Rust's type system for safety and performance
- Flexible Query API: Query data using intuitive builder pattern
Installation
Add Tito to your project:
[]
= "0.1.43"
Quick Start
Setting up a Connection
// Connect to TiKV with multiple endpoints
let tito_db = connect.await?;
// For production, use multiple PD endpoints for high availability
let tito_db = connect.await?;
Creating a Model
// Create model with the storage backend
let user_model = tito_db.clone.;
Basic CRUD Operations
// Create a user
let user_id = new_v4.to_string;
let user = User ;
// Create user with transaction
let saved_user = tito_db.transaction.await?;
// Find user by ID
let found_user = user_model.find_by_id.await?;
// Update user
let updated_user = User ;
tito_db.transaction.await?;
// Delete user
tito_db.transaction.await?;
Using the Query Builder
Tito provides a powerful query builder pattern for easier and more readable querying.
Basic Query
// Find user by email
let mut query = user_model.query_by_index;
let result = query
.value
.execute
.await?;
// Check if we found a user
if let Some = result.items.first
Query with Relationships
// Post model with tag relationships
let mut query = post_model.query_by_index;
let posts = query
.value // Author name
.relationship // Include tags relationship
.limit // Limit to 10 results
.execute
.await?;
for post in posts.items
Advanced Queries
// Find active users by role
let mut query = user_model.query_by_index;
let active_admins = query
.value // First index field (role)
.value // Second index field (status)
.limit // Limit results
.execute
.await?;
// Use cursor for pagination
if let Some = active_admins.cursor
Reverse Order Query
// Get latest posts in reverse chronological order
let mut query = post_model.query_by_index;
let latest_posts = query
.value // Index by year
.execute_reverse // Execute in reverse order
.await?;
Transaction-Specific Queries
tito_db.transaction.await?;
Advanced Features
Conditional Indexing
Tito lets you conditionally index data based on business rules:
TitoIndexConfig
Relationship Modeling
Define relationships between models and fetch related data efficiently:
// Post model with references to multiple tags
// Fetch a post with related tags using query builder
let mut query = post_model.query_by_index;
let post = query
.value
.relationship
.execute
.await?;
Composite Indexes
Create and query using composite indexes:
// Define composite index
TitoIndexConfig
// Query using composite index
let mut query = article_model.query_by_index;
let articles = query
.value // category value
.value // published_at value as number
.limit
.execute
.await?;
Event Queue System
Tito includes a built-in event-driven queue system for asynchronous processing with FIFO ordering and partition-based parallelism.
Defining Events
Define events in your model by implementing the events() method:
Creating Events
Events are automatically created when you perform operations with event options:
use ;
// Create a user and generate an INSERT event
tito_db.transaction.await?;
// Update a user and generate an UPDATE event
tito_db.transaction.await?;
Setting Up Workers
Create workers to process events by event type:
use ;
use PartitionConfig;
use Arc;
use AtomicBool;
use broadcast;
// Create queue
let queue = new;
// Worker configuration
let is_leader = new;
let partition_config = PartitionConfig ;
// Create shutdown channel
let = channel;
// Define event handler
let handler = move |event: TitoEvent| ;
// Start worker for "user" events
let worker_handle = run_worker
.await;
// Gracefully shutdown when done
let _ = shutdown_tx.send;
let _ = worker_handle.await;
Key Concepts
- Event Types: Each model can define multiple event types. Workers process one event type at a time, enabling independent scaling and failure isolation.
- FIFO Ordering: Events are processed oldest-first within each partition, ensuring correct ordering.
- Partitions: The system uses 1024 fixed partitions for parallel processing. Partitioning is determined by the model's
partition_key()method. - Checkpoints: Each event type maintains independent checkpoints per partition, tracking processing progress.
- Leader Election: Use the
is_leaderflag to ensure only one worker processes events in distributed setups. - Graceful Shutdown: Workers respect shutdown signals for clean termination.
Multiple Workers
You can run multiple workers for different event types:
// Worker for user events
let user_worker = run_worker.await;
// Worker for order events
let order_worker = run_worker.await;
Each event type acts as an independent queue (similar to Kafka topics), allowing you to:
- Scale workers independently based on load
- Isolate failures to specific event types
- Configure different concurrency levels per event type
Running the Examples
Tito comes with comprehensive examples demonstrating all major features. To run them, you'll need a TiKV server running locally.
Setting up TiKV
The quickest way to get started is using Docker:
# Start a local TiKV cluster
Or use TiUP for a production-like setup:
|
Example 1: Basic CRUD (crud.rs)
Demonstrates fundamental database operations:
What it does:
- Connects to TiKV
- Creates a user with email indexing
- Finds the user by ID
- Updates user information
- Deletes the user
Expected output:
Created user: User { id: "...", name: "John Doe", email: "john@example.com" }
Found user: User { id: "...", name: "John Doe", email: "john@example.com" }
User updated successfully
User deleted successfully
Example 2: Relationships and Queries (blog.rs)
Shows how to work with related data using the powerful relationship system:
What it does:
- Creates tags (Technology, Travel, Rust, Databases)
- Creates blog posts with multiple tags
- Demonstrates relationship hydration
- Queries posts by tag
- Queries posts by author
Expected output:
Created tags:
- Technology: <uuid>
- Travel: <uuid>
...
Created posts:
1. Introduction to TiKV (by Alice)
2. Best cities to visit in Europe (by Bob)
3. Using Rust with TiKV (by Alice)
Post with tags:
Title: Introduction to TiKV
Tags:
- Technology
- Databases
Technology posts:
- Using Rust with TiKV (by Alice)
Tags: Technology, Rust, Databases
...
Key concepts demonstrated:
- One-to-many relationships (Post → Tags)
- Relationship hydration with
.relationship("tags") - Composite indexes for efficient querying
- Query builder pattern
Example 3: Event Queue System (queue_fifo.rs)
Demonstrates the event-driven queue with FIFO processing:
What it does:
- Creates 5 users with events enabled
- Starts a worker to process events
- Shows FIFO ordering (oldest events first)
- Demonstrates partition-based parallelism
- Graceful shutdown
Expected output:
🚀 Testing FIFO Queue with Checkpoints
📝 Creating 5 users to generate events...
✓ Created: User 1 (user1@example.com)
✓ Created: User 2 (user2@example.com)
...
📊 Setting up queue worker...
⚙️ Worker started! Processing events in FIFO order...
[1] Processing event: INSERT - table:user:xxx (sequence: 00001...)
[2] Processing event: INSERT - table:user:xxx (sequence: 00001...)
...
✅ Complete! Processed 5 events in FIFO order
(Oldest events processed first!)
Key concepts demonstrated:
- Event generation with
TitoOptions::with_events() - Event worker setup with
run_worker() - Event type isolation ("user" events)
- FIFO ordering within partitions
- Checkpoint-based progress tracking
- Graceful shutdown handling
How the Queue System Works
The event queue is perfect for:
- Async processing: Offload heavy work from request handlers
- Event sourcing: Track all changes to your data
- Multi-tenant processing: Partition by tenant ID for isolation
- Saga patterns: Coordinate distributed transactions
Architecture:
Model Change (INSERT/UPDATE/DELETE)
↓
Event Generated (if events() enabled)
↓
Stored in TiKV: event:{event_type}:{partition}:{sequence}
↓
Worker polls: queue:{event_type}:PENDING:{partition}:{sequence}
↓
Process Event (your handler logic)
↓
Mark Complete: queue:{event_type}:COMPLETED:{partition}:{sequence}
↓
Update Checkpoint: queue_checkpoint:{event_type}:{partition}
Practical Example - Email Notifications:
// 1. Define event in your User model
// 2. Create user with event
tito_db.transaction.await?;
// 3. Worker processes event asynchronously
let handler = move |event: TitoEvent| ;
let worker = run_worker.await;
Scaling Pattern:
// Server 1: Partitions 0-511
let partition_config = PartitionConfig ;
// Server 2: Partitions 512-1023
let partition_config = PartitionConfig ;
// Both process same event type, different partitions
// = Horizontal scalability + load balancing
Requirements
- Rust 2021 edition or later
- TiKV server running (local or remote)
License
This project is licensed under the Apache License, Version 2.0.