Skip to content
ImagineWorld

Architectural Patterns

node_idnode-book_design-patterns-and-best-practices-in-rust_chapter-09-architectural-patterns
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num9
chapter_titleArchitectural Patterns
pillar_membershipJ — architecture_design_craft
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

In this chapter, we’ll explore architectural patterns by building Samsa, a producer/consumer (also called pub/sub for “publish/subscribe”) microservice. The name is a nod to Gregor Samsa, the protagonist of Franz Kafka’s The Metamorphosis; our Samsa borrows its architecture from the distributed streaming platform that shares the author’s name. We use the term microservice loosely: our implementation is entirely in-memory, focusing on design patterns rather than networking or deployment. Chapters 10 through 12 continue building on Samsa, applying additional Rust patterns to the same codebase.

Architectural patterns operate at a higher level than the design patterns we’ve seen so far, shaping how entire systems are organized. In Rust, these patterns are particularly important because the language’s ownership system works best when we design with clear data flows, contained mutability, well-defined module boundaries, and lightweight data structures from the start.

We’ll discover how Rust’s seemingly restrictive rules actually guide us toward better architectural decisions. The borrow checker doesn’t fight good design – it enforces principles that lead to more reliable, debuggable code.

In this chapter we’re going to cover the following main topics:

  • Data flows downward
  • Mutability stays contained
  • Modules become interfaces
  • Pack lightly

The source code for the exercises can be found on GitHub at https://github.com/PacktPublishing/Design-Patterns-and-Best-Practices-in-Rust. The repository is organized by chapter. The relevant exercises for this chapter are at https://github.com/PacktPublishing/Design-Patterns-and-Best-Practices-in-Rust/tree/main/ch9.

In this chapter, we’ll start building Samsa – a producer/consumer microservice that will evolve throughout Chapters 9–12. You can build and run the complete examples with cargo build and cargo run --example basic_pubsub.

The most important architectural principle in Rust is designing systems where data flows in clear, predictable directions. Unidirectional, downward data flow minimizes complexity and bugs. This was true in Rust, Python, C++, and every other language. The difference is that those languages allow you to ignore this principle. Rust doesn’t.

When bidirectional communication is needed (such as consumer acknowledgments), the solution is to create a separate downward channel rather than allowing data to flow back upstream.

Let’s build our producer/consumer system with clear directional flow: producers send messages down to the broker, which delivers them down to consumers.

Figure 9.1: Samsa’s unidirectional data flow

To implement this flow, we need a data structure that can travel through each layer unchanged. Our core Message type represents data flowing through the system. Let’s build it step by step:

  • Define the message structure with essential fields for pub/sub messaging
  • Make messages immutable once created to prevent modification during transit
  • Add timestamp tracking to know when each message was created
  • Provide convenient constructors for common use cases

Let’s implement these design decisions in code:

src/message.rs
use std::time::Instant;
/// Messages are immutable once created and flow downward:
/// Producer -> Broker -> Consumer
#[derive(Debug, Clone)]
pub struct Message {
pub topic: String,
pub key: Option<String>,
pub value: Vec<u8>,
pub timestamp: Instant,
}
impl Message {
pub fn new(topic: impl Into<String>, key: Option<String>, value: impl Into<Vec<u8>>) -> Self {
Self {
topic: topic.into(),
key,
value: value.into(),
timestamp: Instant::now(),
}
}
pub fn text(topic: impl Into<String>, text: impl Into<String>) -> Self {
Self::new(topic, None, text.into().into_bytes())
}
pub fn as_text(&self) -> Option<&str> {
std::str::from_utf8(&self.value).ok()
}
}
/// Events represent messages with broker-added metadata
#[derive(Debug, Clone)]
pub struct Event {
pub message: Message,
pub offset: u64,
}
impl Event {
pub fn new(message: Message, offset: u64) -> Self {
Self { message, offset }
}
}

This design creates the foundation for unidirectional data flow. The topic field determines which consumers receive the message, similar to a “channel” or “subject” in other messaging systems. The optional key supports partitioning messages within a topic, and the value holds the actual data payload as Vec<u8> to support any format.

The impl Into<String> parameter type in the constructor accepts both String and &str arguments without requiring the caller to call .to_string() explicitly. Rust’s Into trait handles the conversion.

The Message struct is deliberately simple and immutable: once created, it cannot be modified.

The .into() calls here are infallible conversions (String to String, or &str to String); they cannot panic.

Immutable messages prevent accidental modification as they flow through the system. The clear separation between Message (user data, which is used by producers and consumers) and Event (broker metadata) means producers and consumers only see what they need, while the broker maintains control over ordering and delivery guarantees. This Message type forms the foundation of Samsa’s data flow. The offset is a monotonically increasing integer that records the event’s position within its topic. Consumers use offsets to track which messages they have already processed and to resume reading from where they left off.

We will also need to define a Samsa error type. We’re creating a library, so users will expect clearly defined error values and also the convenience of a custom Result type:

use thiserror::Error;
#[derive(Error, Debug, Clone)]
pub enum SamsaError {
#[error("Broker error: {0}")]
Broker(String),
}
pub type Result<T> = std::result::Result<T, SamsaError>;

This error type provides a clear way to represent failures across the system.

Producers are the entry point for data into our system. Let’s implement them with strict adherence to downward flow:

  • Hold a reference to the broker but never receive data back from it
  • Provide simple sending methods that hide broker complexity
  • Return only acknowledgment data (like offsets) that doesn’t break the flow direction
  • Encapsulate message creation for common patterns

Let’s implement this design in code:

src/producer.rs
use crate::{Message, Broker};
use std::sync::Arc;
/// Producers only push data downward - they never receive data back
pub struct Producer {
broker: Arc<Broker>,
}
impl Producer {
pub fn new(broker: Arc<Broker>) -> Self {
Self { broker }
}
pub fn send(&self, message: Message) -> Result<u64> {
self.broker.publish(message)
}
pub fn send_text(&self, topic: &str, text: &str) -> Result<u64> {
let message = Message::text(topic, text);
self.send(message)
}
}

The producer is intentionally limited: it can only send data downward to the broker. Notice how the send method returns a Result<u64>, representing either success (with offset) or failure. It never retrieves data from the broker.

This constraint prevents producers from becoming sources of complexity. They can’t query broker state, fetch messages, or create bidirectional dependencies. The clean interface means producers are easy to test, reason about, and replace with alternative implementations. With this producer design, Samsa can accept messages from any number of clients without creating complex dependencies.

The broker is the central component that maintains data flow direction while managing all the complexity. Here’s how we’ll build it:

  • Encapsulate all mutable state behind thread-safe wrappers (Arc<Mutex<T>>)
  • Provide clear publish/fetch operations that enforce the flow direction
  • Handle concurrency safely with mutexes around shared data
  • Generate monotonic offsets to maintain message ordering

Let’s implement the broker:

src/broker.rs
use crate::{Message, Event, storage::Storage};
use std::sync::{Arc, Mutex};
use std::collections::HashMap;
pub struct Broker {
storage: Arc<Mutex<Storage>>,
topic_offsets: Arc<Mutex<HashMap<String, u64>>>,
}
impl Broker {
pub fn new() -> Self {
Self {
storage: Arc::new(Mutex::new(Storage::new())),
topic_offsets: Arc::new(Mutex::new(HashMap::new())),
}
}
/// Data flows DOWN from producer to broker
pub fn publish(&self, message: Message) -> Result<u64> {
let mut storage = self.storage.lock()
.map_err(|_| SamsaError::Broker("Storage lock poisoned".into()))?;
let mut offsets = self.topic_offsets.lock()
.map_err(|_| SamsaError::Broker("Topic offsets lock poisoned".into()))?;
let topic = message.topic.clone();
let offset = offsets.entry(topic.clone()).or_insert(0);
let current_offset = *offset;
*offset += 1;
let event = Event::new(message, current_offset);
storage.append(topic, event)?;
Ok(current_offset)
}
/// Data flows DOWN from broker to consumer
pub fn fetch(&self, topic: &str, from_offset: u64, max_events: usize) -> Result<Vec<Event>> {
let storage = self.storage.lock().unwrap();
storage.fetch(topic, from_offset, max_events)
}
pub fn latest_offset(&self, topic: &str) -> u64 {
let offsets = self.topic_offsets.lock().unwrap();
*offsets.get(topic).unwrap_or(&0)
}
}

The broker enforces unidirectional flow through its API design. publish() accepts data from above (producers) and stores it. fetch() provides data to the consumers below. The broker never sends data back upstream to producers or receives data from consumers.

For brevity, in the Samsa code, we occasionally use .lock().unwrap() to acquire mutex locks. As we mentioned in the previous chapter, in production code, you would handle the PoisonError that lock() returns (which occurs when a thread panics while holding the lock). The code repository uses proper error handling with map_err; we use unwrap() in the text for brevity.

All mutable state is contained within the broker and protected by mutexes. This prevents race conditions while maintaining clear flow direction. The broker acts as a controlled gateway that accepts data from one direction and provides it in another, never creating circular dependencies. The broker is Samsa’s central coordinator, managing the flow while keeping complexity contained.

Note: Wait, didn’t Chapter 3 say Arc<Mutex<T>> is bad?

In Chapter 3, Anti-Pattern: Using Clone and Rc Everywhere, we warned against reflexively reaching for smart pointers like Arc<Mutex<T>> to solve borrow checker issues. So why are we using it here?

The difference is that pub/sub systems are inherently concurrent. A message broker exists specifically to allow multiple producers and consumers to share access to topics simultaneously. This is exactly the use case where Arc<Mutex<T>> is appropriate. Because many producers and consumers can hold references to the same broker, we need multiple ownership. Because different threads will access the broker concurrently, we require thread safety. Because multiple threads need to modify the same storage and offset tracking, we have to share mutable state.

The anti-pattern from Chapter 3 was using smart pointers like Arc<Mutex<T>> to fight the borrow checker, typically in single-threaded code. Here, we’re using it because we genuinely need thread-safe shared ownership.

Don’t avoid smart pointers like Arc<Mutex<T>> when you actually need them. The question to ask is: “Do I have a clear reason (like multiple threads that need to share mutable state) why smart pointers are necessary?” If yes, smart pointers are the right tool. If not, design with ownership and borrowing first.

Consumers complete the downward flow by being pure data sinks. Let’s implement them to maintain flow direction:

  • Maintain only local state (current offset position)
  • Pull data from the broker without sending anything back
  • Track consumption progress independently of other consumers
  • Provide a simple polling interface for retrieving messages

Let’s implement the consumer:

src/consumer.rs
use crate::{Event, Broker};
use std::sync::Arc;
/// Consumers only pull data - they never push data back upstream
pub struct Consumer {
broker: Arc<Broker>,
topic: String,
offset: u64,
}
impl Consumer {
pub fn new(broker: Arc<Broker>, topic: impl Into<String>) -> Self {
let topic = topic.into();
let offset = broker.latest_offset(&topic);
Self { broker, topic, offset }
}
pub fn from_beginning(broker: Arc<Broker>, topic: impl Into<String>) -> Self {
Self {
broker,
topic: topic.into(),
offset: 0,
}
}
/// Pulls data DOWN from the broker
pub fn poll(&mut self) -> Result<Option<Event>> {
let events = self.broker.fetch(&self.topic, self.offset, 1)?;
if let Some(event) = events.into_iter().next() {
self.offset = event.offset + 1;
Ok(Some(event))
} else {
Ok(None)
}
}
}

Consumers maintain only their own position state and never send data back upstream. Each consumer tracks its own offset independently, meaning multiple consumers can read the same topic at different rates without interfering with each other.

This design eliminates the complex consumer group management found in systems like Kafka. Each consumer is responsible for its own progress, making the system simpler to understand and debug. Consumers can start from any offset, replay messages, or skip ahead as needed. Samsa’s consumer design prioritizes simplicity and independence over complex coordination.

The storage layer provides the foundation for our broker’s persistence. It is purely functional – it provides data operations without exposing internal structure. Let’s implement it as a simple but complete abstraction:

  • Organize events by topic using a hash map structure
  • Provide append-only semantics to maintain message order
  • Support efficient range queries for consumer fetching
  • Track latest offsets for new consumer positioning

Let’s implement the storage layer with these requirements in mind:

src/storage.rs
use crate::{Event, Result};
use std::collections::HashMap;
pub struct Storage {
topics: HashMap<String, Vec<Event>>,
}
impl Storage {
pub fn new() -> Self {
Self { topics: HashMap::new() }
}
pub fn append(&mut self, topic: String, event: Event) -> Result<()> {
self.topics
.entry(topic)
.or_default()
.push(event);
Ok(())
}
pub fn fetch(&self, topic: &str, from_offset: u64, max_events: usize) -> Result<Vec<Event>> {
if let Some(events) = self.topics.get(topic) {
let start = from_offset as usize;
if start < events.len() {
let end = std::cmp::min(start + max_events, events.len());
return Ok(events[start..end].to_vec());
}
}
Ok(Vec::new())
}
}

When you try to violate unidirectional flow, Rust stops you. Rust’s type system prevents us from creating a web of dependencies that lead to maintenance nightmares. The compiler forces us to think about ownership and data flow before we can even run our code.

Instead of discovering architectural problems months later during debugging sessions, Rust catches them immediately. If consumers need to send acknowledgments, we’re guided toward better patterns, like creating a separate downward flow through the broker rather than reaching back upstream.

This architectural principle was always good practice in every language. Rust simply enforces it.

Designing with downward data flow provides several advantages:

  • Predictable debugging: When something goes wrong, you know data only flows in one direction, so the source is always upstream
  • Easier testing: Each component can be tested in isolation by providing mock inputs from above
  • Clear dependencies: Components only depend on what’s above them, never on what’s below
  • Natural concurrency: Downward flow maps well to message-passing patterns and async processing

The second principle is confining mutability to specific, well-defined components. In other languages, state can be mutated from anywhere. Rust’s ownership system forces us to be explicit about where mutation happens.

Let’s demonstrate how immutability prevents state corruption by designing messages that cannot be modified after creation:

impl Message {
pub fn new(topic: impl Into<String>, key: Option<String>, value: impl Into<Vec<u8>>) -> Self {
Self {
topic: topic.into(),
key,
value: value.into(),
timestamp: Instant::now(), // Set once, never changes
}
}
// All other methods are getters - no mutation allowed
pub fn as_text(&self) -> Option<&str> {
std::str::from_utf8(&self.value).ok()
}
}

By providing only new as a constructor and accessor methods such as as_text (named following Rust’s convention, where as_* methods provide an alternative view of existing data), we ensure messages cannot be modified after creation. The timestamp is set once during construction and cannot be changed, preventing time-based inconsistencies.

It is worth noting that Rust structs are not inherently immutable; a Message held in a mut binding could be modified. The immutability here is architectural: we provide no setter methods, and the system never passes mutable references to messages. This design choice, enforced by the API rather than the type system, is what eliminates entire classes of bugs related to unexpected state changes.

Now let’s see how to properly contain mutation within a single component – the broker. We’ll make all state changes explicit and controlled:

impl Broker {
pub fn publish(&self, message: Message) -> Result<u64> {
let mut offsets = self.topic_offsets.lock().unwrap();
let topic = message.topic.clone();
let offset = offsets.entry(topic.clone()).or_insert(0);
let current_offset = *offset;
*offset += 1;
let event = Event::new(message, current_offset);
let mut storage = self.storage.lock().unwrap();
storage.append(topic, event)?;
Ok(current_offset)
}
// Queries don't mutate
pub fn fetch(&self, topic: &str, from_offset: u64, max_events: usize) -> Result<Vec<Event>> {
let storage = self.storage.lock().unwrap(); // Immutable borrow
storage.fetch(topic, from_offset, max_events)
}
}

The broker’s API makes mutation explicit and controlled. Notice how every mutable operation requires acquiring a lock, making concurrency safety visible in the code. The publish() method clearly modifies state while fetch() is obviously a query operation.

By containing all mutation within the broker and protecting it with mutexes, we eliminate data races and make the system’s behavior predictable. Other components can safely hold references to the broker without worrying about concurrent modifications affecting their operations.

Let’s demonstrate how individual consumers maintain their own state without interfering with each other:

impl Consumer {
pub fn poll(&mut self) -> Result<Option<Event>> {
let events = self.broker.fetch(&self.topic, self.offset, 1)?;
if let Some(event) = events.into_iter().next() {
self.offset = event.offset + 1;
// Only THIS consumer modifies its offset
Ok(Some(event))
} else {
Ok(None)
}
}
}

Each consumer owns its offset state completely. The self.offset = event.offset + 1 line shows the only place where a consumer’s position can change – within its own poll() method. No external component can modify a consumer’s state.

This ownership model eliminates complex coordination between consumers. Each consumer can read at its own pace, restart from any position, or even read the same messages multiple times without affecting others. This leads to predictable behavior, easier debugging, and safe concurrency.

Isolating mutable state to specific components provides key advantages:

  • Predictable behavior: When you know exactly where state can change, you can reason about your program’s behavior
  • Safe concurrency: Mutation points are protected with explicit synchronization, preventing data races
  • Easier debugging: Bugs related to unexpected state changes are confined to a small portion of the codebase
  • Simpler refactoring: Changes to mutable state don’t ripple through the entire system

Rust’s module system creates architectural boundaries beyond simple code organization. Modules define clear contracts about what’s public and private, encouraging clean interfaces between components.

Let’s structure our modules to create clear boundaries between the public interface and private implementation:

src/lib.rs
//! Samsa - A simple producer/consumer microservice
// Public API - what users can access
pub use message::{Message, Event};
pub use broker::Broker;
pub use producer::Producer;
pub use consumer::Consumer;
pub use error::{SamsaError, Result};
// Private modules - implementation hidden
mod message;
mod broker;
mod producer;
mod consumer;
mod storage;
mod error;

The lib.rs file acts as a gateway, explicitly choosing which types to expose publicly while keeping implementation modules private. Anyone who depends on this crate (whether as a library dependency in another project or as code within the same workspace) can only access Message, Event, Broker, Producer, and Consumer through the public API. They cannot directly interact with storage internals.

This creates a stable public interface that can remain unchanged even when internal implementation evolves. Users write code against the public API without coupling to implementation details, making the system more maintainable and extensible.

The previous section showed how modules control visibility at the crate level. Now let’s go deeper and demonstrate interface-based design by creating a trait that hides storage implementation details:

src/storage/mod.rs
use crate::{Event, Result};
pub trait StorageBackend: Send + Sync {
fn append(&mut self, topic: String, event: Event) -> Result<()>;
fn fetch(&self, topic: &str, from_offset: u64, max_events: usize) -> Result<Vec<Event>>;
}
// Factory hides concrete implementation
pub fn create_storage() -> Box<dyn StorageBackend> {
Box::new(memory::MemoryStorage::new())
}
// Private implementation
mod memory;

The StorageBackend trait defines a clean contract for storage operations, while the factory function completely hides the concrete implementation. External code can only interact through the trait interface. They never see MemoryStorage directly.

This design allows us to swap storage implementations (memory, file, database) without changing any code that uses the storage. The trait creates a stable boundary that protects against implementation changes while enabling extensibility.

Note that the returned Box<dyn StorageBackend> is Send and Sync by default, meaning it is designed for multi-threaded use. The broker wraps it in Arc<Mutex<T>> to provide thread-safe access; the storage itself does not need to be thread-safe because the mutex serializes all access.

Module-based architecture provides the following benefits:

  • Clear boundaries: Each module has defined responsibility
  • Encapsulation: Implementation details are hidden
  • Testability: Modules can be tested independently
  • Extensibility: New implementations can be added without breaking changes

By using traits to model behavior, keeping public APIs minimal, and leveraging visibility modifiers like pub(super) to control access precisely, we create stable, flexible, and easy-to-evolve architectures.

In a production environment, you might use an existing message broker library (such as the ZeroMQ bindings in the zmq crate or the rdkafka crate for Apache Kafka). The value of building our own lies in understanding the architectural principles that all such systems share.

The final principle is designing data structures that minimize borrowing conflicts. Large, monolithic structures create problems because you can’t borrow different parts independently.

Let’s see what happens when we try to pack too much into a single structure:

// Bad: Heavy structure creates borrowing conflicts
pub struct HeavyBroker {
messages: HashMap<String, Vec<Event>>,
metrics: HashMap<String, u64>,
configs: HashMap<String, Config>,
}

This structure creates borrowing conflicts because Rust treats the entire struct as one borrowing unit. If you tried to write a method like fn publish_and_record(&mut self) that calls self.messages.insert(...) and self.metrics.insert(...) it would work because both go through the same &mut self. But you cannot pass &mut self.messages to one function and &mut self.metrics to another in the same scope, because Rust sees both as borrowing from the same struct. You can’t simultaneously borrow messages and metrics because they’re part of the same struct, even though they’re logically independent.

Operations that should be independent (recording metrics and fetching messages) become impossible or require complex workarounds. The code either becomes overly complicated with workarounds or suffers from performance bottlenecks.

Now let’s fix the borrowing conflicts by separating data based on how it’s accessed:

use std::sync::RwLock;
pub struct LightweightBroker {
storage: Arc<Mutex<Storage>>,
metrics: Arc<Metrics>,
configs: Arc<RwLock<Configs>>,
}
// Separate components can be accessed independently
impl LightweightBroker {
pub fn publish_and_record(&self, message: Message) -> Result<u64> {
// These happen independently
let offset = self.storage.lock().unwrap().append(message.topic.clone(), Event::new(message.clone(), 0))?;
self.metrics.record_message(message.value.len());
Ok(0) // Simplified for illustration
}
}

By wrapping each logical component in its own Arc, we can access them independently. The publish_and_record method can simultaneously lock storage and update metrics without borrowing conflicts because they’re separate objects.

Each component has its own synchronization primitive and can be accessed independently. Mutex provides exclusive access: only one thread can hold the lock at a time, whether reading or writing. RwLock allows multiple simultaneous readers or one exclusive writer, making it a better choice for data that is read frequently but written rarely (like configuration). We use Mutex for storage (frequent writes) and RwLock for configs (frequent reads, rare writes).

Not all data can be freely shared between components. Rust’s borrow checker requires that references have a well-defined lifetime: the compiler must be able to prove that the referenced data lives long enough. When lifetimes become complex (crossing thread boundaries, for example), cloning may be the simplest solution. However, within a single thread and a well-defined scope, we can use references to avoid copying data entirely. Because we’ve designed Samsa with clear, downward data flow, we know exactly how long messages live and who owns them. Let’s take advantage of that to create lightweight views:

pub struct MessageView<'a> {
topic: &'a str,
value: &'a [u8],
timestamp: Instant,
}
impl Message {
pub fn as_view(&self) -> MessageView<'_> {
MessageView {
topic: &self.topic,
value: &self.value,
timestamp: self.timestamp,
}
}
}

The MessageView<'_> return type uses the anonymous lifetime '_, which tells the compiler to infer the lifetime from context. In this case, it infers that the view borrows from &self, so the MessageView cannot outlive the Message it references.

MessageView provides read-only access to message data without cloning. The lifetime parameter 'a ensures the view cannot outlive the original message, preventing dangling pointer issues while avoiding allocation costs.

Views eliminate unnecessary memory allocations when components only need to read data. Consumers can process messages without copying large payloads, improving performance while maintaining memory safety through Rust’s lifetime system.

Designing with minimal, focused data structures provides the following benefits:

  • Fewer borrowing conflicts: Small, independent components can be accessed simultaneously
  • Better performance: Zero-copy views and Arc-based sharing avoid expensive cloning
  • Flexible composition: Lightweight components can be combined in different ways for different use cases
  • Clearer ownership: When each component owns only what it needs, ownership semantics are obvious

In this chapter, we explored four architectural principles that Rust enforces through its ownership system:

  • Data flows downward: Unidirectional flow prevents circular dependencies and makes systems easier to understand. Our Samsa system flows clearly: Producer → Broker → Consumer.
  • Mutability stays contained: Isolating mutable state makes programs predictable. We contained all mutation within the broker’s controlled interfaces.
  • Modules become interfaces: Rust’s module system creates architectural boundaries. We used traits and visibility modifiers to hide implementation details.
  • Pack lightly: Thoughtful data structure design eliminates borrowing conflicts. We split concerns into separate components that can be accessed independently.

Figure 9.2 shows how these four principles map onto Samsa’s architecture. Each component embodies one or more of the principles we explored in this chapter.

[figure outside: Figure 9.2]

Figure 9.2: Samsa system architecture

It is tempting to think of these as Rust-specific restrictions, but that is a shallow reading. These are architectural best practices that improve code quality in any language. Rust simply enforces them at compile time, preventing the architectural decay that creeps into long-lived projects.

The four principles we’ve established here mirror the design of production message brokers such as Apache Kafka and RabbitMQ. Our synchronous, in-memory implementation keeps the focus on architectural patterns; a production system would add asynchronous input/output (using Tokio or similar runtimes), persistent storage backends, and network communication via channels or message-passing primitives.

Our foundation is now ready for the advanced patterns in the next chapters. In the next chapter, we’ll leverage Rust’s type system to add compile-time guarantees about topic subscriptions, message schemas, and connection states.