How to Create a Real-Time Dashboard Using Ratatui

Combine a tick-based loop with gauges, sparklines and bar charts to build a live dashboard that refreshes smoothly without wasting CPU.

ProjectsRatatui Editorial Team8 min read
How to Create a Real-Time Dashboard Using Ratatui featured image

Real-time dashboards are where terminal interfaces shine. They start instantly, work over SSH and stay readable on a server with no desktop environment. In this tutorial you will build a live metrics dashboard with Ratatui: a CPU line chart that scrolls as new data arrives, a memory gauge and a requests-per-second sparkline, fed by a background thread and redrawn at a steady frame rate. The result is a complete program you can adapt to real data sources such as system statistics, application metrics or a message queue.

The full source, shown later in the article, compiles without warnings on Ratatui 0.30.2. If you are new to Ratatui, read how to build your first terminal application first; this article assumes you know how terminal.draw() and event handling work.

Dashboard Architecture: Data, State and Frames

A dashboard has three moving parts that run at different speeds:

  • A data source produces readings on its own schedule. It might poll the operating system every second, receive network messages, or tail a log file.
  • Application state stores recent history: the last 120 CPU samples, the latest memory reading, whether the user paused the view.
  • The render loop turns state into frames and reacts to keys.

Keeping them separate is the key to a responsive interface. If you collected data inside the draw closure, a slow network call would freeze the screen and delay key presses. Instead, the collector runs on another thread and sends Sample values through a channel. The UI thread drains the channel, updates state and draws. Nothing in the render path ever blocks on I/O.

Ratatui operations dashboard showing services, rollout gauge, error-rate sparkline and events
Illustrative preview of a larger operations dashboard built with the same techniques.

The Tick-Based Event Loop

A simple Ratatui app blocks on event::read() until the user presses a key. A dashboard cannot do that, because it must redraw when new data arrives even if nobody touches the keyboard. The solution is event::poll(timeout): it waits for input, but only up to the given duration, then returns false so your loop can continue.

Each iteration of our loop does three things in order. First, it drains every sample waiting in the channel with try_recv(), which never blocks. Second, it redraws if at least 100 milliseconds have passed since the previous frame, capping the frame rate at ten per second. Third, it polls for input with a timeout equal to the time remaining until the next frame is due. The result is a loop that sleeps most of the time, wakes up promptly for key presses and redraws on a predictable schedule.

Separating the data rate from the frame rate matters. Here the collector produces five samples per second and the UI draws ten frames per second, but either could change independently, for example when you speed up sampling without making the terminal work harder.

Storing History with a Ring Buffer

Charts need recent history, not every reading since the program started. A VecDeque with a fixed capacity works as a ring buffer: push new samples onto the back and pop the oldest from the front once the limit is reached. Memory stays constant no matter how long the dashboard runs.

The CPU history stores (x, y) pairs because Chart plots points on numeric axes. Using a monotonically increasing tick counter as the x value makes the chart scroll naturally: each frame, the visible window spans from ticks - 120 to ticks, so old points slide off the left edge. The requests history stores plain u64 values because Sparkline takes a slice of integers.

A Background Data Collector

The example simulates metrics with trigonometric functions so it runs anywhere without extra crates. In a real project, replace the body of the loop with calls to your data source, such as reading /proc on Linux, querying an HTTP endpoint or using a system-information crate. The important properties stay the same: the collector owns its timing, sends owned values through the channel and stops when the receiver is dropped, which happens automatically when the UI exits.

Channels from std::sync::mpsc are enough for one producer feeding one UI. If you already use Tokio, an async task with a tokio::sync::mpsc channel fills the same role, and you can drive input with crossterm's EventStream. The Ratatui and crossterm guide explains that variant.

The Complete Dashboard Program

Create a new project with cargo new live-dashboard, run cargo add ratatui and replace src/main.rs with the following code:

src/main.rs
use std::collections::VecDeque;
use std::sync::mpsc::{self, Receiver};
use std::thread;
use std::time::{Duration, Instant};

use ratatui::crossterm::event::{self, Event, KeyCode, KeyEventKind};
use ratatui::layout::{Constraint, Layout};
use ratatui::style::{Style, Stylize};
use ratatui::symbols::Marker;
use ratatui::widgets::{Axis, Block, Chart, Dataset, Gauge, GraphType, Paragraph, Sparkline};
use ratatui::{DefaultTerminal, Frame};

/// One reading produced by the background collector.
struct Sample {
    cpu: f64,
    memory: f64,
    requests: u64,
}

struct App {
    cpu_history: VecDeque<(f64, f64)>,
    req_history: VecDeque<u64>,
    memory: f64,
    ticks: u64,
    paused: bool,
}

const HISTORY: usize = 120;

impl App {
    fn new() -> Self {
        Self {
            cpu_history: VecDeque::with_capacity(HISTORY),
            req_history: VecDeque::with_capacity(HISTORY),
            memory: 0.0,
            ticks: 0,
            paused: false,
        }
    }

    fn push(&mut self, s: Sample) {
        if self.paused {
            return;
        }
        self.ticks += 1;
        if self.cpu_history.len() == HISTORY {
            self.cpu_history.pop_front();
            self.req_history.pop_front();
        }
        self.cpu_history.push_back((self.ticks as f64, s.cpu));
        self.req_history.push_back(s.requests);
        self.memory = s.memory;
    }
}

/// Simulates a metrics source on its own thread.
fn spawn_collector(interval: Duration) -> Receiver<Sample> {
    let (tx, rx) = mpsc::channel();
    thread::spawn(move || {
        let mut t: f64 = 0.0;
        loop {
            t += 0.15;
            let sample = Sample {
                cpu: 50.0 + 30.0 * t.sin() + 10.0 * (t * 2.7).cos(),
                memory: 0.55 + 0.15 * (t * 0.3).sin(),
                requests: (40.0 + 25.0 * (t * 1.3).sin().abs()) as u64,
            };
            if tx.send(sample).is_err() {
                break; // the UI has exited
            }
            thread::sleep(interval);
        }
    });
    rx
}

fn main() -> std::io::Result<()> {
    ratatui::run(run)
}

fn run(terminal: &mut DefaultTerminal) -> std::io::Result<()> {
    let samples = spawn_collector(Duration::from_millis(200));
    let mut app = App::new();
    let frame_rate = Duration::from_millis(100);
    let mut last_draw = Instant::now() - frame_rate;

    loop {
        // 1. Drain everything the collector produced since the last frame.
        while let Ok(sample) = samples.try_recv() {
            app.push(sample);
        }
        // 2. Redraw at most ten times per second.
        if last_draw.elapsed() >= frame_rate {
            terminal.draw(|frame| render(frame, &app))?;
            last_draw = Instant::now();
        }
        // 3. Wait for input, but never longer than the next frame is due.
        let timeout = frame_rate.saturating_sub(last_draw.elapsed());
        if event::poll(timeout)? {
            if let Event::Key(key) = event::read()? {
                if key.kind == KeyEventKind::Press {
                    match key.code {
                        KeyCode::Char('q') => return Ok(()),
                        KeyCode::Char('p') => app.paused = !app.paused,
                        _ => {}
                    }
                }
            }
        }
    }
}

fn render(frame: &mut Frame, app: &App) {
    let [header, chart_area, bottom] = Layout::vertical([
        Constraint::Length(1),
        Constraint::Fill(2),
        Constraint::Fill(1),
    ])
    .areas(frame.area());
    let [gauge_area, spark_area] =
        Layout::horizontal([Constraint::Percentage(40), Constraint::Fill(1)]).areas(bottom);

    let status = if app.paused { "PAUSED".yellow() } else { "LIVE".green() };
    frame.render_widget(
        Paragraph::new(ratatui::text::Line::from(vec![
            " metrics ".bold(), status, "  p: pause  q: quit".dim(),
        ])),
        header,
    );

    let points: Vec<(f64, f64)> = app.cpu_history.iter().copied().collect();
    let x_max = app.ticks.max(HISTORY as u64) as f64;
    let x_min = x_max - HISTORY as f64;
    let dataset = Dataset::default()
        .name("cpu %")
        .marker(Marker::Braille)
        .graph_type(GraphType::Line)
        .cyan()
        .data(&points);
    let chart = Chart::new(vec![dataset])
        .block(Block::bordered().title(" CPU "))
        .x_axis(Axis::default().bounds([x_min, x_max]))
        .y_axis(Axis::default().bounds([0.0, 100.0]).labels(["0", "50", "100"]));
    frame.render_widget(chart, chart_area);

    let gauge = Gauge::default()
        .block(Block::bordered().title(" Memory "))
        .gauge_style(Style::new().green())
        .ratio(app.memory.clamp(0.0, 1.0));
    frame.render_widget(gauge, gauge_area);

    let reqs: Vec<u64> = app.req_history.iter().copied().collect();
    let sparkline = Sparkline::default()
        .block(Block::bordered().title(" Requests/s "))
        .data(&reqs)
        .magenta();
    frame.render_widget(sparkline, spark_area);
}

Run it with cargo run --release. Press p to pause the chart and q to quit. Resizing the terminal works without extra code because the layout is recalculated from frame.area() on every draw.

Laying Out the Panels

The render function splits the screen vertically into a one-line header, a chart area and a bottom row, using Fill(2) and Fill(1) so the chart gets two thirds of the remaining height. The bottom row is split horizontally into a gauge and a sparkline. Destructuring the result of .areas() into named variables makes the intent obvious and lets the compiler check that the number of areas matches the number of constraints.

When you add more panels, keep each one in its own function that takes &mut Frame, a Rect and a reference to the state it needs. Our layouts and constraints guide covers responsive patterns, such as stacking panels vertically when the terminal is narrow.

Choosing Widgets for Live Data

  • Chart suits continuous series where trend and scale matter. Braille markers give high resolution, and fixed y-axis bounds stop the chart from jumping as values change.
  • Gauge communicates a single utilization value instantly. Clamp the ratio between 0.0 and 1.0, because Gauge::ratio panics on values outside that range.
  • Sparkline shows the shape of recent activity in very little space and scales automatically to the largest visible value unless you set .max().
  • Table (not used here) is ideal for top-N lists such as busiest processes or slowest endpoints. Sort the data in state, not in the render function.

Keeping the Dashboard Smooth and Efficient

Ratatui already does the heavy lifting by diffing each frame against the previous one and sending only changed cells. A few habits keep the rest of your program equally light:

  • Cap the frame rate. Ten to thirty frames per second is plenty for a terminal. Drawing in a tight loop wastes CPU without visible benefit.
  • Do no I/O in draw. Reading files or the network inside the closure stalls rendering and input handling.
  • Avoid unnecessary allocations. Converting a VecDeque to a Vec each frame is cheap at 120 elements, but for large histories consider make_contiguous() or storing data in a plain vector with an index.
  • Build in release mode. Debug builds can be several times slower for numeric work, which matters when you aggregate large datasets.
  • Redraw only when needed. For dashboards that update rarely, skip the draw when nothing changed since the last frame.

Handling Errors from the Data Source

Real collectors fail: a host goes offline, a file disappears or a request times out. Instead of panicking in the background thread, send an error variant through the channel, for example an enum with Sample and Error(String) cases, and show the latest error in the header with a warning color. The UI keeps running, the user sees what went wrong, and the collector can retry with a backoff.

Ideas for Extending the Dashboard

Once the skeleton works, add a Tabs header to switch between hosts, a table of the noisiest processes, color thresholds that turn the gauge yellow above 70 percent and red above 90, or alerts that flash in the header. You can also accept command-line arguments with a parser such as Clap to choose the refresh interval or data source. Because state, collection and rendering are separate, each feature touches only one part of the code.

Ratatui system monitor with per-core CPU line gauges, process table, memory and temperature gauges
Illustrative: per-core gauges and a process table are natural next steps.

Frequently Asked Questions

Ten to thirty frames per second is enough for smooth updates. Ratatui sends only changed cells, but capping the rate still saves CPU, especially over SSH.

Both work. Standard threads with std::sync::mpsc are simple and need no extra crates. If your app already uses Tokio, async tasks and channels integrate naturally with crossterm's EventStream.

Usually the axis bounds do not include your points. Chart draws only points inside the bounds you pass to Axis::bounds(), so update the x-axis window as time advances.

Yes. Replace the simulated values in the collector thread with readings from your operating system or a system-information crate. The rendering code does not need to change.

Use event::poll with a timeout instead of a busy loop, and skip terminal.draw() when no new data arrived and no key was pressed.

Conclusion

A responsive Ratatui dashboard comes down to a clean separation of concerns: a collector that produces data on its own thread, a ring buffer that keeps recent history, and an event loop that drains new data, redraws on a fixed schedule and waits for input with event::poll. With that structure in place, adding charts, gauges and tables is straightforward. Explore more widgets in our widgets reference, compare patterns on the examples page, and see the official Ratatui website for additional recipes such as async event handling and application templates.

Ratatui Editorial Team

We write tested guides for Rust developers building terminal user interfaces. Every code sample in this article was compiled against Ratatui 0.30.2. Spotted an issue? Let us know.