Building a Modern Terminal UI in Rust with Ratatui: Real-Time System Monitor Guide

Programming tutorial - IT technology blog
Programming tutorial - IT technology blog

Command-line utilities do not have to look like dense walls of plain text. When a production node misbehaves or a background worker eats an entire thread pool, a crisp terminal dashboard gives you instant visibility. You get fast diagnostic data without launching a 400 MB Electron client or tunneling an X11 session over SSH. Rust excels here. A compiled binary idles at roughly 0.1% CPU, sits under 15 MB of resident RAM, and boots in less than 20 milliseconds.

Let’s build a real-time system monitor from scratch. We will use Ratatui (the active community fork of tui-rs), crossterm for raw terminal manipulation, and sysinfo to poll live CPU and memory metrics.

Quick Start (5 min)

Let’s verify your terminal emulator supports raw input and alternate screen buffers before building full UI layouts.

1. Initialize Cargo Project

Generate a clean binary crate and pull in current releases of the required dependencies:

cargo new ratatui-monitor
cd ratatui-monitor
cargo add [email protected] [email protected] [email protected]

2. The Minimal Scaffold

Terminal applications require a strict setup-and-teardown lifecycle. Put this minimal frame into src/main.rs:

use crossterm::{
    execute,
    terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
};
use ratatui::{
    backend::CrosstermBackend,
    widgets::{Block, Borders, Paragraph},
    Terminal,
};
use std::io::{self, stdout};

fn main() -> Result<(), io::Error> {
    enable_raw_mode()?;
    let mut stdout = stdout();
    execute!(stdout, EnterAlternateScreen)?;
    let backend = CrosstermBackend::new(stdout);
    let mut terminal = Terminal::new(backend)?;

    terminal.draw(|frame| {
        let area = frame.area();
        let greeting = Paragraph::new("System Monitor Initializing...")
            .block(Block::default().title(" Status ").borders(Borders::ALL));
        frame.render_widget(greeting, area);
    })?;

    std::thread::sleep(std::time::Duration::from_secs(2));

    disable_raw_mode()?;
    execute!(terminal.backend_mut(), LeaveAlternateScreen)?;
    terminal.show_cursor()?;
    Ok(())
}

Run cargo run. The program clears your terminal, renders a bordered box in the alternate buffer, pauses for two seconds, and restores your shell history cleanly.

Deep Dive

Every polished TUI relies on three pillars: terminal modes, flexible layouts, and immediate-mode widgets.

The Terminal Lifecycle

By default, terminals operate in canonical mode. The operating system buffers keystrokes until the user hits Enter. In raw mode, the terminal passes every byte straight to your application. That means keypresses register instantly when someone hits q or an arrow key.

Teardown hygiene is non-negotiable. If your binary crashes while raw mode is active, the parent shell stays broken. Characters disappear, the cursor vanishes, and newlines stop carriage-returning. You often have to run reset blind just to recover your prompt.

Responsive Layout Engine

Ratatui divides viewports with a constraint-based layout solver. You assign lengths, percentages, or ratios along vertical and horizontal axes. Whether a user runs an 80×24 tmux pane or a 4K fullscreen alacritty window, the UI adjusts automatically.

Here is how to slice a window into a fixed 3-row header, twin metric meters, and a footer log:

use ratatui::layout::{Constraint, Direction, Layout, Rect};

fn calculate_layout(area: Rect) -> (Rect, Rect, Rect, Rect) {
    let main_chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(3),      // Top header bar
            Constraint::Min(8),         // Metrics area
            Constraint::Length(7),      // Footer logs
        ])
        .split(area);

    let metric_chunks = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([
            Constraint::Percentage(50), // Left: CPU Gauge
            Constraint::Percentage(50), // Right: RAM Gauge
        ])
        .split(main_chunks[1]);

    (main_chunks[0], metric_chunks[0], metric_chunks[1], main_chunks[2])
}

Essential Widgets

Ratatui uses an immediate-mode approach. You do not maintain stateful widget trees across ticks. Instead, you declare lightweight descriptors on every redraw cycle:

  • Block: Draws outer borders, titles, padding, and background fills.
  • Gauge: Renders visual progress bars for metrics like CPU usage or disk saturation.
  • Paragraph: Formats wrapped text blocks with styled inline spans.
  • List: Manages scrollable collections of items like running processes or log streams.

Advanced Usage

Static boxes are straightforward. Next, let’s wire hardware telemetry to an interactive, 4 FPS event loop.

Building the Real-Time Event Loop

Blocking on user input freezes telemetry collection. If you use standard blocking reads, the gauges halt until a user touches the keyboard. We solve this by using event::poll with a 250 ms timeout, giving us smooth 4 Hz updates while keeping idle CPU usage below 0.5%.

use crossterm::event::{self, Event, KeyCode, KeyEventKind};
use ratatui::{
    backend::CrosstermBackend,
    style::{Color, Modifier, Style},
    widgets::{Block, Borders, Gauge, Paragraph},
    Terminal,
};
use sysinfo::System;
use std::{
    io::{self, stdout},
    time::{Duration, Instant},
};

struct App {
    sys: System,
    cpu_usage: f32,
    mem_used_pct: f32,
    should_quit: bool,
}

impl App {
    fn new() -> Self {
        let mut sys = System::new_all();
        sys.refresh_cpu_usage();
        sys.refresh_memory();
        Self {
            sys,
            cpu_usage: 0.0,
            mem_used_pct: 0.0,
            should_quit: false,
        }
    }

    fn update(&mut self) {
        self.sys.refresh_cpu_usage();
        self.sys.refresh_memory();

        self.cpu_usage = self.sys.global_cpu_usage();
        let total_mem = self.sys.total_memory() as f32;
        let used_mem = self.sys.used_memory() as f32;
        self.mem_used_pct = if total_mem > 0.0 { (used_mem / total_mem) * 100.0 } else { 0.0 };
    }
}

fn main() -> Result<(), io::Error> {
    crossterm::terminal::enable_raw_mode()?;
    let mut stdout = stdout();
    crossterm::execute!(stdout, crossterm::terminal::EnterAlternateScreen)?;
    let backend = CrosstermBackend::new(stdout);
    let mut terminal = Terminal::new(backend)?;

    let mut app = App::new();
    let tick_rate = Duration::from_millis(250);
    let mut last_tick = Instant::now();

    loop {
        app.update();
        
        terminal.draw(|f| {
            let chunks = ratatui::layout::Layout::default()
                .direction(ratatui::layout::Direction::Vertical)
                .constraints([
                    ratatui::layout::Constraint::Length(3),
                    ratatui::layout::Constraint::Length(3),
                    ratatui::layout::Constraint::Length(3),
                    ratatui::layout::Constraint::Min(0),
                ])
                .split(f.area());

            let title = Paragraph::new("System Monitor (Press 'q' to quit)")
                .style(Style::default().fg(Color::Cyan).add_modifier(Modifier::BOLD))
                .block(Block::default().borders(Borders::ALL));
            f.render_widget(title, chunks[0]);

            let cpu_label = format!("CPU Usage: {:.1}%", app.cpu_usage);
            let cpu_gauge = Gauge::default()
                .block(Block::default().title(cpu_label).borders(Borders::ALL))
                .gauge_style(Style::default().fg(Color::Green))
                .percent(app.cpu_usage.clamp(0.0, 100.0) as u16);
            f.render_widget(cpu_gauge, chunks[1]);

            let mem_label = format!("Memory Usage: {:.1}%", app.mem_used_pct);
            let mem_gauge = Gauge::default()
                .block(Block::default().title(mem_label).borders(Borders::ALL))
                .gauge_style(Style::default().fg(Color::Yellow))
                .percent(app.mem_used_pct.clamp(0.0, 100.0) as u16);
            f.render_widget(mem_gauge, chunks[2]);
        })?;

        let timeout = tick_rate.saturating_sub(last_tick.elapsed());
        if event::poll(timeout)? {
            if let Event::Key(key) = event::read()? {
                if key.kind == KeyEventKind::Press && key.code == KeyCode::Char('q') {
                    app.should_quit = true;
                }
            }
        }

        if last_tick.elapsed() >= tick_rate {
            last_tick = Instant::now();
        }

        if app.should_quit {
            break;
        }
    }

    crossterm::terminal::disable_raw_mode()?;
    crossterm::execute!(terminal.backend_mut(), crossterm::terminal::LeaveAlternateScreen)?;
    terminal.show_cursor()?;
    Ok(())
}

Practical Tips

Here are three production guardrails to avoid common TUI bugs in edge cases.

1. Catching Panics Gracefully

An unhandled Rust panic inside raw mode corrupts the active terminal session. To protect users, install a panic hook that resets terminal states and re-enables cursor visibility before printing tracebacks:

fn install_panic_hook() {
    let original_hook = std::panic::take_hook();
    std::panic::set_hook(Box::new(move |panic_info| {
        let _ = crossterm::terminal::disable_raw_mode();
        let _ = crossterm::execute!(
            std::io::stdout(),
            crossterm::terminal::LeaveAlternateScreen,
            crossterm::cursor::Show
        );
        original_hook(panic_info);
    }));
}

2. Avoiding Spinlocks and Busy Waiting

Never write a raw loop {} without a sleep or polling timeout. A naive loop pegs an entire CPU core at 100% simply evaluating empty iterations. Using event::poll(timeout) puts the thread to sleep in the OS kernel scheduler until input arrives or the 250 ms tick expires.

3. Supporting Resizing Automatically

Do not hardcode dimensions or cache coordinates between frames. Ratatui fetches dynamic terminal bounds directly from frame.area() on every draw. Use responsive constraints (Percentage, Ratio, and Min), and your interface will adjust seamlessly whether resized to 80×24 or 200×60.

Share: