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

  1. Ping frequency: Use 60-second intervals for most applications

  2. Health monitoring: Track connection health and implement recovery

  3. Error handling: Handle ping failures gracefully with exponential backoff

  4. Resource cleanup: Properly close connections on shutdown

  5. Logging: Log keepalive status for debugging and monitoring

  6. Timeouts: Set appropriate timeouts for ping requests

  7. Reconnection logic: Implement automatic reconnection on connection loss

Last updated