Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Saga Pattern Implementation in TypeScript

19 min readadvanced
Website QA and SEO audits

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

A saga replaces one distributed ACID transaction with a sequence of local transactions, each of which commits immediately and irreversibly. There is no global commit and no global rollback, so the only way back is forward: every step declares a compensating action (refund the charge, release the reservation) that is itself a new business transaction, may fail, may run out of order relative to concurrent readers, and must be safe to retry. That forces idempotency keys per step and per compensation, and it forces a decision about who holds the state machine: an orchestrator that calls services and records its own position, or choreography where each service reacts to an event and nobody knows the whole plan. Intermediate states are visible to everyone, so isolation must be recovered by semantic locks or commutative operations. Languages diverge because the undo stack is a scope-lifetime problem: some have a native LIFO unwind primitive (defer, AsyncExitStack, drop guards), some have structured cancellation that fights compensation, and some push crash-durable resumption entirely into a framework.

Saga Pattern in TypeScript: what you actually reach for

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.

TypeScript implementation

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. Type compensations as () => Promise<void>, never () => void. Reviewers reject as SagaState on parsed JSON, reject enums for step names in favour of a const object with satisfies, and reject any leaking out of the transport layer into the orchestrator.
typescript
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 Free

The TypeScript-specific 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. 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.

Performance in TypeScript, beyond the O(n)

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. The asymptotic cost is the same in every language, O(n) time and O(n) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Saga Pattern between languages.

Real-World Applications

Saga Pattern is used extensively in production software: relational databases, NoSQL systems, ORMs, and data pipelines use this pattern for managing data access and consistency. In TypeScript, check whether the standard library or a well maintained package already provides it before you write your own. Understanding Saga Pattern helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Saga Pattern appears frequently in final rounds at FAANG-level companies and system design interviews. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Saga Pattern over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Saga Pattern to build pattern recognition. In TypeScript, demonstrate proficiency with generics and type guards to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic TypeScript code that is both correct and maintainable.

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).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

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 trial

If you are a student, see what GitHub Copilot offers students for free on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

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.