O'Reilly logo

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Mastering Akka

Book Description

Master the art of creating scalable, concurrent, and reactive applications using Akka

About This Book

  • This book will help you cure anemic models with domain-driven design
  • We cover major Akka programming concepts such as concurrency, scalability, and reactivity
  • You will learn concepts like Event Sourcing and CQRS via Akka Persistence, Akka Streams, Akka Http as well as Akka Clustering

Who This Book Is For

If you want to use the Lightbend platform to create highly performant reactive applications, then this book is for you. If you are a Scala developer looking for techniques to use all features of the new Akka release and want to incorporate these solutions in your current or new projects, then this book is for you. Expert Java developers who want to build scalable, concurrent, and reactive application will find this book helpful.

What You Will Learn

  • Use Akka actors to enable parallel execution
  • Build out domain-driven design based components like entities and aggregates
  • Respond to command requests on that aggregate root that affect the internal state
  • Leverage Akka Persistence, protobuf and Cassandra to save the persistent state of you entities
  • Build out complex processing graphs with the Graph Builder DSL
  • Understand the dynamic push/pull nature of backpressure handling within Akka Streams
  • Route HTTP requests to an actor and return a response
  • Deploy actor instances across a set of nodes via ConductR for high availability

In Detail

For a programmer, writing multi-threaded applications is critical as it is important to break large tasks into smaller ones and run them simultaneously. Akka is a distributed computing toolkit that uses the abstraction of the Actor model, enabling developers to build correct, concurrent, and distributed applications using Java and Scala with ease.

The book begins with a quick introduction that simplifies concurrent programming with actors. We then proceed to master all aspects of domain-driven design. We’ll teach you how to scale out with Akka Remoting/Clustering. Finally, we introduce Conductr as a means to deploy to and manage microservices across a cluster.

Style and approach

This comprehensive, fast-paced guide is packed with several real-world use cases that will help you understand concepts, issues, and resolutions while using Akka to create highly performant, scalable, and concurrency-proof reactive applications.

Downloading the example code for this book. You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the code file.

Table of Contents

  1. Mastering Akka
    1. Mastering Akka
    2. Credits
    3. About the Author
    4. Acknowledgments
    5. About the Reviewer
    6. www.PacktPub.com
      1. Why subscribe?
    7. Preface
      1. What this book covers
      2. What you need for this book
      3. Who this book is for
      4. Conventions
      5. Reader feedback
      6. Customer support
        1. Downloading the example code
        2. Downloading the color images of this book
        3. Errata
        4. Piracy
        5. Questions
    8. 1. Building a Better Reactive App
      1. Understanding the initial example app
      2. Working with the example application
        1. Setting up Docker
          1. Adding the boot2docker hosts entry
        2. Understanding the bookstore Postgres schema
        3. Running bash scripts on Windows
        4. Starting up the example application
        5. Interacting with the example application endpoints
          1. Installing httpie on Mac OS X
          2. Installing httpie on Windows
          3. Interacting with the user endpoint
          4. Interacting with the Book endpoint
          5. Interacting with the Order endpoint
      3. So what's wrong with this application?
        1. Understanding the meanings of scalability
        2. The scalability cube
          1. X axis scaling
          2. Microservices and Y axis scaling
          3. Z axis scaling
          4. Monolith versus microservices
        3. Scale issues with our monolith
          1. Issues with the size of deployments
          2. Supporting different runtime characteristics of services
          3. The pain of a shared domain model
        4. Issues with our relational database usage
          1. Sharing the same schema across all services
          2. Fixing a single point of failure
          3. Avoiding cross-domain transactions
          4. Understanding the CAP theorem
          5. Cassandra to the rescue
        5. Assessing the application's domain model
        6. Recognizing poorly written actors
        7. Replacing our HTTP libraries
      4. Summary
    9. 2. Simplifying Concurrent Programming with Actors
      1. Understanding the actor model's origin
      2. Differentiating concurrency and parallelism
        1. Defining concurrency in computing
        2. Defining parallelism
        3. The dangers of concurrent programming
      3. Using Akka actors for safe concurrency
        1. Concurrent programming with actors
        2. Achieving parallelism with Akka actors and routers
      4. A word on dispatchers in Akka
        1. Dispatchers and executors
        2. Dispatcher types in Akka
          1. Dispatcher
          2. PinnedDispatcher
          3. BalancingDispatcher
          4. CallingThreadDispatcher
        3. Configuring a dispatcher for your actors
      5. Mailbox types in Akka
        1. Unbounded mailboxes
        2. Bounded mailboxes
        3. Configuring mailboxes for your actors
      6. Refactoring a bad actor to FSM
        1. Modeling the new process flow
        2. Coding the new order process flow
          1. Defining state and data representations
          2. Implementing the idle state handling
          3. Implementing the ResolvingDependencies state handling
          4. Implementing the LookingUpEntities state handling
          5. Implementing the ChargingCard state handling
          6. Implementing the WritingEntity state handling
          7. Handling unhandled events
          8. Summing up the refactor
      7. Testing your Akka actors
        1. Understanding the testing pyramid
          1. Unit testing
          2. Integration testing
          3. Acceptance testing
        2. Unit testing Akka actors
          1. The CallingThreadDispatcher
          2. Using TestActorRefs
          3. Using ImplicitSender
          4. Using TestProbes
        3. Testing the SalesOrderProcessor actor
        4. Testing homework
      8. Summary
    10. 3. Curing Anemic Models with Domain-Driven Design
      1. What is DDD?
        1. Knowing where the domain layer fits
        2. Understanding strategic DDD
          1. Ubiquitous language
          2. Bounded context
          3. Continuous integration
          4. Context map
        3. Patterns of intercommunication in strategic DDD
          1. Published language
          2. Open host service
          3. Shared kernel
          4. Customer/supplier
          5. Conformist
          6. Anticorruption layer
          7. Visualizing the spectrum of cooperation
          8. Visualizing the relationships in strategic DDD
        4. Building blocks of DDD
          1. Entity
          2. Value object
          3. Aggregate
          4. Domain event
          5. Service
          6. Repository
          7. Factory
      2. Identifying anemic vs rich models
      3. Designing our DDD refactor
        1. The bookstore context map
        2. Modelling DDD with actors
          1. Understanding the vocabulary of a component
          2. Difficulties of DDD and actors
        3. Remodeling the user management context
        4. Remodeling the inventory management context
        5. Remodeling the credit processing context
        6. Remodeling the sales order processing context
      4. Understanding the refactored bookstore code
        1. The EntityActor abstract class
        2. The EntityAggregate abstract class
        3. The Book and InventoryClerk actors
        4. Looking up a single Book
          1. Looking up multiple books
          2. Making a persistence action on a book
      5. Fixing the transaction in the order creation process
      6. Improvements needed for the refactor
      7. Refactoring homework
      8. Summary
    11. 4. Making History with Event Sourcing
      1. Event sourcing primer
        1. The pros of event sourcing
          1. High performance
          2. Avoidance of Object-relational mapping
          3. Full audit trail
          4. Enabler for system/context separation
          5. No atomic concerns
          6. A natural fit with DDD
        2. The cons of event sourcing
          1. Querying
          2. Performance with long lived entities
          3. Versioning concerns
          4. It's just different
        3. Bookstore-specific example of event sourcing
      2. Akka Persistence for event sourcing
        1. The PersistentActor trait
          1. Persistent actor state handling
          2. The persistenceId method
          3. Taking snapshots for faster recovery
          4. Serialization of events and snapshots
        2. The AsyncWriteJournal
        3. The SnapshotStore
      3. Using Cassandra for our persistent store
        1. Installing Cassandra
        2. Configuring Akka Persistence to use Cassandra
      4. Refactoring the inventory management module
        1. The PersistentEntity abstract class
        2. The Aggregate abstract class
        3. The JsonSerializer class
        4. The event sourced Book entity
        5. The refactored InventoryClerk actor
        6. Trying out the new Book entity
          1. Viewing the events in Cassandra
        7. Adding snapshotting to book
        8. Dealing with an evolving schema
          1. Using event adapters
          2. Detaching the domain model from the data model
      5. The refactored sales order processing module
      6. Refactoring homework
      7. Summary
    12. 5. Separating Concerns with CQRS
      1. A brief history of CQRS
      2. CQRS in the event sourced world
      3. Designing our read model implementation
        1. Selecting our read model data store
        2. Projecting events into the read model
        3. Using Persistence Query to build our views
          1. Understanding your journal provider's query capabilities
          2. Setting up a ReadJournal in your code
          3. Obtaining all of the persistenceIds in the system
          4. Getting events by persistenceId
          5. Getting events by tag
      4. Implementing the Book read model
        1. Supporting tagging in ProtobufDatamodelAdapter
        2. Elasticsearch support traits
        3. The ViewBuilder trait
          1. Acknowledging the flaws with the current code
          2. Discussing the code
        4. Building the BookViewBuilder
        5. Building the BookView
        6. Building a resumable projection
          1. Defining the resumable projection framework
          2. Applying ResumableProjection into our code
      5. Refactoring sales order processing
        1. Denormalization in the SalesOrder read model
        2. Using Persistence Query for inventory allocation
      6. Playing around with the new application
      7. Refactoring homework
      8. Closing comments
      9. Summary
    13. 6. Going with the Flow with Akka Streams
      1. Understanding the Reactive Streams API
        1. Back-pressure in action
      2. The Akka Streams API
        1. The building blocks of Akka Streams
        2. Learning the basics of Stream building
        3. Understanding Stream Materialization
        4. Operator fusion within streams
        5. Using buffers to control rate
          1. Internal buffers on async stages
          2. Adding explicit buffers to data flows
        6. Transforming rate within flows
          1. Reducing data flow rates with conflate
          2. Increasing data flow rates with expand
        7. Building processing graphs with the graph builder DSL
          1. Graph building basics
          2. Building a real-world graph example
          3. Working with partial graphs
        8. Handling streaming I/O
          1. Streams and TCP
          2. Framing your streaming I/O handling
      3. Refactoring the view building code
      4. Refactoring homework
      5. Summary
    14. 7. REST Easy with Akka HTTP
      1. Creating RESTful HTTP interfaces
      2. Comparing Akka HTTP to Spray
        1. Akka Streams and back-pressure
        2. Other differences
      3. Creating RESTful interfaces with Akka HTTP
        1. Using the low-level server-side API
          1. Akka Streams in the low-level API
          2. Handling requests with the low-level API
          3. Controlling parallelism within your server
          4. Low-level server example
        2. Using the high-level server-side API
          1. Completing, rejecting, or failing routes
          2. The RequestContext class
          3. Building out a routing tree
          4. Using directives to build your routing tree
          5. Composing directives together
          6. Marshalling and unmarshalling JSON with spray-json
          7. Handling rejections within your routes
          8. Building a custom RejectionHandler
          9. Testing your routes with route TestKit
      4. Invoking RESTful APIs with Akka HTTP
        1. Client-side Akka HTTP and streams
          1. Consuming the response entity
          2. Parsing the response entity as JSON
        2. Understanding the outbound connection models
          1. The connection-level API
          2. The host-level API
          3. The request-level API
      5. Refactoring homework
        1. Inbound HTTP changes
        2. Outbound HTTP changes
      6. Summary
    15. 8. Scaling Out with Akka Remoting/Clustering
      1. Using Akka Remoting
        1. Enabling Akka Remoting in your projects
        2. Interacting with remote actors
        3. Akka Remoting and serialization
          1. Looking up remote actors
          2. Deploying actors to remote systems
          3. Using remote routers
      2. Using Akka Clustering
        1. Core architectural principles of clustering
          1. Dealing with unreachable nodes
          2. Understanding the membership life cycle
        2. Enabling clustering in your projects
        3. Refactoring the remote worker example for clustering
      3. Using clustering in the bookstore application
        1. Using Cluster Sharding in the bookstore application
          1. Basic concepts of Akka Cluster Sharding
          2. Refactoring the code for Cluster Sharding
          3. Proper passivation of sharded entities
          4. Cluster Sharding related homework
        2. Using Cluster Singleton in the bookstore application
          1. Using the Cluster Singleton pattern
          2. Implementing Cluster Singleton for ViewBuilders
          3. Cluster Singleton homework
        3. Playing with the clustered bookstore application
      4. Summary
    16. 9. Managing Deployments with ConductR
      1. An overview of ConductR
      2. Installing and setting up ConductR locally
        1. Installing the ConductR CLI sandbox
        2. Setting up the ConductR sandbox
        3. Setting up sbt-conductr plugin
        4. A quick note about the use of Docker in the sandbox
      3. Using the ConductR CLI
        1. Viewing the ConductR version information
        2. Viewing the deployed bundle information
        3. Viewing service information from your bundles
        4. Viewing access-control lists for bundle services
        5. Loading a bundle into ConductR
        6. Starting a bundle within ConductR
        7. Stopping a bundle within ConductR
        8. Removing a bundle from ConductR
        9. Viewing bundle-related events in ConductR
        10. Viewing your bundle's logs
      4. Preparing your services for ConductR
        1. Bundling your components for deployment
          1. Creating and deploying your bundle
        2. Code requirements for deployment into ConductR
          1. Signalling the application state
          2. Setting up your ActorSystem and HTTP server
          3. Locating other services within the cluster
      5. Refactoring the bookstore for ConductR
        1. Splitting apart the bookstore projects
        2. Common changes to support ConductR
          1. The new Server class
          2. The ServiceConsumer classes
        3. Turning the service modules into ConductR bundles
          1. Setting up an application.conf for each module
          2. Adding bundle keys to our sbt build files
          3. Creating a main class to startup each bundle
        4. Refactoring the sales-order-processing module
          1. Refactoring the SalesOrderCreateValidator
          2. Refactoring SalesOrderViewBuilder
          3. Refactoring the inventory-allocation process
        5. Refactoring the inventory-management module
      6. Building and deploying the bookstore bundles
      7. Testing the bookstore modules in ConductR
      8. Summary
    17. 10. Troubleshooting and Best Practices
      1. Refactoring retrospective
        1. Coding better actors
        2. Using Domain-driven design
        3. Akka Persistence and event sourcing
        4. Akka Persistence Query and CQRS
        5. Akka Streams
        6. Akka HTTP
        7. Akka Remoting and Akka Clustering
        8. Separating the modules via ConductR
      2. Troubleshooting and best practices for actors
        1. Avoid closing over mutable state with Futures
          1. Avoiding closing over the sender
        2. Minimize your use of ActorSelection
        3. Use tell instead of ask
        4. Avoid creating a lot of top-level actors
      3. Troubleshooting and best practices for Akka HTTP
        1. Trouble with the tilde
        2. Building an inbound HTTP request log
        3. Building an outbound HTTP request log
      4. Troubleshooting and best practices for Akka Clustering/Akka Remoting
        1. Prefer using IP addresses over host names in config
        2. Configuring more than one seed node
        3. Disassociated exceptions in the logs can be normal
      5. Further reading
        1. Lagom
        2. Akka Streams cookbook
        3. How to and common patterns
        4. Akka Persistence schema evolution
        5. Other Akka books to consider reading
        6. Domain-driven design by Eric Evans
        7. Martin Fowler on event sourcing
      6. Summary