Arc Swap Config Reload
Reload configuration atomically by swapping an Arc while readers keep lock-free snapshots, with no downtime or partial state.
Code
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);
}Report a problem with this exampleOpens a pre-filled issue on GitHub.