Event Sourcing Implementation in Rust
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Event Sourcing runs in O(1) append time and O(n) space, in Rust as in every other language.
- ✓The event set is an enum, and match over it is exhaustive by the compiler, so no default arm and no unknown-variant class of bug.
- ✓apply takes &mut self and returns nothing, because a persisted event already happened and cannot be rejected; validation lives in decide(&self, cmd) -> Result<Vec<Event>, DomainError> and the two are reviewed as separate functions.
- ✓The Rust trap: #[serde(untagged)] on an event enum is the trap that costs you the log. Untagged tries each variant in declaration order and takes the first that deserialises, so Withdrawn { cents } and Deposited { cents } decode to whichever is listed first, with no error at all, and every replay after that is confidently wrong.
- ✓No GC, so replay cost is allocation from serde_json building an owned String per text field.
What Event Sourcing actually is
Event Sourcing in Rust: what you actually reach for
Rust implementation
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug)]
#[serde(tag = "type")] // internally tagged. NEVER untagged for a log.
#[non_exhaustive]
pub enum Event {
#[serde(rename = "deposited", alias = "credited")] // alias = free rename of history
Deposited { cents: i64, #[serde(default)] currency: Option<String> },
#[serde(rename = "withdrawn")]
Withdrawn { cents: i64 },
}
#[derive(Default, Debug)]
pub struct Account { pub cents: i64, pub version: u64 }
impl Account {
// infallible on purpose: you cannot reject an event that already happened
fn apply(&mut self, e: &Event) {
match e { // exhaustive; adding a variant is a compile error, not a runtime one
Event::Deposited { cents, .. } => self.cents += cents,
Event::Withdrawn { cents } => self.cents -= cents,
}
self.version += 1;
}
}
// bytes are one mmapped buffer of newline-delimited JSON
pub fn replay(bytes: &[u8], mut acc: Account) -> serde_json::Result<Account> {
for line in bytes.split(|b| *b == b'\n').filter(|l| !l.is_empty()) {
let e: Event = serde_json::from_slice(line)?; // slice, not str: no UTF-8 re-scan
acc.apply(&e);
}
Ok(acc)
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Rust-specific trap
Performance in Rust, beyond the O(1) append
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Rust type or library should I use for Event Sourcing?
The event set is an enum, and match over it is exhaustive by the compiler, so no default arm and no unknown-variant class of bug. serde plus serde_json carry the wire format: #[serde(tag = "type")] makes an internally tagged union, #[serde(rename)] and #[serde(alias)] rename a variant on disk without touching history, and #[serde(default)] lets a field added today decode against every event written before it. Iterator::fold does the replay. Errors are Result with a thiserror enum, never panics. For a compact binary log reach for rmp-serde, not bincode, because bincode is not self-describing.
What is the most common Rust mistake when implementing Event Sourcing?
#[serde(untagged)] on an event enum is the trap that costs you the log. Untagged tries each variant in declaration order and takes the first that deserialises, so Withdrawn { cents } and Deposited { cents } decode to whichever is listed first, with no error at all, and every replay after that is confidently wrong. Use tag. The second is field addition: adding cents: i64 to an existing variant makes every historical event fail with missing field cents, because Option<T> is implicitly defaulted but a plain integer is not, so a field addition needs #[serde(default)] to be backward-compatible. And #[serde(deny_unknown_fields)] on an event guarantees a rollback cannot read forward-written data.
How does Event Sourcing actually perform in Rust?
No GC, so replay cost is allocation from serde_json building an owned String per text field. Deserialise from a single mmapped buffer with from_slice and borrow those fields with #[serde(borrow)] as &str and the string allocations disappear entirely. Watch enum size: a Vec<Event> pays the largest variant plus a discriminant for every element, so one variant with a fat payload doubles the memory traffic of the whole fold; Box that variant's body. Iterating a contiguous Vec is prefetcher-friendly and LLVM hoists the bounds checks out of the loop. Time complexity is O(1) append and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialStudying for this? GitHub Copilot free tiers and academic plans are laid out on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.