Saga Pattern Implementation in TypeScript
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
- ✓Saga Pattern runs in O(n) time and O(n) space, in TypeScript as in every other language.
- ✓Same runtime as JavaScript, so the value is in the types: a discriminated union for step outcomes, a branded string for idempotency keys so a raw string cannot be passed by accident, and a tuple type over the step list so the compensation stack is checked against the steps that produced it.
- ✓Model the saga state as a discriminated union on a status field and switch exhaustively with a never default, so adding a step is a compile error everywhere it matters.
- ✓The TypeScript trap: Types are erased, so nothing you write here survives to runtime, and one assignability rule turns that into lost money: a function returning Promise<void> is assignable to a parameter typed () => void.
- ✓Zero runtime cost, and zero runtime protection. The cost that is real is compile time: encoding a long step list as a recursive conditional type over a tuple can push tsc into error 2589, type instantiation is excessively deep, and slows editor feedback badly.
What Saga Pattern actually is
Saga Pattern in TypeScript: what you actually reach for
TypeScript implementation
type Key = string & { readonly __key: unique symbol };
const key = (id: string, step: string) => `${id}:${step}` as Key;
// () => void would silently accept an async fn and DROP the promise
type Compensation = { step: string; run: (k: Key) => Promise<void> };
type SagaState =
| { v: 1; status: 'charged'; chargeId: string }
| { v: 1; status: 'reserved'; chargeId: string; holdId: string }
| { v: 1; status: 'done' | 'compensated' };
export async function placeOrder(orderId: string, cents: number): Promise<string> {
const undo: Compensation[] = [];
try {
const charge = await payments.charge(key(orderId, 'pay'), cents);
undo.push({ step: 'pay', run: (k) => payments.refund(charge.id, k) });
const hold = await stock.reserve(key(orderId, 'hold'));
undo.push({ step: 'hold', run: (k) => stock.release(hold.id, k) });
await shipping.book(key(orderId, 'ship'));
return charge.id;
} catch (e) {
for (const c of [...undo].reverse()) {
await c.run(key(orderId, `undo-${c.step}`));
}
throw e;
}
}
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 TypeScript-specific trap
Performance in TypeScript, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which TypeScript type or library should I use for Saga Pattern?
Same runtime as JavaScript, so the value is in the types: a discriminated union for step outcomes, a branded string for idempotency keys so a raw string cannot be passed by accident, and a tuple type over the step list so the compensation stack is checked against the steps that produced it. Use satisfies on the step table to keep literal types without widening, and a versioned union for the persisted saga record. Because JSON.parse returns any, the rehydration boundary needs a real runtime validator such as zod; the interface alone checks nothing there.
What is the most common TypeScript mistake when implementing Saga Pattern?
Types are erased, so nothing you write here survives to runtime, and one assignability rule turns that into lost money: a function returning Promise<void> is assignable to a parameter typed () => void. Declare your compensation registry as Array<() => void> and every async compensation type-checks perfectly, is called without await, and the process moves on or exits before the refund is sent. The second erasure trap is rehydration after a deploy: the row written by the previous version parses cleanly and is cast to the new SagaState, so a step that no longer exists is replayed. Type compensations as Promise-returning and validate the persisted record at the boundary.
How does Saga Pattern actually perform in TypeScript?
Zero runtime cost, and zero runtime protection. The cost that is real is compile time: encoding a long step list as a recursive conditional type over a tuple can push tsc into error 2589, type instantiation is excessively deep, and slows editor feedback badly. Keep step tuples flat, prefer a union of step names over recursive tuple arithmetic, and use satisfies rather than a generic wrapper function whose inference has to be re-run for every saga. Runtime characteristics are exactly the JavaScript ones. Time complexity is O(n) 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 trialIf you are a student, see what GitHub Copilot offers students for free 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.