Skip to chapter content
navan✳THE BUILD LABRUST / GUIDE
0/26 read
CHAPTER 21 / 21 · SYSTEMS BOUNDARIES

Performance and complete systems.

Connect language rules to measurement, deployment, and a coherent system design.

BY NAVAN SAMILONG READRUST 2024THEORY FIRST
01 / THE MENTAL MODEL

The idea behind the syntax.

Rust's zero-cost-abstraction goal means higher-level code can often compile to efficient machine code, but an individual program's performance still depends on algorithms, allocations, I/O, and workload. Measure the behavior that matters before optimising. A microbenchmark of a tiny loop may say little about a real service dominated by network waits or disk access.

A system also has boundaries beyond the compiler: configuration, logs, data format, failure recovery, packaging, and deployment. The type system can help encode many contracts, but operational behavior must be designed. A program that returns the correct answer on one machine may still fail because a file path, permission, dependency, or shutdown sequence differs elsewhere.

02 / THE RULES

What Rust is checking.

A useful performance investigation starts with a baseline and a representative input. Identify whether time is spent in computation, allocation, locking, or waiting. Change one thing, measure again, and keep the simpler version if the supposed improvement is not meaningful. Profiling reveals hotspots that intuition can miss; release builds also differ substantially from debug builds.

When reading a complete application, trace one request or command from input through parsing, domain logic, storage, and output. At each boundary, ask who owns the data, what type represents failure, and what happens if work stops halfway. Those questions unify the earlier chapters. The cookbook remains a separate place to explore full projects; this reading course ends with the principles that make such projects comprehensible.

03 / CODE, EXPLAINED

See the rule in context.

Each example isolates one part of the model. Follow the bindings, types, ownership transfers, and possible outcomes line by line.

EXAMPLE 01

Performance & measurement

Start performance work by choosing a representative workload and measuring an optimized build. Debug builds can exaggerate costs that optimization removes. Algorithmic complexity, allocation patterns, unnecessary copies, and I/O often matter more than a clever local expression. Reserve capacity when the final size is known and useful, but do not treat capacity as correctness. Instant measures elapsed time on a monotonic clock; one tiny timing is not a reliable benchmark. Use repeatable benchmarks and compare identical semantics before accepting an optimization.

performance.rs
fn main() {
    let mut output = Vec::with_capacity(4);
    for n in 0..4 {
        output.push(n * n);
    }
    println!("{output:?}");
    assert_eq!(output.len(), 4);
}
OUTPUT
[0, 1, 4, 9]
  1. with_capacity can avoid growth reallocations for this known size.
  2. Length remains zero until elements are pushed.
  3. Use cargo run --release for representative optimized application measurements.

The boundary: Faster code with different overflow, error, or ordering semantics is not an equivalent optimization.

EXAMPLE 02

Release builds, docs & deployment

cargo build --release produces an optimized binary for a selected target. That does not make a binary portable across every operating system, architecture, or C library. A deployable service also needs configuration, health checks, graceful shutdown, logs, and an explicit persistence model. Desktop applications add platform dependencies, bundling, and signing. The cookbook includes local runnable projects and describes the next production decisions beside each one. Review dependency updates and lockfile changes as part of maintaining the application, not just launching it.

shipping.rs
use std::time::Duration;
fn main() {
    let shutdown_budget = Duration::from_secs(10);
    let environment = "local";
    println!(
        "mode={environment}, shutdown={}s",
        shutdown_budget.as_secs()
    );
}
OUTPUT
mode=local, shutdown=10s
  1. A shutdown budget is an operational policy, not automatic cancellation.
  2. Use configuration at the application boundary.
  3. The cookbook shows ctrl_c handling and a local-only default address.

The boundary: Do not assume an in-memory task list or broadcast chat survives a restart. Persistence and delivery guarantees need a deliberate design.

EXAMPLE 03

Capstone: a tested text index

This capstone turns text documents into a small inverted index. Each lowercase whitespace-separated term maps to a sorted set of document IDs. Inserting the same term twice in one document does not duplicate the posting. Querying returns the stored IDs in sorted order. This deliberately simple tokenizer treats punctuation as part of a term and is not a complete search engine. Make that contract visible, then extend it with multi-term intersections, replacement semantics, and persistence only when tests define the new behavior.

capstone.rs
use std::collections::{BTreeMap, BTreeSet};
#[derive(Default)]
struct Index {
    postings: BTreeMap<String, BTreeSet<u32>>,
}
impl Index {
    fn insert(&mut self, id: u32, text: &str) {
        for word in text.split_whitespace() {
            self.postings
                .entry(word.to_lowercase())
                .or_default()
                .insert(id);
        }
    }
    fn query(&self, word: &str) -> Vec<u32> {
        self.postings
            .get(&word.to_lowercase())
            .map(|ids| ids.iter().copied().collect())
            .unwrap_or_default()
    }
}
fn main() {
    let mut index = Index::default();
    index.insert(2, "Rust builds");
    index.insert(1, "rust rust tests");
    println!("{:?}", index.query("RUST"));
    assert!(index.query("missing").is_empty());
}
OUTPUT
[1, 2]
  1. The outer map owns normalized terms.
  2. The set deduplicates document IDs and sorts the results.
  3. Query borrows the index and returns an independent vector.

The boundary: This insert method adds postings; reusing an ID does not remove its old terms. Define document replacement separately.

04 / THE CONNECTION

Keep this model.

Performance claims need measurement, and reliable systems need explicit behavior at every boundary. Rust supplies strong language rules within that larger design.

Finished reading?
Built with curiosity. By Navan Sami. ↗Rust · The rules behind the code.