Keepalive
Maintain persistent gRPC connections to NextBlock for optimal performance using Rust's Tonic client.
Basic Keepalive Implementation
use std::time::Duration;
use tokio::time::{interval, sleep};
use tonic::Request;
// Send periodic ping to keep connection alive
async fn start_keepalive_task(
// mut nextblock_client: YourGeneratedApiClient,
ping_interval: Duration,
) -> Result<(), Box<dyn std::error::Error>> {
let mut interval_timer = interval(ping_interval);
println!("Starting keepalive task with interval: {:?}", ping_interval);
loop {
interval_timer.tick().await;
// Send ping request
/* Uncomment when you have the generated API client
match nextblock_client.ping(Request::new(())).await {
Ok(_) => {
println!("Keepalive ping successful at {}",
chrono::Utc::now().format("%H:%M:%S"));
}
Err(e) => {
eprintln!("Keepalive ping failed: {}", e);
// Optionally implement reconnection logic here
break;
}
}
*/
// Mock ping for demonstration
println!("Mock keepalive ping sent at {}",
chrono::Utc::now().format("%H:%M:%S"));
}
Ok(())
}Advanced Keepalive with Connection Management
Connection Recovery
Usage Example
Best Practices
Ping frequency: Use 60-second intervals for most applications
Health monitoring: Track connection health and implement recovery
Error handling: Handle ping failures gracefully with exponential backoff
Resource cleanup: Properly close connections on shutdown
Logging: Log keepalive status for debugging and monitoring
Timeouts: Set appropriate timeouts for ping requests
Reconnection logic: Implement automatic reconnection on connection loss
Last updated