Arc Swap Config Reload

Reload configuration atomically by swapping an Arc while readers keep lock-free snapshots, with no downtime or partial state.

RustConfig Management

Code

rustsnippet
46 lines
use arc_swap::ArcSwap;
use std::sync::Arc;

#[derive(Debug, Clone, PartialEq)]
struct Config {
    max_connections: usize,
    feature_flag: bool,
}

struct ConfigStore {
    current: ArcSwap<Config>,
}

impl ConfigStore {
    fn new(initial: Config) -> Self {
        Self {
            current: ArcSwap::from_pointee(initial),
        }
    }

    fn load(&self) -> Arc<Config> {
        self.current.load_full()
    }

    fn reload(&self, next: Config) -> Arc<Config> {
        self.current.swap(Arc::new(next))
    }
}

fn main() {
    let store = ConfigStore::new(Config {
        max_connections: 8,
        feature_flag: false,
    });

    let snapshot = store.load();
    let previous = store.reload(Config {
        max_connections: 16,
        feature_flag: true,
    });

    println!("previous: {:?}", previous);
    println!("snapshot: {:?}", snapshot);
    println!("current: {:?}", store.load());
    assert_eq!(store.load().max_connections, 16);
}

How it works

Count the functions new, load, reload and main as the entire surface area of Arc Swap Config Reload.

What to watch for

  • Plan for an install step: arc_swap::ArcSwap is a real dependency, resolved by the package manager.

Using it

Signature: fn new(initial: Config) -> Self

The demo output is labeled (previous:, snapshot:, current:), so every printed line maps back to its originating operation.

The sequence new, load and reload lives in main; running the file triggers it.

Key statements

fn reload(&self, next: Config) -> Arc<Config> {
self.current.swap(Arc::new(next))
}
fn new(initial: Config) -> Self {
Self {
current: ArcSwap::from_pointee(initial),
}
}
fn load(&self) -> Arc<Config> {
self.current.load_full()
}

Interactive Tools for This Topic

FAQ

What does this need from the package registry?
These are real dependencies: `arc_swap::ArcSwap`. Without it the snippet will not load.