Event Sourcing Implementation in JavaScript
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 JavaScript as in every other language.
- ✓The whole fold is Array.prototype.reduce and JSON.parse/JSON.stringify; there is no stdlib schema layer at all, which is the defining fact.
- ✓Events are plain data with a string type field, never class instances, because JSON.stringify drops the prototype and JSON.parse never restores it.
- ✓The JavaScript trap: JSON has one number type and it is a float64, so a cents total, a Twitter-style id, or a stream version past 2^53-1 loses precision on JSON.parse with no error whatsoever.
- ✓V8 keeps reduce fast only while the array is monomorphic: same hidden class, same key insertion order on every event object.
What Event Sourcing actually is
Event Sourcing in JavaScript: what you actually reach for
JavaScript implementation
// Events are plain JSON. JSON.parse restores no prototypes and no Date objects.
const revive = (k, v) => (k === "at" ? new Date(v) : v);
function apply(state, e) {
switch (e.type) {
case "deposited": return { ...state, cents: state.cents + e.cents };
case "withdrawn": return { ...state, cents: state.cents - e.cents };
// unknown tag = the log is ahead of this build; skipping it corrupts state silently
default: throw new Error(`unknown event ${e.type}`);
}
}
// upcasting is just a total function from old shape to current shape
const upcast = (e) => (e.v === 1 ? { ...e, v: 2, currency: "USD" } : e);
async function replay(store, streamId, snapshot) {
let state = snapshot?.state ?? { cents: 0 };
let version = snapshot?.version ?? 0;
for await (const line of store.readFrom(streamId, version)) {
const e = upcast(JSON.parse(line, revive));
state = apply(state, e);
version = e.version; // trust the log's version, never a local counter
}
return { state, version };
}
async function append(store, streamId, expectedVersion, events) {
// must be one compare-and-set in the store; a read-then-write here is the classic race
if (!(await store.appendIfVersion(streamId, expectedVersion, events)))
throw new Error("concurrency conflict");
}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 JavaScript-specific trap
Performance in JavaScript, beyond the O(1) append
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which JavaScript type or library should I use for Event Sourcing?
The whole fold is Array.prototype.reduce and JSON.parse/JSON.stringify; there is no stdlib schema layer at all, which is the defining fact. crypto.randomUUID() gives event ids in Node and in secure browser contexts, structuredClone deep-copies a snapshot without a JSON round-trip, and BigInt is the only exact integer you have once a running total passes Number.MAX_SAFE_INTEGER. Node adds node:fs createReadStream plus node:readline for line-delimited logs. Because nothing validates, the ecosystem standard at the deserialisation boundary is zod, which is what actually makes a tagged union true at runtime.
What is the most common JavaScript mistake when implementing Event Sourcing?
JSON has one number type and it is a float64, so a cents total, a Twitter-style id, or a stream version past 2^53-1 loses precision on JSON.parse with no error whatsoever. The two events that push you over produce a balance that is off by one and stays off. The second is revival: JSON.stringify calls Date.prototype.toJSON and writes an ISO string, but JSON.parse gives you back a string, so state.lastSeen.getTime() throws only on the streams that happen to contain that event. And structuredClone throws DataCloneError only on functions, symbols and unsupported host objects; a class instance never throws, it is copied into a plain object carrying its own enumerable fields with the prototype and every method silently gone, so the snapshot looks correct right up to the state.total.add is not a function on the next fold.
How does Event Sourcing actually perform in JavaScript?
V8 keeps reduce fast only while the array is monomorphic: same hidden class, same key insertion order on every event object. Adding a field to some events, or building them with conditional property assignment, makes the property access megamorphic and deoptimises the loop. Each JSON.parse allocates a fresh object graph, so replay is young-generation churn that scavenges cheaply, while the retained state graph gets promoted and costs real major GC. A 500k-event replay blocks the single-threaded event loop outright: chunk with setImmediate or push it into a worker_thread. 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.