Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.
Akka in ActionRaymond Roestenburg@RayRoestenburgrroestenburg@xebia.comgithub.com/RayRoestenburg
manning.com/roestenburg12mp25 for 42% Off!Early Akka adopter (v0.7, 2010)Akka Committer (akka-camel in 2.x)Co-author of Ak...
“The free lunch is over” / TANSTAAFLHerb Sutter 2005 http://www.gotw.ca/publications/concurrency-ddj.htmNumberof transisto...
Can‟t I just..Parallelizethat Sh*t™?Put that in a box!Something like this?ParallelVersion9Hey Oracle don‟t sue me, of cour...
Nope. Parallelize that Sh*t™Not every algorithm can be parallelizedDynamic coordination (concurrent)Amdahl‟s LawSequential...
Threads?Shared (mutable) state + locksRequire synchronizationDiminishing returns**Which primitives to use?Difficult to pre...
“Life is too short forBlocking code”**Mario Fusco just the other day on twitter
Why Async? Less latency.ServiceService AService BService C4 sec6 sec3 secSync takes 13 secondsAsync takes max 6 secondsAsy...
1. The world is concurrent2. Things in the world dont share data3. Things communicate with messages4. Things failJoe Armst...
We need better tools to build..Reactive*Applications* The latest need-to-know buzz word!
event drivenscalableasynchronousresilient
Scale Up and OutConcurrentDistributedMany NodesMany ThreadsAkkaA uniform model for both upand out, embracesconcurrency and...
ActorsFuturesAgents
Scale UpProcesses (even less**)Actors (2.7 million / 1GB)Threads (4096 / 1GB)Actors are small** Disclaimer: text is not sh...
Reactive Asynchronous Building Blocks1. CREATE2. SEND3. BECOME4. SUPERVISE*
ActorActorInstanceActorRefMailbox
ActorRefActorInstanceActorRefMailboxPoints to ActorDelivers messages to Mailbox
MailboxActorInstanceActorRefMailboxProcesses Messages asynchronously*Invokes Actor Instance with message*The Mailbox runs ...
Actor InstanceActorInstanceActorRefMailboxReceives messages one at a timeYour code runs here.
Actor InstanceCrashed ActorInstanceMailboxAn Actor Instance crashes instead of handlingExceptions. A Supervisor decides it...
ActorRefActorInstanceMailboxImmutable. Only the ActorRef is accessibleFrom the outside.ActorRef
ActorRefActorInstanceMailboxThe ActorRef is usedfor both local and remote actors.ActorRef
ActorRefActorInstanceMailboxThe ActorRef always points 1 on 1 to the„same‟ Actor instance. (Alive or Restarted)ActorRefAct...
ActorRefDead ActorInstanceMailboxThe ActorRef points to deadletters ActorRefwhen the actor is dead (terminated).ActorRefde...
msgmsgImmutable messagesmsgLocationTransparencymsg Serialized messagesActor SystemActor SystemActor SystemActor systemsEvent
Immutable messagesmsgmsgapp@node2app@node1app@node3“app” clusteredactor systemOn three nodesClustered actor systemmsgmsg
“GoTicks.com”Build a REST APIPUT /events{“event” : “RHCP”,“nrOfTickets”: 300}GET /ticket/RHCPResponse:{“event”: “RHCP”,“nr...
RestApiTicketSellerTicketSellerBoxOfficeGoTicks.comSpray&Akka“goticks” ActorSystemREST Spray-can
GoTicks.comREST InterfaceHandles HTTP callsTranslates to and fromJSONRestApiREST Spray-can
GoTicks.comBoxOfficeREST Spray-canBoxOfficeCreates EventsCreates TicketSellerOne for every EventPartition / shard per even...
GoTicks.comTicketSellerTicketSellerREST Spray-canTicketSellerContains list of TicketsSells Tickets for a Eventuntil SoldOut
RestApiTicketSellerTicketSellerBoxOfficeClustered GoTicks.comTicketSellerTicketSellerBoxOfficeConsistentHashingConsistentH...
Code
1. CREATE
Inside our Main class…val system = new ActorSystem(“goticks”)CreateThe systemActorSystem(“goticks”)
Inside Main…val system = new ActorSystem(“goticks”)val api = system.actorOf(Props[RestInterface],“httpInterface”)…CREATERe...
Inside Main…val system = new ActorSystem(“goticks”)val api = system.actorOf(Props[RestInterface],“httpInterface”)…CREATERe...
Inside Main…val system = new ActorSystem(“goticks”)val api = system.actorOf(Props[RestInterface],“httpInterface”)…CREATERe...
ActorSystem(“goticks”)ActorSystem(“goticks”)Inside RestInterface..val master = context.actorOf(Props[BoxOffice],”boxOffice...
ActorSystem(“goticks”)ActorSystem(“goticks”)Inside RestInterface..val master = context.actorOf(Props[BoxOffice],”boxOffice...
Inside BoxOffice…val child = context.actorOf(Props[TicketSeller],eventName)1. CREATETicketSellerActorSystem(“goticks”)Acto...
Inside BoxOffice…val child = context.actorOf(Props[TicketSeller],eventName)1. CREATETicketSellerActorSystem(“goticks”)Acto...
2. SEND/RECEIVE
Receiving messagesclass BoxOffice extends Actor {def receive = {case TicketRequest(name) =>…case GetEvents =>…case event: ...
Receiving messagesclass TicketSeller extends Actor {def receive = soldOutdef soldOut:Receive = {case Tickets(newTickets) =...
Create EventActorSystem(“goticks”)ActorSystem(“goticks”)REST InterfaceBoxOfficeEvent(“RHCP”, 250){ event: “RHCP” nrOfTicke...
Create EventActorSystem(“goticks”)ActorSystem(“goticks”)REST InterfaceBoxOfficeEvent(“RHCP”, 250){ event: “RHCP” nrOfTicke...
ActorSystem(“goticks”)ActorSystem(“goticks”)REST InterfaceBoxOfficeEvent(“RHCP”, 250){ event: “RHCP” nrOfTickets: 250}Insi...
ActorSystem(“goticks”)ActorSystem(“goticks”)REST InterfaceBoxOfficeEventCreatedInside BoxOffice…sender ! EventCreatedRespo...
ActorSystem(“goticks”)ActorSystem(“goticks”)REST InterfaceBoxOffice{ event: “RHCP” nrOfTickets: 250}BuyTicketTicketSellerI...
ActorSystem(“goticks”)ActorSystem(“goticks”)REST InterfaceBoxOffice{ event: “RHCP”, nr :1}TicketSellerInside TicketSeller…...
CODE
Questions?@RayRoestenburgrroestenburg@xebia.comwww.xebia.comgithub.com/RayRoestenburg/xebicon
Backup slides
“Async sending subscriptiondata”SendThread XConsumerConsumerConsumerThread 1Thread 2Thread 1Service A
SendThread XConsumerConsumerConsumerThread 1Thread 2Thread 1Service AThread 2 fails
SendThread XConsumerConsumerConsumerThread 1Thread 2Thread 1Service AThread 2 failsHandle every possible errorinside Threa...
SendThread XConsumerConsumerConsumerThread 1Thread 2Thread 1Service AThread 2 failsRestart / Stop?Monitor?Handle errorsacr...
4. Supervise*Untangle behavior and errors„Just Reboot‟Let It Crash ™Error Kernel
4. Supervise*StrategiesOne for One(Poison Pill /Seppuku)All for One
4. Supervise*val supervisorStrategy =OneForOneStrategy(maxNrOfRetries = 5,withinTimeRange = 1 minute) {case _: Exception =...
4. Supervise*val supervisorStrategy =OneForOneStrategy(maxNrOfRetries = 5,withinTimeRange = 1 minute) {case _: Exception =...
Upcoming SlideShare
Loading in …5
×

Akka in-action

6,234 views

Published on

Slides from Akka in Action live coding session at Xebicon demonstrating a simple app using Scala, Akka and Spray. Both single node and clustered.

  • Be the first to comment

Akka in-action

  1. 1. Akka in ActionRaymond Roestenburg@RayRoestenburgrroestenburg@xebia.comgithub.com/RayRoestenburg
  2. 2. manning.com/roestenburg12mp25 for 42% Off!Early Akka adopter (v0.7, 2010)Akka Committer (akka-camel in 2.x)Co-author of Akka in Action
  3. 3. “The free lunch is over” / TANSTAAFLHerb Sutter 2005 http://www.gotw.ca/publications/concurrency-ddj.htmNumberof transistorsClock Speed
  4. 4. Can‟t I just..Parallelizethat Sh*t™?Put that in a box!Something like this?ParallelVersion9Hey Oracle don‟t sue me, of course it‟s fake
  5. 5. Nope. Parallelize that Sh*t™Not every algorithm can be parallelizedDynamic coordination (concurrent)Amdahl‟s LawSequential fraction determines max speedup
  6. 6. Threads?Shared (mutable) state + locksRequire synchronizationDiminishing returns**Which primitives to use?Difficult to predict & maintainDeadlockLivelockThread starvationRace condition*Using threads directly is meant here**Performance improvement degrades with more threads than cores.
  7. 7. “Life is too short forBlocking code”**Mario Fusco just the other day on twitter
  8. 8. Why Async? Less latency.ServiceService AService BService C4 sec6 sec3 secSync takes 13 secondsAsync takes max 6 secondsAsynchronous „first completed response‟ is easy to do
  9. 9. 1. The world is concurrent2. Things in the world dont share data3. Things communicate with messages4. Things failJoe Armstrong (creator of Erlang)
  10. 10. We need better tools to build..Reactive*Applications* The latest need-to-know buzz word!
  11. 11. event drivenscalableasynchronousresilient
  12. 12. Scale Up and OutConcurrentDistributedMany NodesMany ThreadsAkkaA uniform model for both upand out, embracesconcurrency and failureMaximize the use of cores_and_ nodes.Concurrent(moreCores)Distributed (more Nodes)
  13. 13. ActorsFuturesAgents
  14. 14. Scale UpProcesses (even less**)Actors (2.7 million / 1GB)Threads (4096 / 1GB)Actors are small** Disclaimer: text is not shown to scale, actors are way smaller..** Especially JVM processes
  15. 15. Reactive Asynchronous Building Blocks1. CREATE2. SEND3. BECOME4. SUPERVISE*
  16. 16. ActorActorInstanceActorRefMailbox
  17. 17. ActorRefActorInstanceActorRefMailboxPoints to ActorDelivers messages to Mailbox
  18. 18. MailboxActorInstanceActorRefMailboxProcesses Messages asynchronously*Invokes Actor Instance with message*The Mailbox runs on a Dispatcher that abstracts threading
  19. 19. Actor InstanceActorInstanceActorRefMailboxReceives messages one at a timeYour code runs here.
  20. 20. Actor InstanceCrashed ActorInstanceMailboxAn Actor Instance crashes instead of handlingExceptions. A Supervisor decides it‟s fate.ActorRefRestart / Resume / Stop / EscalateNew ActorInstance
  21. 21. ActorRefActorInstanceMailboxImmutable. Only the ActorRef is accessibleFrom the outside.ActorRef
  22. 22. ActorRefActorInstanceMailboxThe ActorRef is usedfor both local and remote actors.ActorRef
  23. 23. ActorRefActorInstanceMailboxThe ActorRef always points 1 on 1 to the„same‟ Actor instance. (Alive or Restarted)ActorRefActorInstance
  24. 24. ActorRefDead ActorInstanceMailboxThe ActorRef points to deadletters ActorRefwhen the actor is dead (terminated).ActorRefdeadletters
  25. 25. msgmsgImmutable messagesmsgLocationTransparencymsg Serialized messagesActor SystemActor SystemActor SystemActor systemsEvent
  26. 26. Immutable messagesmsgmsgapp@node2app@node1app@node3“app” clusteredactor systemOn three nodesClustered actor systemmsgmsg
  27. 27. “GoTicks.com”Build a REST APIPUT /events{“event” : “RHCP”,“nrOfTickets”: 300}GET /ticket/RHCPResponse:{“event”: “RHCP”,“nr”: 1}GET /eventsResponse:[{ “event”: “RHCP”, “nrOfTickets”: 299 }]
  28. 28. RestApiTicketSellerTicketSellerBoxOfficeGoTicks.comSpray&Akka“goticks” ActorSystemREST Spray-can
  29. 29. GoTicks.comREST InterfaceHandles HTTP callsTranslates to and fromJSONRestApiREST Spray-can
  30. 30. GoTicks.comBoxOfficeREST Spray-canBoxOfficeCreates EventsCreates TicketSellerOne for every EventPartition / shard per eventMany sharding strategies possible
  31. 31. GoTicks.comTicketSellerTicketSellerREST Spray-canTicketSellerContains list of TicketsSells Tickets for a Eventuntil SoldOut
  32. 32. RestApiTicketSellerTicketSellerBoxOfficeClustered GoTicks.comTicketSellerTicketSellerBoxOfficeConsistentHashingConsistentHashing
  33. 33. Code
  34. 34. 1. CREATE
  35. 35. Inside our Main class…val system = new ActorSystem(“goticks”)CreateThe systemActorSystem(“goticks”)
  36. 36. Inside Main…val system = new ActorSystem(“goticks”)val api = system.actorOf(Props[RestInterface],“httpInterface”)…CREATERestInterfaceActorSystem(“goticks”)Top Level ActorActorSystem(“goticks”)REST Interface
  37. 37. Inside Main…val system = new ActorSystem(“goticks”)val api = system.actorOf(Props[RestInterface],“httpInterface”)…CREATERestInterfaceActorSystem(“goticks”)Factory/Creator/ Immutable Configuration objectActorSystem(“goticks”)REST Interface
  38. 38. Inside Main…val system = new ActorSystem(“goticks”)val api = system.actorOf(Props[RestInterface],“httpInterface”)…CREATERestInterfaceActorSystem(“goticks”)ActorRef to the ActorActorSystem(“goticks”)REST Interface
  39. 39. ActorSystem(“goticks”)ActorSystem(“goticks”)Inside RestInterface..val master = context.actorOf(Props[BoxOffice],”boxOffice”)1. CREATEBoxOfficeREST InterfaceBoxOfficeChild ofREST Interface Actor
  40. 40. ActorSystem(“goticks”)ActorSystem(“goticks”)Inside RestInterface..val master = context.actorOf(Props[BoxOffice],”boxOffice”)1. CREATEBoxOfficeREST InterfaceBoxOfficeAn Actor has a name, part of an ActorPath
  41. 41. Inside BoxOffice…val child = context.actorOf(Props[TicketSeller],eventName)1. CREATETicketSellerActorSystem(“goticks”)ActorSystem(“goticks”)REST InterfaceBoxOfficeTicketSellerChild ofBoxOffice Actor
  42. 42. Inside BoxOffice…val child = context.actorOf(Props[TicketSeller],eventName)1. CREATETicketSellerActorSystem(“goticks”)ActorSystem(“goticks”)REST InterfaceBoxOfficeTicketSellerTicket sellers are named by event
  43. 43. 2. SEND/RECEIVE
  44. 44. Receiving messagesclass BoxOffice extends Actor {def receive = {case TicketRequest(name) =>…case GetEvents =>…case event: Event =>…}}Pattern MatchingOn Messages
  45. 45. Receiving messagesclass TicketSeller extends Actor {def receive = soldOutdef soldOut:Receive = {case Tickets(newTickets) =>.. //store new ticketsbecome(selling)}def selling:Receive = {case BuyTicket(name) =>…}}Partial Function3. BECOME:You can change thbehavior atevery msg
  46. 46. Create EventActorSystem(“goticks”)ActorSystem(“goticks”)REST InterfaceBoxOfficeEvent(“RHCP”, 250){ event: “RHCP” nrOfTickets: 250}Inside RestInterface… (receives JSON, unmarshall to event)boxOffice ! event
  47. 47. Create EventActorSystem(“goticks”)ActorSystem(“goticks”)REST InterfaceBoxOfficeEvent(“RHCP”, 250){ event: “RHCP” nrOfTickets: 250}Inside RestInterface… (receives JSON, unmarshall to event)boxOffice ! eventBang Operator„Tell‟„One-way‟
  48. 48. ActorSystem(“goticks”)ActorSystem(“goticks”)REST InterfaceBoxOfficeEvent(“RHCP”, 250){ event: “RHCP” nrOfTickets: 250}Inside RestInterface…boxOffice ! eventReceiver can respondto „sender‟Send EventTo BoxOffice
  49. 49. ActorSystem(“goticks”)ActorSystem(“goticks”)REST InterfaceBoxOfficeEventCreatedInside BoxOffice…sender ! EventCreatedRespond withEventCreated,results in OKHTTP OK
  50. 50. ActorSystem(“goticks”)ActorSystem(“goticks”)REST InterfaceBoxOffice{ event: “RHCP” nrOfTickets: 250}BuyTicketTicketSellerInside BoxOffice…ticketSeller forward BuyTicketGet a TicketForward keeps sender(RestInterface)TicketRequest(“RHCP”)
  51. 51. ActorSystem(“goticks”)ActorSystem(“goticks”)REST InterfaceBoxOffice{ event: “RHCP”, nr :1}TicketSellerInside TicketSeller…sender ! ticketRespond tooriginal senderBuyTicketTicket(“RHCP”, 1)
  52. 52. CODE
  53. 53. Questions?@RayRoestenburgrroestenburg@xebia.comwww.xebia.comgithub.com/RayRoestenburg/xebicon
  54. 54. Backup slides
  55. 55. “Async sending subscriptiondata”SendThread XConsumerConsumerConsumerThread 1Thread 2Thread 1Service A
  56. 56. SendThread XConsumerConsumerConsumerThread 1Thread 2Thread 1Service AThread 2 fails
  57. 57. SendThread XConsumerConsumerConsumerThread 1Thread 2Thread 1Service AThread 2 failsHandle every possible errorinside Thread 2, never fail?Not completely under your control.
  58. 58. SendThread XConsumerConsumerConsumerThread 1Thread 2Thread 1Service AThread 2 failsRestart / Stop?Monitor?Handle errorsacross all subscriptions?
  59. 59. 4. Supervise*Untangle behavior and errors„Just Reboot‟Let It Crash ™Error Kernel
  60. 60. 4. Supervise*StrategiesOne for One(Poison Pill /Seppuku)All for One
  61. 61. 4. Supervise*val supervisorStrategy =OneForOneStrategy(maxNrOfRetries = 5,withinTimeRange = 1 minute) {case _: Exception => Restart}
  62. 62. 4. Supervise*val supervisorStrategy =OneForOneStrategy(maxNrOfRetries = 5,withinTimeRange = 1 minute) {case _: Exception => Restart}Restart,Resume,Escalate,Stop,

×