Building Stateful Microservices With Akka

Yaroslav Tkachenko
Yaroslav TkachenkoPrincipal Software Engineer at Goldsky
Building Stateful Microservices With Akka
Yaroslav Tkachenko
Senior Software Engineer at Demonware (Activision)
1 / 40
Java, Scala, Python, Node
Microservices
Event-driven Systems
Distributed Systems
DevOps
... and more
About me
Yaroslav (Slava) Tkachenko, Vancouver, Canada
Demonware (Activision), 2017
Senior Software Engineer [Data Pipeline]
Mobify, 2016 - 2017
Senior Software Engineer, Lead [Platform]
Bench Accounting, 2011 - 2016
Director of Engineering [Platform]
Engineering Lead
Software Engineer
Freelance, 2007 - 2011
Web Developer
2 / 40
https://sap1ens.com/slides/stateful-services/
3 / 40
Agenda
Microservices: stateless vs stateful
Actor systems
Akka
Akka Cluster and Persistence
Real-world applications
4 / 40
Microservices: stateless vs stateful
5 / 40
Microservices: stateless vs stateful
Stateless application: application that doesn't keep any state in memory / runtime, but uses
external services instead.
External service: database, cache, API, etc.
Examples: most of the web apps are stateless or designed to be stateless (Spring, Django, Rails,
Express, etc.).
Stateful application: application that keeps internal state in memory / runtime, instead of relying
on external services.
Examples: actors can be stateful, so Akka and other actor-based systems (Erlang/OTP, Orleans)
can be stateful. But it's also possible to create stateful applications in Node.js or Python, for
example.
6 / 40
Microservices: stateless
7 / 40
Microservices: stateless
Benefits:
Simple development & deployment
Simple to scale out -> just add more nodes
Biggest challenges:
Low latency -> can use caching, but not when strong consistency is needed
Concurrent modifications -> conflict resolution with optimistic / pessimistic locking
8 / 40
Microservices: stateful
9 / 40
Microservices: stateful
10 / 40
Microservices: stateful
Benefits:
Data locality -> low latency, fast processing
Sticky consistency -> "simple" and "cheap" consistency without using consensus protocols
Biggest challenges:
High availability
Scaling out
11 / 40
Actor systems
12 / 40
Actor systems
An actor is a computational entity that, in response to a message it receives, can concurrently:
send a finite number of messages to other actors;
create a finite number of new actors;
designate the behavior to be used for the next message it receives.
There is no assumed sequence to the above actions and they could be carried out in parallel.
Every actor has:
A mailbox
A supervisor
Some state [optionally]
13 / 40
Rachel Alex
Actor systems - Examples
 
 
 
 
 
Fred
14 / 40
Actor systems - Examples
Akka Concurrency by Derek Wyatt, Artima
15 / 40
Actor systems - Examples
Akka Concurrency by Derek Wyatt, Artima
16 / 40
Actor systems - Examples
Akka Concurrency by Derek Wyatt, Artima
17 / 40
Akka
18 / 40
Akka
Akka is an open-source toolkit and runtime simplifying the construction of concurrent and
distributed applications on the JVM.
Akka supports multiple programming models for concurrency, but it emphasizes actor-based
concurrency, with inspiration drawn from Erlang.
19 / 40
Akka - Actors
case class Greeting(who: String)
class GreetingActor extends Actor with ActorLogging {
def receive = {
case Greeting(who) => log.info("Hello " + who)
}
}
val system = ActorSystem("MySystem")
val greeter = system.actorOf(Props[GreetingActor], name = "greeter")
greeter ! Greeting("Charlie Parker")
 
Messages are handled one by one
Immutability of messages
20 / 40
Akka - Communication
class HelloActor extends Actor with ActorLogging {
def receive = {
case who => sender() ! "Hello, " + who
}
}
object ConversationActor {
def props(fellowActor: ActorRef): Props = Props(classOf[ConversationActor], fellowActor)
}
class ConversationActor(fellowActor: ActorRef) extends Actor with ActorLogging {
def receive = {
case "start" => fellowActor ! "it's me!"
case message => log.info(message)
}
}
val system = ActorSystem("MySystem")
val helloActor = system.actorOf(Props[HelloActor])
val conversationActor = ConversationActor.props(helloActor)
conversationActor ! "start"
21 / 40
Actor systems and Akka - Why?
So, why actors?
Simple concurrency
Clean asynchronous programming model
Great fit for event-driven systems
Resilience
Scalability
22 / 40
Akka Persistence
23 / 40
Akka Persistence - Overview
24 / 40
Akka Persistence - Overview
Event Sourcing
Persistent Actor
Journal
Snapshot
Has plugins for JDBC (MySQL, Postgres, ...), MongoDB, Cassandra, Kafka, Redis and more.
25 / 40
Akka Persistence - Example
case class Cmd(data: String)
case class Evt(data: String)
case class ExampleState(events: List[String] = Nil) {
def updated(evt: Evt): ExampleState = copy(evt.data :: events)
override def toString: String = events.reverse.toString
}
class ExamplePersistentActor extends PersistentActor {
override def persistenceId = "sample-id-1"
var state = ExampleState()
def updateState(event: Evt): Unit =
state = state.updated(event)
val receiveRecover: Receive = {
case evt: Evt => updateState(evt)
case SnapshotOffer(_, snapshot: ExampleState) => state = snapshot
}
val receiveCommand: Receive = {
case Cmd(data) => persist(Evt(data))(updateState)
case "snap" => saveSnapshot(state)
case "print" => println(state)
}
}
26 / 40
Akka Cluster
27 / 40
Cluster
Node
Gossip protocol
Failure Detector
Akka Cluster - Overview
28 / 40
Akka Cluster - Sharding
Features:
One of the most powerful Akka features!
Allows to route messages across nodes in a cluster using a sharding function (actually two)
You don't need to know the physical location of an actor - cluster will forward message to a
remote node if needed
Uses Akka Persistence internally (or brand-new Distributed Data)
Concepts:
Coordinator
Shard Region
Shard
Entity
Entities (actors) are "activated" by receiving a first message and can be "passivated" using
context.setReceiveTimeout.
29 / 40
Akka Cluster - Sharding
Counter interface:
case object Increment
case object Decrement
final case class Get(counterId: Long)
final case class EntityEnvelope(id: Long, payload: Any)
case object Stop
final case class CounterChanged(delta: Int)
30 / 40
Akka Cluster - Sharding
Counter implementation:
class Counter extends PersistentActor {
context.setReceiveTimeout(120.seconds)
override def persistenceId: String = "Counter-" + self.path.name
var count = 0
def updateState(event: CounterChanged): Unit =
count += event.delta
override def receiveRecover: Receive = {
case evt: CounterChanged ⇒ updateState(evt)
}
override def receiveCommand: Receive = {
case Increment ⇒ persist(CounterChanged(+1))(updateState)
case Decrement ⇒ persist(CounterChanged(-1))(updateState)
case Get(_) ⇒ sender() ! count
case ReceiveTimeout ⇒ context.parent ! Passivate(stopMessage = Stop)
case Stop ⇒ context.stop(self)
}
}
31 / 40
Akka Cluster - Sharding
Create a region on every node:
val counterRegion: ActorRef = ClusterSharding(system).start(
typeName = "Counter",
entityProps = Props[Counter],
settings = ClusterShardingSettings(system),
extractEntityId = extractEntityId,
extractShardId = extractShardId)
Sharding functions:
val extractEntityId: ShardRegion.ExtractEntityId = {
case EntityEnvelope(id, payload) ⇒ (id.toString, payload)
case msg @ Get(id) ⇒ (id.toString, msg)
}
val numberOfShards = 100
val extractShardId: ShardRegion.ExtractShardId = {
case EntityEnvelope(id, _) ⇒ (id % numberOfShards).toString
case Get(id) ⇒ (id % numberOfShards).toString
}
32 / 40
Akka Cluster Sharding + Persistence = ❤
Akka Cluster Sharding:
Consistent hashing for all requests based on user-defined function
Automatic forwarding (from local to remote and vice versa)
Akka Persistence:
Keeping internal state
Easy and fast recovery (journal + snapshots)
Event-sourcing built-in
33 / 40
Real-world applications
34 / 40
Real-world applications
Complex event-driven state machine with low latency API (aka The Tracker)
More (online gaming, data aggregation, trading, complex domains, ...)
35 / 40
Real-world applications - The Tracker
Complex event-driven state machine:
Consuming:
Domain Events via messaging queue (Akka Camel)
Interface for querying:
HTTP API (Akka HTTP)
Websockets (Akka HTTP)
Every entity has a clientId and they never intersect - it's a perfect use-case for sharding (clientId
as a sharding key).
36 / 40
Real-world applications - The Tracker
object TrackerService {
case class TrackerData(
accounts: Map[String, BankAccount] = Map[String, BankAccount]()
)
}
class TrackerService extends PersistentActor {
private var state = TrackerData()
private def handleMessage(message: EventMessage) {
val maybeUpdatedState = message match {
case b: BankAccountMessage => handleBankMessage(b)
case c: ClientMessage => handleClientMessage(c)
case _ => None
}
maybeUpdatedState.foreach { updatedState =>
updateState(updatedState)
}
}
private def updateState(updatedState: TrackerData) = {
state = state.copy(
accounts = (state.accounts ++ updatedState.accounts).filterNot(_._2.deleted)
)
}
}
37 / 40
Real-world applications
38 / 40
Summary
Actor-based programming simplifies building highly scalable and reliable systems
It's not easy to build & maintain a stateful application, but you never know when it's going to
be needed
Don't try to write abstractions for distributed programming from scratch (unless you're an
expert)
Akka has a few great abstractions already, use them!
It's easier to build a stateful application as a microservice - smaller state size, more flexibility
and great separation of concerns
39 / 40
Questions?
@sap1ens
40 / 40
1 of 40

Recommended

Building Eventing Systems for Microservice Architecture by
Building Eventing Systems for Microservice Architecture  Building Eventing Systems for Microservice Architecture
Building Eventing Systems for Microservice Architecture Yaroslav Tkachenko
3.6K views51 slides
Why Actor-Based Systems Are The Best For Microservices by
Why Actor-Based Systems Are The Best For MicroservicesWhy Actor-Based Systems Are The Best For Microservices
Why Actor-Based Systems Are The Best For MicroservicesYaroslav Tkachenko
940 views42 slides
Akka Microservices Architecture And Design by
Akka Microservices Architecture And DesignAkka Microservices Architecture And Design
Akka Microservices Architecture And DesignYaroslav Tkachenko
4.6K views59 slides
Build Real-Time Streaming ETL Pipelines With Akka Streams, Alpakka And Apache... by
Build Real-Time Streaming ETL Pipelines With Akka Streams, Alpakka And Apache...Build Real-Time Streaming ETL Pipelines With Akka Streams, Alpakka And Apache...
Build Real-Time Streaming ETL Pipelines With Akka Streams, Alpakka And Apache...Lightbend
7.5K views72 slides
Building Scalable and Extendable Data Pipeline for Call of Duty Games: Lesson... by
Building Scalable and Extendable Data Pipeline for Call of Duty Games: Lesson...Building Scalable and Extendable Data Pipeline for Call of Duty Games: Lesson...
Building Scalable and Extendable Data Pipeline for Call of Duty Games: Lesson...Yaroslav Tkachenko
1.8K views44 slides
Why actor-based systems are the best for microservices by
Why actor-based systems are the best for microservicesWhy actor-based systems are the best for microservices
Why actor-based systems are the best for microservicesYaroslav Tkachenko
4.3K views31 slides

More Related Content

What's hot

Kafka Summit NYC 2017 - Easy, Scalable, Fault-tolerant Stream Processing with... by
Kafka Summit NYC 2017 - Easy, Scalable, Fault-tolerant Stream Processing with...Kafka Summit NYC 2017 - Easy, Scalable, Fault-tolerant Stream Processing with...
Kafka Summit NYC 2017 - Easy, Scalable, Fault-tolerant Stream Processing with...confluent
1.2K views44 slides
Akka Streams - From Zero to Kafka by
Akka Streams - From Zero to KafkaAkka Streams - From Zero to Kafka
Akka Streams - From Zero to KafkaMark Harrison
743 views31 slides
Akka Revealed: A JVM Architect's Journey From Resilient Actors To Scalable Cl... by
Akka Revealed: A JVM Architect's Journey From Resilient Actors To Scalable Cl...Akka Revealed: A JVM Architect's Journey From Resilient Actors To Scalable Cl...
Akka Revealed: A JVM Architect's Journey From Resilient Actors To Scalable Cl...Lightbend
12.3K views106 slides
Developing a Real-time Engine with Akka, Cassandra, and Spray by
Developing a Real-time Engine with Akka, Cassandra, and SprayDeveloping a Real-time Engine with Akka, Cassandra, and Spray
Developing a Real-time Engine with Akka, Cassandra, and SprayJacob Park
3.5K views42 slides
Spark Streaming Recipes and "Exactly Once" Semantics Revised by
Spark Streaming Recipes and "Exactly Once" Semantics RevisedSpark Streaming Recipes and "Exactly Once" Semantics Revised
Spark Streaming Recipes and "Exactly Once" Semantics RevisedMichael Spector
3.5K views45 slides
From Zero to Streaming Healthcare in Production (Alexander Kouznetsov, Invita... by
From Zero to Streaming Healthcare in Production (Alexander Kouznetsov, Invita...From Zero to Streaming Healthcare in Production (Alexander Kouznetsov, Invita...
From Zero to Streaming Healthcare in Production (Alexander Kouznetsov, Invita...confluent
1.2K views31 slides

What's hot(20)

Kafka Summit NYC 2017 - Easy, Scalable, Fault-tolerant Stream Processing with... by confluent
Kafka Summit NYC 2017 - Easy, Scalable, Fault-tolerant Stream Processing with...Kafka Summit NYC 2017 - Easy, Scalable, Fault-tolerant Stream Processing with...
Kafka Summit NYC 2017 - Easy, Scalable, Fault-tolerant Stream Processing with...
confluent1.2K views
Akka Streams - From Zero to Kafka by Mark Harrison
Akka Streams - From Zero to KafkaAkka Streams - From Zero to Kafka
Akka Streams - From Zero to Kafka
Mark Harrison743 views
Akka Revealed: A JVM Architect's Journey From Resilient Actors To Scalable Cl... by Lightbend
Akka Revealed: A JVM Architect's Journey From Resilient Actors To Scalable Cl...Akka Revealed: A JVM Architect's Journey From Resilient Actors To Scalable Cl...
Akka Revealed: A JVM Architect's Journey From Resilient Actors To Scalable Cl...
Lightbend12.3K views
Developing a Real-time Engine with Akka, Cassandra, and Spray by Jacob Park
Developing a Real-time Engine with Akka, Cassandra, and SprayDeveloping a Real-time Engine with Akka, Cassandra, and Spray
Developing a Real-time Engine with Akka, Cassandra, and Spray
Jacob Park3.5K views
Spark Streaming Recipes and "Exactly Once" Semantics Revised by Michael Spector
Spark Streaming Recipes and "Exactly Once" Semantics RevisedSpark Streaming Recipes and "Exactly Once" Semantics Revised
Spark Streaming Recipes and "Exactly Once" Semantics Revised
Michael Spector3.5K views
From Zero to Streaming Healthcare in Production (Alexander Kouznetsov, Invita... by confluent
From Zero to Streaming Healthcare in Production (Alexander Kouznetsov, Invita...From Zero to Streaming Healthcare in Production (Alexander Kouznetsov, Invita...
From Zero to Streaming Healthcare in Production (Alexander Kouznetsov, Invita...
confluent1.2K views
UDF/UDAF: the extensibility framework for KSQL (Hojjat Jafapour, Confluent) K... by confluent
UDF/UDAF: the extensibility framework for KSQL (Hojjat Jafapour, Confluent) K...UDF/UDAF: the extensibility framework for KSQL (Hojjat Jafapour, Confluent) K...
UDF/UDAF: the extensibility framework for KSQL (Hojjat Jafapour, Confluent) K...
confluent1.4K views
Apache Kafka: New Features That You Might Not Know About by Yaroslav Tkachenko
Apache Kafka: New Features That You Might Not Know AboutApache Kafka: New Features That You Might Not Know About
Apache Kafka: New Features That You Might Not Know About
Yaroslav Tkachenko4.9K views
Developing Secure Scala Applications With Fortify For Scala by Lightbend
Developing Secure Scala Applications With Fortify For ScalaDeveloping Secure Scala Applications With Fortify For Scala
Developing Secure Scala Applications With Fortify For Scala
Lightbend11.1K views
Kafka Streams: the easiest way to start with stream processing by Yaroslav Tkachenko
Kafka Streams: the easiest way to start with stream processingKafka Streams: the easiest way to start with stream processing
Kafka Streams: the easiest way to start with stream processing
Yaroslav Tkachenko6.6K views
Real Time Streaming Data with Kafka and TensorFlow (Yong Tang, MobileIron) Ka... by confluent
Real Time Streaming Data with Kafka and TensorFlow (Yong Tang, MobileIron) Ka...Real Time Streaming Data with Kafka and TensorFlow (Yong Tang, MobileIron) Ka...
Real Time Streaming Data with Kafka and TensorFlow (Yong Tang, MobileIron) Ka...
confluent3.4K views
Getting Started with Confluent Schema Registry by confluent
Getting Started with Confluent Schema RegistryGetting Started with Confluent Schema Registry
Getting Started with Confluent Schema Registry
confluent483 views
Specs2 whirlwind tour at Scaladays 2014 by Eric Torreborre
Specs2 whirlwind tour at Scaladays 2014Specs2 whirlwind tour at Scaladays 2014
Specs2 whirlwind tour at Scaladays 2014
Eric Torreborre2.5K views
Real-time streaming and data pipelines with Apache Kafka by Joe Stein
Real-time streaming and data pipelines with Apache KafkaReal-time streaming and data pipelines with Apache Kafka
Real-time streaming and data pipelines with Apache Kafka
Joe Stein48.1K views
Introduction to Structured Streaming by Knoldus Inc.
Introduction to Structured StreamingIntroduction to Structured Streaming
Introduction to Structured Streaming
Knoldus Inc.6.8K views
Event sourcing - what could possibly go wrong ? Devoxx PL 2021 by Andrzej Ludwikowski
Event sourcing  - what could possibly go wrong ? Devoxx PL 2021Event sourcing  - what could possibly go wrong ? Devoxx PL 2021
Event sourcing - what could possibly go wrong ? Devoxx PL 2021
ksqlDB: A Stream-Relational Database System by confluent
ksqlDB: A Stream-Relational Database SystemksqlDB: A Stream-Relational Database System
ksqlDB: A Stream-Relational Database System
confluent1.4K views
Fundamentals of Stream Processing with Apache Beam, Tyler Akidau, Frances Perry by confluent
Fundamentals of Stream Processing with Apache Beam, Tyler Akidau, Frances Perry Fundamentals of Stream Processing with Apache Beam, Tyler Akidau, Frances Perry
Fundamentals of Stream Processing with Apache Beam, Tyler Akidau, Frances Perry
confluent11K views
Streaming Microservices With Akka Streams And Kafka Streams by Lightbend
Streaming Microservices With Akka Streams And Kafka StreamsStreaming Microservices With Akka Streams And Kafka Streams
Streaming Microservices With Akka Streams And Kafka Streams
Lightbend34.1K views

Similar to Building Stateful Microservices With Akka

Reactive integrations with Akka Streams by
Reactive integrations with Akka StreamsReactive integrations with Akka Streams
Reactive integrations with Akka StreamsKonrad Malawski
1.9K views52 slides
Akka streams - Umeå java usergroup by
Akka streams - Umeå java usergroupAkka streams - Umeå java usergroup
Akka streams - Umeå java usergroupJohan Andrén
556 views57 slides
Reactive stream processing using Akka streams by
Reactive stream processing using Akka streams Reactive stream processing using Akka streams
Reactive stream processing using Akka streams Johan Andrén
1.1K views69 slides
Akka lsug skills matter by
Akka lsug skills matterAkka lsug skills matter
Akka lsug skills matterSkills Matter
2K views29 slides
Scaling Web Apps with Akka by
Scaling Web Apps with AkkaScaling Web Apps with Akka
Scaling Web Apps with AkkaMaciej Matyjas
5.5K views29 slides
VJUG24 - Reactive Integrations with Akka Streams by
VJUG24  - Reactive Integrations with Akka StreamsVJUG24  - Reactive Integrations with Akka Streams
VJUG24 - Reactive Integrations with Akka StreamsJohan Andrén
897 views38 slides

Similar to Building Stateful Microservices With Akka(20)

Reactive integrations with Akka Streams by Konrad Malawski
Reactive integrations with Akka StreamsReactive integrations with Akka Streams
Reactive integrations with Akka Streams
Konrad Malawski1.9K views
Akka streams - Umeå java usergroup by Johan Andrén
Akka streams - Umeå java usergroupAkka streams - Umeå java usergroup
Akka streams - Umeå java usergroup
Johan Andrén556 views
Reactive stream processing using Akka streams by Johan Andrén
Reactive stream processing using Akka streams Reactive stream processing using Akka streams
Reactive stream processing using Akka streams
Johan Andrén1.1K views
Scaling Web Apps with Akka by Maciej Matyjas
Scaling Web Apps with AkkaScaling Web Apps with Akka
Scaling Web Apps with Akka
Maciej Matyjas5.5K views
VJUG24 - Reactive Integrations with Akka Streams by Johan Andrén
VJUG24  - Reactive Integrations with Akka StreamsVJUG24  - Reactive Integrations with Akka Streams
VJUG24 - Reactive Integrations with Akka Streams
Johan Andrén897 views
Akka london scala_user_group by Skills Matter
Akka london scala_user_groupAkka london scala_user_group
Akka london scala_user_group
Skills Matter1.1K views
Developing distributed applications with Akka and Akka Cluster by Konstantin Tsykulenko
Developing distributed applications with Akka and Akka ClusterDeveloping distributed applications with Akka and Akka Cluster
Developing distributed applications with Akka and Akka Cluster
Reactive Streams 1.0 and Akka Streams by Dean Wampler
Reactive Streams 1.0 and Akka StreamsReactive Streams 1.0 and Akka Streams
Reactive Streams 1.0 and Akka Streams
Dean Wampler1.8K views
Spark streaming state of the union by Databricks
Spark streaming state of the unionSpark streaming state of the union
Spark streaming state of the union
Databricks3.9K views
Asynchronous stream processing with Akka Streams by Johan Andrén
Asynchronous stream processing with Akka StreamsAsynchronous stream processing with Akka Streams
Asynchronous stream processing with Akka Streams
Johan Andrén3K views
Reactive streams processing using Akka Streams by Johan Andrén
Reactive streams processing using Akka StreamsReactive streams processing using Akka Streams
Reactive streams processing using Akka Streams
Johan Andrén1.9K views
Reactive Stream Processing with Akka Streams by Konrad Malawski
Reactive Stream Processing with Akka StreamsReactive Stream Processing with Akka Streams
Reactive Stream Processing with Akka Streams
Konrad Malawski14.2K views
Strata NYC 2015: What's new in Spark Streaming by Databricks
Strata NYC 2015: What's new in Spark StreamingStrata NYC 2015: What's new in Spark Streaming
Strata NYC 2015: What's new in Spark Streaming
Databricks4K views
IPT Reactive Java IoT Demo - BGOUG 2018 by Trayan Iliev
IPT Reactive Java IoT Demo - BGOUG 2018IPT Reactive Java IoT Demo - BGOUG 2018
IPT Reactive Java IoT Demo - BGOUG 2018
Trayan Iliev355 views
Reactive Programming in .Net - actorbased computing with Akka.Net by Sören Stelzer
Reactive Programming in .Net - actorbased computing with Akka.NetReactive Programming in .Net - actorbased computing with Akka.Net
Reactive Programming in .Net - actorbased computing with Akka.Net
Sören Stelzer491 views
Akka A to Z: A Guide To The Industry’s Best Toolkit for Fast Data and Microse... by Lightbend
Akka A to Z: A Guide To The Industry’s Best Toolkit for Fast Data and Microse...Akka A to Z: A Guide To The Industry’s Best Toolkit for Fast Data and Microse...
Akka A to Z: A Guide To The Industry’s Best Toolkit for Fast Data and Microse...
Lightbend7.7K views
Apache Flink Overview at SF Spark and Friends by Stephan Ewen
Apache Flink Overview at SF Spark and FriendsApache Flink Overview at SF Spark and Friends
Apache Flink Overview at SF Spark and Friends
Stephan Ewen2.2K views

More from Yaroslav Tkachenko

Streaming SQL for Data Engineers: The Next Big Thing? by
Streaming SQL for Data Engineers: The Next Big Thing?Streaming SQL for Data Engineers: The Next Big Thing?
Streaming SQL for Data Engineers: The Next Big Thing?Yaroslav Tkachenko
198 views57 slides
Apache Flink Adoption at Shopify by
Apache Flink Adoption at ShopifyApache Flink Adoption at Shopify
Apache Flink Adoption at ShopifyYaroslav Tkachenko
1.1K views36 slides
Storing State Forever: Why It Can Be Good For Your Analytics by
Storing State Forever: Why It Can Be Good For Your AnalyticsStoring State Forever: Why It Can Be Good For Your Analytics
Storing State Forever: Why It Can Be Good For Your AnalyticsYaroslav Tkachenko
483 views38 slides
It's Time To Stop Using Lambda Architecture by
It's Time To Stop Using Lambda ArchitectureIt's Time To Stop Using Lambda Architecture
It's Time To Stop Using Lambda ArchitectureYaroslav Tkachenko
213 views37 slides
Bravo Six, Going Realtime. Transitioning Activision Data Pipeline to Streaming by
Bravo Six, Going Realtime. Transitioning Activision Data Pipeline to StreamingBravo Six, Going Realtime. Transitioning Activision Data Pipeline to Streaming
Bravo Six, Going Realtime. Transitioning Activision Data Pipeline to StreamingYaroslav Tkachenko
542 views39 slides
Designing Scalable and Extendable Data Pipeline for Call Of Duty Games by
Designing Scalable and Extendable Data Pipeline for Call Of Duty GamesDesigning Scalable and Extendable Data Pipeline for Call Of Duty Games
Designing Scalable and Extendable Data Pipeline for Call Of Duty GamesYaroslav Tkachenko
1.1K views27 slides

More from Yaroslav Tkachenko(9)

Streaming SQL for Data Engineers: The Next Big Thing? by Yaroslav Tkachenko
Streaming SQL for Data Engineers: The Next Big Thing?Streaming SQL for Data Engineers: The Next Big Thing?
Streaming SQL for Data Engineers: The Next Big Thing?
Yaroslav Tkachenko198 views
Storing State Forever: Why It Can Be Good For Your Analytics by Yaroslav Tkachenko
Storing State Forever: Why It Can Be Good For Your AnalyticsStoring State Forever: Why It Can Be Good For Your Analytics
Storing State Forever: Why It Can Be Good For Your Analytics
Yaroslav Tkachenko483 views
Bravo Six, Going Realtime. Transitioning Activision Data Pipeline to Streaming by Yaroslav Tkachenko
Bravo Six, Going Realtime. Transitioning Activision Data Pipeline to StreamingBravo Six, Going Realtime. Transitioning Activision Data Pipeline to Streaming
Bravo Six, Going Realtime. Transitioning Activision Data Pipeline to Streaming
Yaroslav Tkachenko542 views
Designing Scalable and Extendable Data Pipeline for Call Of Duty Games by Yaroslav Tkachenko
Designing Scalable and Extendable Data Pipeline for Call Of Duty GamesDesigning Scalable and Extendable Data Pipeline for Call Of Duty Games
Designing Scalable and Extendable Data Pipeline for Call Of Duty Games
Yaroslav Tkachenko1.1K views
10 tips for making Bash a sane programming language by Yaroslav Tkachenko
10 tips for making Bash a sane programming language10 tips for making Bash a sane programming language
10 tips for making Bash a sane programming language
Yaroslav Tkachenko764 views
Быстрая и безболезненная разработка клиентской части веб-приложений by Yaroslav Tkachenko
Быстрая и безболезненная разработка клиентской части веб-приложенийБыстрая и безболезненная разработка клиентской части веб-приложений
Быстрая и безболезненная разработка клиентской части веб-приложений
Yaroslav Tkachenko801 views

Recently uploaded

DSD-INT 2023 The Danube Hazardous Substances Model - Kovacs by
DSD-INT 2023 The Danube Hazardous Substances Model - KovacsDSD-INT 2023 The Danube Hazardous Substances Model - Kovacs
DSD-INT 2023 The Danube Hazardous Substances Model - KovacsDeltares
8 views17 slides
SAP FOR TYRE INDUSTRY.pdf by
SAP FOR TYRE INDUSTRY.pdfSAP FOR TYRE INDUSTRY.pdf
SAP FOR TYRE INDUSTRY.pdfVirendra Rai, PMP
24 views3 slides
Myths and Facts About Hospice Care: Busting Common Misconceptions by
Myths and Facts About Hospice Care: Busting Common MisconceptionsMyths and Facts About Hospice Care: Busting Common Misconceptions
Myths and Facts About Hospice Care: Busting Common MisconceptionsCare Coordinations
5 views1 slide
20231129 - Platform @ localhost 2023 - Application-driven infrastructure with... by
20231129 - Platform @ localhost 2023 - Application-driven infrastructure with...20231129 - Platform @ localhost 2023 - Application-driven infrastructure with...
20231129 - Platform @ localhost 2023 - Application-driven infrastructure with...sparkfabrik
5 views46 slides
DSD-INT 2023 Simulation of Coastal Hydrodynamics and Water Quality in Hong Ko... by
DSD-INT 2023 Simulation of Coastal Hydrodynamics and Water Quality in Hong Ko...DSD-INT 2023 Simulation of Coastal Hydrodynamics and Water Quality in Hong Ko...
DSD-INT 2023 Simulation of Coastal Hydrodynamics and Water Quality in Hong Ko...Deltares
14 views23 slides
DSD-INT 2023 Machine learning in hydraulic engineering - Exploring unseen fut... by
DSD-INT 2023 Machine learning in hydraulic engineering - Exploring unseen fut...DSD-INT 2023 Machine learning in hydraulic engineering - Exploring unseen fut...
DSD-INT 2023 Machine learning in hydraulic engineering - Exploring unseen fut...Deltares
7 views28 slides

Recently uploaded(20)

DSD-INT 2023 The Danube Hazardous Substances Model - Kovacs by Deltares
DSD-INT 2023 The Danube Hazardous Substances Model - KovacsDSD-INT 2023 The Danube Hazardous Substances Model - Kovacs
DSD-INT 2023 The Danube Hazardous Substances Model - Kovacs
Deltares8 views
Myths and Facts About Hospice Care: Busting Common Misconceptions by Care Coordinations
Myths and Facts About Hospice Care: Busting Common MisconceptionsMyths and Facts About Hospice Care: Busting Common Misconceptions
Myths and Facts About Hospice Care: Busting Common Misconceptions
20231129 - Platform @ localhost 2023 - Application-driven infrastructure with... by sparkfabrik
20231129 - Platform @ localhost 2023 - Application-driven infrastructure with...20231129 - Platform @ localhost 2023 - Application-driven infrastructure with...
20231129 - Platform @ localhost 2023 - Application-driven infrastructure with...
sparkfabrik5 views
DSD-INT 2023 Simulation of Coastal Hydrodynamics and Water Quality in Hong Ko... by Deltares
DSD-INT 2023 Simulation of Coastal Hydrodynamics and Water Quality in Hong Ko...DSD-INT 2023 Simulation of Coastal Hydrodynamics and Water Quality in Hong Ko...
DSD-INT 2023 Simulation of Coastal Hydrodynamics and Water Quality in Hong Ko...
Deltares14 views
DSD-INT 2023 Machine learning in hydraulic engineering - Exploring unseen fut... by Deltares
DSD-INT 2023 Machine learning in hydraulic engineering - Exploring unseen fut...DSD-INT 2023 Machine learning in hydraulic engineering - Exploring unseen fut...
DSD-INT 2023 Machine learning in hydraulic engineering - Exploring unseen fut...
Deltares7 views
Navigating container technology for enhanced security by Niklas Saari by Metosin Oy
Navigating container technology for enhanced security by Niklas SaariNavigating container technology for enhanced security by Niklas Saari
Navigating container technology for enhanced security by Niklas Saari
Metosin Oy14 views
Gen Apps on Google Cloud PaLM2 and Codey APIs in Action by Márton Kodok
Gen Apps on Google Cloud PaLM2 and Codey APIs in ActionGen Apps on Google Cloud PaLM2 and Codey APIs in Action
Gen Apps on Google Cloud PaLM2 and Codey APIs in Action
Márton Kodok5 views
Sprint 226 by ManageIQ
Sprint 226Sprint 226
Sprint 226
ManageIQ5 views
DSD-INT 2023 Exploring flash flood hazard reduction in arid regions using a h... by Deltares
DSD-INT 2023 Exploring flash flood hazard reduction in arid regions using a h...DSD-INT 2023 Exploring flash flood hazard reduction in arid regions using a h...
DSD-INT 2023 Exploring flash flood hazard reduction in arid regions using a h...
Deltares5 views
DSD-INT 2023 Process-based modelling of salt marsh development coupling Delft... by Deltares
DSD-INT 2023 Process-based modelling of salt marsh development coupling Delft...DSD-INT 2023 Process-based modelling of salt marsh development coupling Delft...
DSD-INT 2023 Process-based modelling of salt marsh development coupling Delft...
Deltares7 views
Airline Booking Software by SharmiMehta
Airline Booking SoftwareAirline Booking Software
Airline Booking Software
SharmiMehta6 views
Unmasking the Dark Art of Vectored Exception Handling: Bypassing XDR and EDR ... by Donato Onofri
Unmasking the Dark Art of Vectored Exception Handling: Bypassing XDR and EDR ...Unmasking the Dark Art of Vectored Exception Handling: Bypassing XDR and EDR ...
Unmasking the Dark Art of Vectored Exception Handling: Bypassing XDR and EDR ...
Donato Onofri825 views
DSD-INT 2023 Simulating a falling apron in Delft3D 4 - Engineering Practice -... by Deltares
DSD-INT 2023 Simulating a falling apron in Delft3D 4 - Engineering Practice -...DSD-INT 2023 Simulating a falling apron in Delft3D 4 - Engineering Practice -...
DSD-INT 2023 Simulating a falling apron in Delft3D 4 - Engineering Practice -...
Deltares6 views
AI and Ml presentation .pptx by FayazAli87
AI and Ml presentation .pptxAI and Ml presentation .pptx
AI and Ml presentation .pptx
FayazAli8711 views
DSD-INT 2023 Leveraging the results of a 3D hydrodynamic model to improve the... by Deltares
DSD-INT 2023 Leveraging the results of a 3D hydrodynamic model to improve the...DSD-INT 2023 Leveraging the results of a 3D hydrodynamic model to improve the...
DSD-INT 2023 Leveraging the results of a 3D hydrodynamic model to improve the...
Deltares6 views
Dev-HRE-Ops - Addressing the _Last Mile DevOps Challenge_ in Highly Regulated... by TomHalpin9
Dev-HRE-Ops - Addressing the _Last Mile DevOps Challenge_ in Highly Regulated...Dev-HRE-Ops - Addressing the _Last Mile DevOps Challenge_ in Highly Regulated...
Dev-HRE-Ops - Addressing the _Last Mile DevOps Challenge_ in Highly Regulated...
TomHalpin96 views
DSD-INT 2023 3D hydrodynamic modelling of microplastic transport in lakes - J... by Deltares
DSD-INT 2023 3D hydrodynamic modelling of microplastic transport in lakes - J...DSD-INT 2023 3D hydrodynamic modelling of microplastic transport in lakes - J...
DSD-INT 2023 3D hydrodynamic modelling of microplastic transport in lakes - J...
Deltares9 views
Fleet Management Software in India by Fleetable
Fleet Management Software in India Fleet Management Software in India
Fleet Management Software in India
Fleetable11 views

Building Stateful Microservices With Akka

  • 1. Building Stateful Microservices With Akka Yaroslav Tkachenko Senior Software Engineer at Demonware (Activision) 1 / 40
  • 2. Java, Scala, Python, Node Microservices Event-driven Systems Distributed Systems DevOps ... and more About me Yaroslav (Slava) Tkachenko, Vancouver, Canada Demonware (Activision), 2017 Senior Software Engineer [Data Pipeline] Mobify, 2016 - 2017 Senior Software Engineer, Lead [Platform] Bench Accounting, 2011 - 2016 Director of Engineering [Platform] Engineering Lead Software Engineer Freelance, 2007 - 2011 Web Developer 2 / 40
  • 4. Agenda Microservices: stateless vs stateful Actor systems Akka Akka Cluster and Persistence Real-world applications 4 / 40
  • 5. Microservices: stateless vs stateful 5 / 40
  • 6. Microservices: stateless vs stateful Stateless application: application that doesn't keep any state in memory / runtime, but uses external services instead. External service: database, cache, API, etc. Examples: most of the web apps are stateless or designed to be stateless (Spring, Django, Rails, Express, etc.). Stateful application: application that keeps internal state in memory / runtime, instead of relying on external services. Examples: actors can be stateful, so Akka and other actor-based systems (Erlang/OTP, Orleans) can be stateful. But it's also possible to create stateful applications in Node.js or Python, for example. 6 / 40
  • 8. Microservices: stateless Benefits: Simple development & deployment Simple to scale out -> just add more nodes Biggest challenges: Low latency -> can use caching, but not when strong consistency is needed Concurrent modifications -> conflict resolution with optimistic / pessimistic locking 8 / 40
  • 11. Microservices: stateful Benefits: Data locality -> low latency, fast processing Sticky consistency -> "simple" and "cheap" consistency without using consensus protocols Biggest challenges: High availability Scaling out 11 / 40
  • 13. Actor systems An actor is a computational entity that, in response to a message it receives, can concurrently: send a finite number of messages to other actors; create a finite number of new actors; designate the behavior to be used for the next message it receives. There is no assumed sequence to the above actions and they could be carried out in parallel. Every actor has: A mailbox A supervisor Some state [optionally] 13 / 40
  • 14. Rachel Alex Actor systems - Examples           Fred 14 / 40
  • 15. Actor systems - Examples Akka Concurrency by Derek Wyatt, Artima 15 / 40
  • 16. Actor systems - Examples Akka Concurrency by Derek Wyatt, Artima 16 / 40
  • 17. Actor systems - Examples Akka Concurrency by Derek Wyatt, Artima 17 / 40
  • 19. Akka Akka is an open-source toolkit and runtime simplifying the construction of concurrent and distributed applications on the JVM. Akka supports multiple programming models for concurrency, but it emphasizes actor-based concurrency, with inspiration drawn from Erlang. 19 / 40
  • 20. Akka - Actors case class Greeting(who: String) class GreetingActor extends Actor with ActorLogging { def receive = { case Greeting(who) => log.info("Hello " + who) } } val system = ActorSystem("MySystem") val greeter = system.actorOf(Props[GreetingActor], name = "greeter") greeter ! Greeting("Charlie Parker")   Messages are handled one by one Immutability of messages 20 / 40
  • 21. Akka - Communication class HelloActor extends Actor with ActorLogging { def receive = { case who => sender() ! "Hello, " + who } } object ConversationActor { def props(fellowActor: ActorRef): Props = Props(classOf[ConversationActor], fellowActor) } class ConversationActor(fellowActor: ActorRef) extends Actor with ActorLogging { def receive = { case "start" => fellowActor ! "it's me!" case message => log.info(message) } } val system = ActorSystem("MySystem") val helloActor = system.actorOf(Props[HelloActor]) val conversationActor = ConversationActor.props(helloActor) conversationActor ! "start" 21 / 40
  • 22. Actor systems and Akka - Why? So, why actors? Simple concurrency Clean asynchronous programming model Great fit for event-driven systems Resilience Scalability 22 / 40
  • 24. Akka Persistence - Overview 24 / 40
  • 25. Akka Persistence - Overview Event Sourcing Persistent Actor Journal Snapshot Has plugins for JDBC (MySQL, Postgres, ...), MongoDB, Cassandra, Kafka, Redis and more. 25 / 40
  • 26. Akka Persistence - Example case class Cmd(data: String) case class Evt(data: String) case class ExampleState(events: List[String] = Nil) { def updated(evt: Evt): ExampleState = copy(evt.data :: events) override def toString: String = events.reverse.toString } class ExamplePersistentActor extends PersistentActor { override def persistenceId = "sample-id-1" var state = ExampleState() def updateState(event: Evt): Unit = state = state.updated(event) val receiveRecover: Receive = { case evt: Evt => updateState(evt) case SnapshotOffer(_, snapshot: ExampleState) => state = snapshot } val receiveCommand: Receive = { case Cmd(data) => persist(Evt(data))(updateState) case "snap" => saveSnapshot(state) case "print" => println(state) } } 26 / 40
  • 29. Akka Cluster - Sharding Features: One of the most powerful Akka features! Allows to route messages across nodes in a cluster using a sharding function (actually two) You don't need to know the physical location of an actor - cluster will forward message to a remote node if needed Uses Akka Persistence internally (or brand-new Distributed Data) Concepts: Coordinator Shard Region Shard Entity Entities (actors) are "activated" by receiving a first message and can be "passivated" using context.setReceiveTimeout. 29 / 40
  • 30. Akka Cluster - Sharding Counter interface: case object Increment case object Decrement final case class Get(counterId: Long) final case class EntityEnvelope(id: Long, payload: Any) case object Stop final case class CounterChanged(delta: Int) 30 / 40
  • 31. Akka Cluster - Sharding Counter implementation: class Counter extends PersistentActor { context.setReceiveTimeout(120.seconds) override def persistenceId: String = "Counter-" + self.path.name var count = 0 def updateState(event: CounterChanged): Unit = count += event.delta override def receiveRecover: Receive = { case evt: CounterChanged ⇒ updateState(evt) } override def receiveCommand: Receive = { case Increment ⇒ persist(CounterChanged(+1))(updateState) case Decrement ⇒ persist(CounterChanged(-1))(updateState) case Get(_) ⇒ sender() ! count case ReceiveTimeout ⇒ context.parent ! Passivate(stopMessage = Stop) case Stop ⇒ context.stop(self) } } 31 / 40
  • 32. Akka Cluster - Sharding Create a region on every node: val counterRegion: ActorRef = ClusterSharding(system).start( typeName = "Counter", entityProps = Props[Counter], settings = ClusterShardingSettings(system), extractEntityId = extractEntityId, extractShardId = extractShardId) Sharding functions: val extractEntityId: ShardRegion.ExtractEntityId = { case EntityEnvelope(id, payload) ⇒ (id.toString, payload) case msg @ Get(id) ⇒ (id.toString, msg) } val numberOfShards = 100 val extractShardId: ShardRegion.ExtractShardId = { case EntityEnvelope(id, _) ⇒ (id % numberOfShards).toString case Get(id) ⇒ (id % numberOfShards).toString } 32 / 40
  • 33. Akka Cluster Sharding + Persistence = ❤ Akka Cluster Sharding: Consistent hashing for all requests based on user-defined function Automatic forwarding (from local to remote and vice versa) Akka Persistence: Keeping internal state Easy and fast recovery (journal + snapshots) Event-sourcing built-in 33 / 40
  • 35. Real-world applications Complex event-driven state machine with low latency API (aka The Tracker) More (online gaming, data aggregation, trading, complex domains, ...) 35 / 40
  • 36. Real-world applications - The Tracker Complex event-driven state machine: Consuming: Domain Events via messaging queue (Akka Camel) Interface for querying: HTTP API (Akka HTTP) Websockets (Akka HTTP) Every entity has a clientId and they never intersect - it's a perfect use-case for sharding (clientId as a sharding key). 36 / 40
  • 37. Real-world applications - The Tracker object TrackerService { case class TrackerData( accounts: Map[String, BankAccount] = Map[String, BankAccount]() ) } class TrackerService extends PersistentActor { private var state = TrackerData() private def handleMessage(message: EventMessage) { val maybeUpdatedState = message match { case b: BankAccountMessage => handleBankMessage(b) case c: ClientMessage => handleClientMessage(c) case _ => None } maybeUpdatedState.foreach { updatedState => updateState(updatedState) } } private def updateState(updatedState: TrackerData) = { state = state.copy( accounts = (state.accounts ++ updatedState.accounts).filterNot(_._2.deleted) ) } } 37 / 40
  • 39. Summary Actor-based programming simplifies building highly scalable and reliable systems It's not easy to build & maintain a stateful application, but you never know when it's going to be needed Don't try to write abstractions for distributed programming from scratch (unless you're an expert) Akka has a few great abstractions already, use them! It's easier to build a stateful application as a microservice - smaller state size, more flexibility and great separation of concerns 39 / 40