Leanpub Header

Skip to main content

Saga Architecture in Scala

Functional Saga Architecture in Scala 3 and ZIO

No distributed transaction spans your whole business process—so you design steps and compensations instead. In Scala 3 and ZIO, build a full order-placement saga from domain types and service algebras to orchestration and event-driven choreography, with tests that prove compensations fire when things break. Then see what it takes to move the same design toward production: outbox, idempotency, persistence, and how to choose between central coordination and decentralized reactions.

Minimum price

$11.99

$19.99

You pay

$19.99

Author earns

$15.99
$
You can also buy this book with 1 book credit. Get book credits with a Reader Membership or an Organization Membership for your team.
PDF
About

About

About the Book

Distributed systems rarely give you one big ACID transaction across services. When a workflow spans inventory, payments, shipping, and notifications, partial failure is normal—and you need a clear way to move forward or undo work with compensating actions. This book teaches saga patterns by building a single, coherent example in Scala 3 and ZIO: an order-placement flow with reserves, charges, shipments, and customer notifications.

You work through complete source files as they appear in the project (the book presents 100% of the code across the chapters), so you always see real traits, types, layers, and tests—not fragments disconnected from a runnable design. Early chapters establish the Scala 3 choices that matter for sagas (opaque types, enums, immutability, service traits) and ZIO as the effect model: typed errors, sequential composition, and how that maps to “run steps, then compensate in reverse order.” ZLayer and ZIO.service show dependencies as values and keep orchestration testable.

The narrative moves from why global transactions and two-phase commit are a poor fit to saga concepts: steps and compensations, orchestration vs choreography, ordering, recovery, and consistency at boundaries. You implement orchestration with an explicit saga step type and runner, then choreography with domain events and reactions—so you can compare the same domain under two coordination styles. Testing is first-class: in-memory interpreters, test doubles, and strategies to assert that compensations run when you expect.

Later chapters bridge simulation to production: swapping interpreters (e.g. HTTP), reliability concerns, outbox/inbox, idempotency, retries, saga state persistence, and operational topics like observability and runbooks. An appendix sketches the same ideas in Cats Effect for readers who prefer that stack; others provide a code index and an ADR template for documenting saga policies.

Audience: Scala developers who already know the basics (e.g. Option, Either, some familiarity with effects) and want a rigorous, code-complete path from saga theory to implementation and operations—not a framework tutorial alone, but architecture with executable Scala.

Bundle

Bundles that include this book

Author

About the Author

Piotr Pruchniewicz

I am a Scala developer by profession and a passionate advocate for Scala, Scala 3, functional programming, and concurrent programming. I am an enthusiast of ZIO, Cats Effect, and AI tools, constantly exploring how these technologies can work together to create robust and scalable solutions.

I consider myself a perpetual learner with an insatiable appetite for knowledge and passion. My curiosity drives me to continuously deepen my understanding of functional programming paradigms, effect systems, and modern software architecture. This book represents not just a compilation of knowledge, but also a journey of discovery and sharing the insights I have gained through years of working with Scala and its rich ecosystem.

Through SCALAPEDIA, I aim to share this passion and knowledge with the Scala community, helping both newcomers and experienced developers discover the full potential of functional programming in Scala.

Contents

Table of Contents

  1. Chapter 1 · What You Need from Scala 3
    1. 1.1 Build configuration
    2. 1.2 Package object
    3. 1.3 First domain type: Order (opaque types, extension methods, case classes)
    4. 1.4 Enums and other domain types (preview)
    5. 1.5 Why these features matter for the saga (summary)
  2. Chapter 2 · Describing Effects with ZIO
    1. 2.1 First algebra: InventoryService (full file)
    2. 2.2 The ZIO type
    3. 2.3 The error channel
    4. 2.4 Building programs with flatMap and for
    5. 2.5 Common operations
    6. 2.6 Referential transparency
    7. 2.7 Effect model and the runtime
    8. 2.8 Error channel and typed failure
    9. 2.9 Sequential composition and short-circuiting (saga perspective)
  3. Chapter 3 · Dependencies as Values (ZLayer, ZIO.service)
    1. 3.1 AppLayers: composing the in-memory environment (full file)
    2. 3.2 Requiring the environment
    3. 3.3 Accessing services with ZIO.service
    4. 3.4 Building the environment with ZLayer
    5. 3.5 Providing the layer at the edge
    6. 3.6 Layer composition and the ++ operator
    7. 3.7 Summary
  4. Chapter 4 · Testing Effects
    1. 4.1 OrderSagaSpec: full test file
    2. 4.2 ZIOSpecDefault and suite/test
    3. 4.3 Providing the environment in tests
    4. 4.4 In-memory interpreters and test doubles
    5. 4.5 Asserting compensations with Ref spies
    6. 4.6 Test strategy: behaviour and compensations
    7. 4.7 Running the tests
  5. Chapter 5 · The Problem: Distributed Workflows Without Global ACID
    1. 5.1 The dream: one big transaction
    2. 5.2 The reality: multiple steps, partial failure
    3. 5.3 Why compensations, not rollback
    4. 5.4 Why not distributed two-phase commit (2PC)?
    5. 5.5 Eventual consistency and visibility windows
    6. 5.6 Failure taxonomy you must design for
    7. 5.7 Consistency contracts per boundary
    8. 5.8 The core requirement for our book project
    9. 5.9 Practical anti-patterns to avoid
    10. 5.10 What comes next
  6. Chapter 6 · Saga Concepts
    1. 6.1 Step and compensate
    2. 6.2 Saga lifecycle as a state machine
    3. 6.3 Orchestration
    4. 6.4 Choreography
    5. 6.5 Order of compensations
    6. 6.6 Forward recovery vs backward recovery
    7. 6.7 Invariants and compensation semantics
    8. 6.8 Command vs event semantics
    9. 6.9 Concurrency and isolation scope
    10. 6.10 What we build
  7. Chapter 7 · Our Running Example: Order Placement
    1. 7.1 The workflow (forward steps)
    2. 7.2 Compensations (reverse order)
    3. 7.3 Domain types (preview)
    4. 7.4 Simulation in this book
  8. Chapter 8 · Domain and Algebras
    1. 8.1 Dependency inversion and algebra design
    2. 8.2 Domain: Reservation (full file)
    3. 8.3 Domain: Payment (full file)
    4. 8.4 Domain: Shipment (full file)
    5. 8.5 Algebra: PaymentService (full file)
    6. 8.6 Algebra: ShippingService (full file)
    7. 8.7 Algebra: NotificationService (full file)
    8. 8.8 Summary
  9. Chapter 9 · In-Memory Interpreters
    1. 9.1 InMemoryInventory (full file)
    2. 9.2 InMemoryPayment (full file)
    3. 9.3 InMemoryShipping (full file)
    4. 9.4 InMemoryNotification (full file)
    5. 9.5 Composing the layers
    6. 9.6 Semantic fidelity of the simulation
    7. 9.7 Ref as a concurrency primitive (under the hood)
    8. 9.8 State transition discipline
    9. 9.9 Idempotency gaps in the current in-memory model
    10. 9.10 Determinism as a pedagogical contract
    11. 9.11 How to evolve these interpreters toward production
    12. 9.12 Quick simulation-vs-production failure matrix
  10. Chapter 10 · The Saga as a Sequence of Steps
    1. 10.1 SagaError (full file)
    2. 10.2 SagaStep (full file)
    3. 10.3 OrderSaga (full file)
    4. 10.4 Why mapError to SagaError?
    5. 10.5 Why AlreadyCompensated?
    6. 10.6 Under the hood: how runOrchestrator runs steps and compensations
    7. 10.7 Formalizing the contract of a SagaStep
    8. 10.8 Error algebra design: domain vs control errors
    9. 10.9 Compensation failure strategy (advanced)
    10. 10.10 Deterministic ordering and ambiguity boundaries
    11. 10.11 Invariants enforced by this design
    12. 10.12 Extension points for production-grade orchestration
    13. 10.13 Formal failure matrix (orchestration)
    14. 10.14 State-transition expectations per matrix row
  11. Chapter 11 · Running the Orchestrator
    1. 11.1 OrchestrationMain (full file)
    2. 11.2 How runOrchestrator works
    3. 11.3 Success and failure paths
    4. 11.4 Runtime execution model in ZIOAppDefault
    5. 11.5 Boundary responsibility: where to decide policy
    6. 11.6 What this sample intentionally does not model
    7. 11.7 Operational interpretation of results
    8. 11.8 Hardening checklist for orchestration main
    9. 11.9 Runtime decision matrix (operator view)
    10. 11.10 Failure matrix consistency check
    11. 11.11 Notification failure policy (make it explicit)
  12. Chapter 12 · Testing the Orchestration Saga
    1. 12.1 Test layout: OrderSagaSpec
    2. 12.2 Test doubles and spies
    3. 12.3 Running the tests
    4. 12.4 Matrix-derived test plan (recommended)
    5. 12.5 Advanced scenarios to add
    6. 12.6 Property-style invariants
  13. Chapter 13 · Events and Reactions
    1. 13.1 OrderEvents (full file)
    2. 13.2 Event semantics
    3. 13.3 Who reacts?
    4. 13.4 No central coordinator
  14. Chapter 14 · Implementing Choreography
    1. 14.1 InMemoryEventBus (full file)
    2. 14.2 OrderChoreography (full file)
    3. 14.3 ChoreographyMain (full file)
    4. 14.4 ChoreographySpec (full file)
    5. 14.5 Event ordering, delivery semantics, and correctness
    6. 14.6 Idempotent handler design
    7. 14.7 Choreography state ownership
    8. 14.8 Failure modes unique to event-driven coordination
    9. 14.9 Observability model for choreography
    10. 14.10 When choreography is truly worth it
    11. 14.11 Choreography failure matrix (event-driven)
    12. 14.12 Transition guards for robust handlers
    13. 14.13 Aligning notification semantics with orchestration
  15. Chapter 15 · Same Domain, Different Coordination
    1. 15.1 Comparison table
    2. 15.2 When to choose orchestration
    3. 15.3 When to choose choreography
    4. 15.4 Decision framework (practical)
    5. 15.5 Hybrid pattern in real systems
    6. 15.6 In this book
  16. Chapter 16 · From Simulation to Production
    1. 16.1 Same algebras, different interpreters
    2. 16.2 “In the book” vs “In production” (summary)
    3. 16.3 HTTP interpreter skeleton (conceptual)
    4. 16.4 Reliability primitives you must add
    5. 16.5 Transactional outbox and inbox patterns
    6. 16.6 Outbox/Inbox execution timeline (step-by-step)
    7. 16.7 Event contract versioning and schema evolution
    8. 16.8 Idempotency and retries
    9. 16.9 Exactly-once myths and practical guarantees
    10. 16.10 Persisting saga state
    11. 16.11 Ordering and concurrency concerns
    12. 16.12 Migration path from this book to production
  17. Chapter 17 · Trade-offs and Operational Concerns
    1. 17.1 Observability
    2. 17.2 Partial failures and consistency
    3. 17.3 Saga persistence
    4. 17.4 SLOs, alerts, and runbooks
    5. 17.5 Handling compensation failures
    6. 17.6 Testing strategy for confidence
    7. 17.7 Governance and boundaries
    8. 17.8 Summary
  18. Appendix A · Same Flow in Cats Effect
    1. A.1 Effect type
    2. A.2 Dependency injection
    3. A.3 Orchestration structure
    4. A.4 Choreography with Cats Effect
    5. A.5 Summary
    6. A.6 Error semantics: F[Either[E, A]] vs EitherT
    7. A.7 Dependency injection styles in Cats Effect
    8. A.8 Cancellation and resource safety notes
  19. Appendix B · Code Index
  20. Appendix C · Where the Code Appears
  21. Appendix D · ADR Template for Saga Policies
    1. D.1 Why use ADRs for Saga decisions
    2. D.2 ADR template (copy/paste)
    3. D.3 Mandatory Saga policy checklist
    4. D.4 Example ADR summary (compact)
    5. D.5 How this appendix maps to this book

The Leanpub 60 Day 100% Happiness Guarantee

Within 60 days of purchase you can get a 100% refund on any Leanpub purchase, in two clicks.

Now, this is technically risky for us, since you'll have the book or course files either way. But we're so confident in our products and services, and in our authors and readers, that we're happy to offer a full money back guarantee for everything we sell.

You can only find out how good something is by trying it, and because of our 100% money back guarantee there's literally no risk to do so!

So, there's no reason not to click the Add to Cart button, is there?

See full terms...

Earn $8 on a $10 Purchase, and $16 on a $20 Purchase

We pay 80% royalties on purchases of $7.99 or more, and 80% royalties minus a 50 cent flat fee on purchases between $0.99 and $7.98. You earn $8 on a $10 sale, and $16 on a $20 sale. So, if we sell 5000 non-refunded copies of your book for $20, you'll earn $80,000.

(Yes, some authors have already earned much more than that on Leanpub.)

In fact, authors have earned over $15 million writing, publishing and selling on Leanpub.

Learn more about writing on Leanpub

Free Updates. DRM Free.

If you buy a Leanpub book, you get free updates for as long as the author updates the book! Many authors use Leanpub to publish their books in-progress, while they are writing them. All readers get free updates, regardless of when they bought the book or how much they paid (including free).

Most Leanpub books are available in PDF (for computers) and EPUB (for phones, tablets and Kindle). The formats that a book includes are shown at the top right corner of this page.

Finally, Leanpub books don't have any DRM copy-protection nonsense, so you can easily read them on any supported device.

Learn more about Leanpub's ebook formats and where to read them

Write and Publish on Leanpub

You can use Leanpub to easily write, publish and sell in-progress and completed ebooks and online courses!

Leanpub is a powerful platform for serious authors, combining a simple, elegant writing and publishing workflow with a store focused on selling in-progress ebooks.

Leanpub is a magical typewriter for authors: just write in plain text, and to publish your ebook, just click a button. (Or, if you are producing your ebook your own way, you can even upload your own PDF and/or EPUB files and then publish with one click!) It really is that easy.

Learn more about writing on Leanpub