Leanpub Header

Skip to main content

Layerd FP in Scala

Clean Architecture, Hexagonal and Onion with Scala 3 and ZIO

Clean, Hexagonal, Onion—one dependency rule, three names. Walk a runnable multi-module SaaS billing service in Scala 3 and ZIO: a pure domain ring, ports and use cases in the middle, PostgreSQL + Flyway + JDBC and a thin HTTP shell on the outside—with full source in the PDF, not truncated snippets. See how ZLayer at the composition root keeps one repository for the whole graph, how webhook idempotency stays on the right side of the boundary, and how munit and zio-test (plus optional Docker) prove the architecture you intend to defend in code review.

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

Clean Architecture, hexagonal (ports and adapters), and the onion model are one family of ideas: dependencies point inward, boundaries stay explicit, and the core stays testable while technology churn stays at the edges. This book treats them that way—decision-grade material for experienced Scala developers, tech leads, and architects who already ship services and want the dependency rule enforced in real modules, not only on diagrams.

The worked example is SaaS billing: plans, subscriptions, cancellation, plan changes, payment notify, and idempotent webhooks. The domain is a functional core (opaque identifiers, pure SubscriptionRules, DomainError) with no ZIO in production domain code. The application ring defines outbound ports, ApplicationError, and use-case services (for example subscribe and webhook handling) in ZIO. Adapters supply in-memory stores, PostgreSQL with Flyway migrations and JDBC, JDK HttpServer, Circe JSON, and an outbound HTTP payment gateway—then the composition root (AppLayers, Main) wires ZLayer so one repository instance serves the whole graph.

The manuscript mirrors a multi-module sbt companion repository: Chapters 3–7 print complete, line-faithful production sources in reading order (no elided bodies in repository code—only Chapter 11 uses labelled wrong snippets on purpose). You get guided reading (source-order commentary), placement in Clean/Hex/Onion, production tension (retries, clocks, bad HTTP), and master synthesis sections that tie each chapter to review and shipping concerns. Later chapters cover reliability (what the code proves and what it does not), a testing strategy (munit for pure domain, zio-test for effects, optional Docker integration tests), compile-time module boundaries, anti-patterns and fixes, and a summary linking vertical slices to sibling topics (event sourcing, saga).

Audience: Scala 3 (given, enums, opaque types), basic sbt, and algebraic effects / ZIO at least in outline; working SQL and HTTP. Not a Stripe or PCI hardening guide—the payment paths are architecturally realistic but minimal so boundaries remain visible.

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 · Scope, audience, and how to read this book
    1. 1.1 Audience and prerequisites
    2. 1.2 Companion repository and accuracy contract
    3. 1.3 How to run and build the PDF
    4. 1.4 Environment variables (reference)
    5. 1.5 Manuscript chapters vs full outline
    6. 1.6 Project constitution (summary)
    7. 1.7 How to read code listings (convention)
    8. 1.8 Line fidelity: what “the whole code” means
    9. 1.9 How explanations are layered (master-to-master rubric)
    10. 1.10 End-to-end architecture in one breath (before you open src)
    11. 1.11 Proof obligation
  2. Chapter 2 · One family: Clean, Hexagonal, Onion — professional unification
    1. 2.1 One rule, three drawings
    2. 2.2 Driving vs driven in this repo
    3. 2.3 Where ideas live in the repo (compile-time map)
    4. 2.4 Dependency flow (one direction)
    5. 2.5 Ports as algebraic boundaries (why traits, why ZIO)
    6. 2.6 Domain vs application errors (separation of concerns)
    7. 2.7 When this architecture is too much (honest cost)
    8. 2.8 Review checklist (architecture pass)
    9. 2.9 Reading order in this book
  3. Chapter 3 · Domain module: full source, guided line-by-line
    1. 3.0 Why the domain stays effect-free
    2. 3.1 Opaque identifiers — 3.1.1 Guided reading (line-faithful)
    3. 3.2 Model: plan, subscription, status — 3.2.1 Guided reading
    4. 3.3 Domain errors (ADT) — 3.3.1 Guided reading
    5. 3.4 Subscription rules: pure functions — 3.4.1 Guided reading
    6. 3.5 Tests without ZIO: munit — 3.5.1 Guided reading
    7. 3.6 Chapter boundary: where ZIO enters
  4. Chapter 4 · Application layer: ports, errors, use cases
    1. 4.0 Reading order and commentary model
    2. 4.1 Application errors
    3. 4.2 Outbound ports
    4. 4.3 Use cases — Guided reading — SubscribeService (faithful to the for comprehension)
    5. 4.4 Façades: BillingUseCases and BillingHttpApp
    6. 4.5 In-memory adapters (early vertical slice)
    7. 4.6 System clock and random IDs (runtime defaults)
    8. 4.7 Master architect’s synthesis — the application ring as a system
      1. 4.7.1 Error algebra as the contract between rings
      2. 4.7.2 Ports as the stable surface under churn
      3. 4.7.3 Use-case orchestration: SubscribeService as the template
      4. 4.7.4 BillingUseCases and the single repository instance
      5. 4.7.5 BillingHttpApp vs BillingUseCases
      6. 4.7.6 In-memory adapters as proof objects
      7. 4.7.7 What you should defend in code review
  5. Chapter 5 · PostgreSQL, Flyway, JDBC adapters
    1. 5.1 Flyway migrations
    2. 5.2 Migrator and datasource
    3. 5.3 PostgresSubscriptionRepository
    4. 5.4 PostgresProcessedWebhookStore
    5. 5.5 Wiring recap (Chapter 7)
    6. 5.6 Guided reading — SQL and idempotency schema
    7. 5.7 Guided reading — DbMigrator and JDBC repositories
    8. 5.8 Master architect’s synthesis — persistence as a replaceable side
  6. Chapter 6 · Driving adapter: JSON, HTTP mapping, JDK server
    1. 6.1 JSON helpers (Circe)
    2. 6.2 Application errors to HTTP
    3. 6.3 Outbound HTTP payment notify
    4. 6.4 BillingJdkHttpServer (full)
    5. 6.5 Endpoint summary
    6. 6.6 Guided reading — JSON boundary and HTTP semantics
    7. 6.7 Master architect’s synthesis — the driving adapter as a thin membrane
  7. Chapter 7 · Composition root: AppLayers and Main
    1. 7.1 AppLayers (full)
    2. 7.2 Main (full)
    3. 7.3 Decision table
    4. 7.4 Guided reading — ZLayer algebra in AppLayers
    5. 7.5 Master architect’s synthesis — the composition root owns all sins
  8. Chapter 8 · Professional reliability: what this codebase proves — and what it does not
    1. 8.1 What the reference implementation demonstrates well
    2. 8.2 Current webhook semantics (read before copying)
    3. 8.3 Outbound POST .../notify
    4. 8.4 Transactions and consistency
    5. 8.5 Review checklist (before you ship billing for real)
    6. 8.6 How to extend this book
    7. 8.7 Related material in this workspace
    8. 8.8 Guided walk-through — payment webhook path (every layer)
    9. 8.9 Master synthesis — reliability is a property of the whole graph
  9. Chapter 9 · Testing strategy: munit, zio-test, and opt-in Docker
    1. 9.1 Layer matrix
    2. 9.2 Test doubles: fixed clock and sequential UUIDs
    3. 9.3 BillingUseCasesSpec (vertical slice in memory)
    4. 9.4 PaymentWebhookServiceSpec (idempotency)
    5. 9.5 HttpPaymentGatewaySpec (embedded notify server)
    6. 9.6 BillingJdkHttpServerSpec (GET + POST)
    7. 9.7 PostgresBillingITSpec (opt-in Docker)
    8. 9.8 Master architect’s synthesis — tests prove the boundaries
  10. Chapter 10 · sbt modules and compile-time boundaries
    1. 10.1 Root build.sbt (full)
    2. 10.2 Dependency graph (compile time)
    3. 10.3 Forked tests and UTC
    4. 10.4 When to split modules further
    5. 10.5 Master architect’s synthesis — the compiler as gatekeeper
  11. Chapter 11 · Dependency violations: anti-patterns and fixes
    1. 11.1 Domain that imports infrastructure
    2. 11.2 Use case that builds JSON or status codes
    3. 11.3 Three different Ref repositories in one runtime
    4. 11.4 God ZLayer in every test
    5. 11.5 Webhook handler that mutates before idempotency
    6. 11.6 Code review checklist (architecture)
    7. 11.7 Master architect’s synthesis — anti-patterns are compressed experience
  12. Chapter 12 · Summary: layers, vertical slices, and sibling architectures
    1. 12.1 What you have in one stack
    2. 12.2 Vertical slice vs layers (when they diverge)
    3. 12.3 Event sourcing and saga (sibling books)
    4. 12.4 Closing thesis
    5. 12.5 Master architect’s closing — what “done” means for this book
  13. Appendix E · Where the reference code appears in 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