Slide 1

Slide 1 text

Tony Arcieri JRubyConf May 23rd, 2012 Concurrent programming with http://celluloid.io

Slide 2

Slide 2 text

About Me

Slide 3

Slide 3 text

About Me libev binding for Ruby (1 year before Node)

Slide 4

Slide 4 text

About Me Actors +“Fibered” I/O (2 years before em-synchrony)

Slide 5

Slide 5 text

About Me Ruby-Flavored Erlang (2 years before Elixir)

Slide 6

Slide 6 text

http://elixir-lang.org/

Slide 7

Slide 7 text

What next?

Slide 8

Slide 8 text

No content

Slide 9

Slide 9 text

No content

Slide 10

Slide 10 text

If I can’t drag Erlang halfway to Ruby...

Slide 11

Slide 11 text

Perhaps I can get Ruby halfway to Erlang...

Slide 12

Slide 12 text

Rubyists don’t like threads I want to change that

Slide 13

Slide 13 text

x86 CPU Trends (Not Entirely to Scale)

Slide 14

Slide 14 text

AMD Bulldozer 1 CPU = 16 Cores

Slide 15

Slide 15 text

Multicore is the future

Slide 16

Slide 16 text

Threads are important

Slide 17

Slide 17 text

No GIL! Thread-level parallelism Threads = Multicore

Slide 18

Slide 18 text

When everyone has 100 core CPUs...

Slide 19

Slide 19 text

will we run 100 virtual machines?

Slide 20

Slide 20 text

or one?

Slide 21

Slide 21 text

Sidekiq What if 1 Sidekiq process could do the work of 20 Resque processes? http://mperham.github.com/sidekiq/

Slide 22

Slide 22 text

What is Celluloid?

Slide 23

Slide 23 text

Celluloid is a general purpose concurrency framework for Ruby built on the Actor Model

Slide 24

Slide 24 text

“Akka for Ruby”

Slide 25

Slide 25 text

...but not quite •Designed from the ground up around Ruby and OOP •Conceptually harmonious and simple! •More advanced object model •Not quite as mature :|

Slide 26

Slide 26 text

Less Boilerplate package typedactordemo import akka.actor._ import akka.dispatch.Future import akka.pattern.ask import akka.util.Timeout import akka.util.duration._ case class Request(payload: String) case class Response(payload: String) trait Service { def request(r: Request): Future[Response] } class ServiceImpl extends Service { val actor = { val ctx = TypedActor.context ctx.actorOf(Props[ServiceActor]) } implicit val timeout = Timeout(10 seconds) def request(req: Request): Future[Response] = (actor ? req).mapTo[Response] } class ServiceActor extends Actor { def receive = { case Request(payload) => sender ! Response(payload) } } object Main extends App { val system = ActorSystem("TypedActorDemo") val service: Service = TypedActor(system).typedActorOf( TypedProps[ServiceImpl]() ) val req = Request("hello world!") service.request(req) onSuccess { case Response(response) => println(response) system.shutdown() } }

Slide 27

Slide 27 text

Less Boilerplate require 'celluloid' class Greeter include Celluloid def greet(msg) puts msg end end Greeter.new.greet "hello world!"

Slide 28

Slide 28 text

What is the Actor Model?

Slide 29

Slide 29 text

Actor Model •Actors are computational entities that can receive messages •Each actor has a unique address •If you know an actor’s address, you can send it messages •Actors can create new actors

Slide 30

Slide 30 text

How is that different from an object?

Slide 31

Slide 31 text

Actors are concurrent Each actor has its own thread in Celluloid

Slide 32

Slide 32 text

Actors are asynchronous

Slide 33

Slide 33 text

Celluloid is an abstraction on top of the Actor Model

Slide 34

Slide 34 text

Actor-based Concurrent Objects

Slide 35

Slide 35 text

“Cells”

Slide 36

Slide 36 text

A Contrived Example

Slide 37

Slide 37 text

require 'thread' class ConcurrentNestedHash def initialize @outer = {} @mutex = Mutex.new end def [](*keys) @mutex.synchronize { keys.inject(@outer) { |h,k| h[k] } } end def []=(*args) @mutex.synchronize do value = args.pop raise ArgumentError, "wrong number of arguments (1 for 2)" if args.empty? key = args.pop hash = args.inject(@outer) { |h,k| h[k] ||= {} } hash[key] = value end end def inspect; @mutex.synchronize { super }; end end

Slide 38

Slide 38 text

>> h = ConcurrentNestedHash.new => #> >> h[:foo, :bar, :baz] = 42 => 42 >> h => #{:bar=>{:baz=>42}}}, @mutex=#> >> h[:foo, :bar, :baz] => 42

Slide 39

Slide 39 text

-require 'thread' +require 'celluloid' class ConcurrentNestedHash + include Celluloid def initialize @outer = {} - @mutex = Mutex.new end def [](*keys) - @mutex.synchronize { keys.inject(@outer) { |h,k| h[k] } } + keys.inject(@outer) { |h,k| h[k] } end def []=(*args) - @mutex.synchronize do value = args.pop raise ArgumentError, "wrong number of arguments (1 for 2)" if args.empty? key = args.pop hash = args.inject(@outer) { |h,k| h[k] ||= {} } hash[key] = value - end end - - def inspect; @mutex.synchronize { super }; end end

Slide 40

Slide 40 text

require 'celluloid' class ConcurrentNestedHash include Celluloid def initialize @outer = {} end def [](*keys) keys.inject(@outer) { |h,k| h[k] } end def []=(*args) value = args.pop raise ArgumentError, "wrong number of arguments (1 for 2)" if args.empty? key = args.pop hash = args.inject(@outer) { |h,k| h[k] ||= {} } hash[key] = value end end

Slide 41

Slide 41 text

How?

Slide 42

Slide 42 text

MAGIC

Slide 43

Slide 43 text

Automatic locking?

Slide 44

Slide 44 text

No content

Slide 45

Slide 45 text

No content

Slide 46

Slide 46 text

Locks are hard •Dining Philosophers Problem •Sleeping Barber Problem •Cigarette Smokers Problem

Slide 47

Slide 47 text

OOP + Concurrency

Slide 48

Slide 48 text

“I thought of objects being like biological cells and/or individual computers on a network, only able to communicate with messages” - Alan Kay, creator of Smalltalk, on the meaning of "object oriented programming"

Slide 49

Slide 49 text

OOP Tools Classes Inheritance Messages

Slide 50

Slide 50 text

Concurrency Tools Threads Locks Queues

Slide 51

Slide 51 text

OOP Tools Classes Inheritance Messages Concurrency Tools Threads Locks Queues +

Slide 52

Slide 52 text

=

Slide 53

Slide 53 text

Concurrent Objects &DOOHU &HOOXORLG $FWRU3UR[\ &$// 5HFHLYHU &HOOXORLG 0DLOER[ 5(63216( &HOOXORLG 0DLOER[ &HOOXORLG$FWRU &HOOXORLG&DOO &HOOXORLG5HVSRQVH

Slide 54

Slide 54 text

Communicating Sequential Processes •Do One Thing At a Time •Communicate With Messages •Encapsulate Local State

Slide 55

Slide 55 text

Concurrent Objects do more...

Slide 56

Slide 56 text

Generalized Deadlock-free Synchronization

Slide 57

Slide 57 text

No content

Slide 58

Slide 58 text

No content

Slide 59

Slide 59 text

No content

Slide 60

Slide 60 text

No content

Slide 61

Slide 61 text

No content

Slide 62

Slide 62 text

Pythons did it!

Slide 63

Slide 63 text

No content

Slide 64

Slide 64 text

1997

Slide 65

Slide 65 text

No content

Slide 66

Slide 66 text

How does Celluloid work?

Slide 67

Slide 67 text

>> h = ConcurrentNestedHash.new => #

Slide 68

Slide 68 text

>> h = ConcurrentNestedHash.new => #

Slide 69

Slide 69 text

# Class methods added to classes which include Celluloid module ClassMethods # Create a new actor def new(*args, &block) proxy = Actor.new(allocate).proxy proxy._send_(:initialize, *args, &block) proxy end ...

Slide 70

Slide 70 text

Synchronous Calls

Slide 71

Slide 71 text

EXTREME Late Binding &DOOHU &HOOXORLG $FWRU3UR[\ &$// 5HFHLYHU &HOOXORLG 0DLOER[ 5(63216( &HOOXORLG 0DLOER[ &HOOXORLG$FWRU &HOOXORLG&DOO &HOOXORLG5HVSRQVH

Slide 72

Slide 72 text

>> h = ConcurrentNestedHash.new => # >> h.inspect => “#” Synchronous Calls

Slide 73

Slide 73 text

Asynchronous Calls

Slide 74

Slide 74 text

Asynchronous Calls &DOOHU &HOOXORLG $FWRU3UR[\ &$// 5HFHLYHU &HOOXORLG 0DLOER[ &HOOXORLG$FWRU &HOOXORLG&DOO

Slide 75

Slide 75 text

Asynchronous Calls >> h = ConcurrentNestedHash.new => # >> h.send!(:[]=, :foo, :bar, :baz, 42) => nil >> h[:foo, :bar, :baz] => 42

Slide 76

Slide 76 text

>> h = ConcurrentNestedHash.new => # >> h.send!(:[]=, :foo, :bar, :baz, 42) => nil >> h[:foo, :bar, :baz] => 42 Asynchronous Calls

Slide 77

Slide 77 text

Asynchronous Calls >> h.inspect! => nil

Slide 78

Slide 78 text

Asynchronous Calls Kind of like “next tick”

Slide 79

Slide 79 text

Asynchronous Calls How do I get the value returned?

Slide 80

Slide 80 text

Futures

Slide 81

Slide 81 text

Futures &DOOHU &HOOXORLG $FWRU3UR[\ 5HFHLYHU &HOOXORLG 0DLOER[ &HOOXORLG$FWRU &HOOXORLG&DOO &$// &HOOXORLG 0DLOER[ )8785( &HOOXORLG )XWXUH &HOOXORLG5HVSRQVH 9$/8(" 9$/8(

Slide 82

Slide 82 text

>> h = ConcurrentNestedHash.new => # >> future = h.future :inspect => # >> 41 + 1 # roflscale computation => 42 >> future.value => “#” Futures

Slide 83

Slide 83 text

>> h = ConcurrentNestedHash.new => # >> future = h.future :inspect => # >> 41 + 1 # roflscale computation => 42 >> future.value => “#” Futures

Slide 84

Slide 84 text

Basic Ingredients •Regular method calls •Async calls (“next tick”) •Futures

Slide 85

Slide 85 text

Secret Sauce

Slide 86

Slide 86 text

How do we prevent deadlocks?

Slide 87

Slide 87 text

No content

Slide 88

Slide 88 text

No content

Slide 89

Slide 89 text

No content

Slide 90

Slide 90 text

No content

Slide 91

Slide 91 text

No content

Slide 92

Slide 92 text

Why do deadlocks happen?

Slide 93

Slide 93 text

Waiting for something that never happens...

Slide 94

Slide 94 text

...instead of what’s important

Slide 95

Slide 95 text

No content

Slide 96

Slide 96 text

How can we wait on everything at once?

Slide 97

Slide 97 text

FIBERS!

Slide 98

Slide 98 text

Communicating Sequential Processes Do one thing at a time

Slide 99

Slide 99 text

Fibers Cheap suspendable/resumable execution context

Slide 100

Slide 100 text

Fibers Cheap suspendable/resumable execution context Communicating Sequential Processes Do one thing at a time +

Slide 101

Slide 101 text

Internal Concurrency for Actors

Slide 102

Slide 102 text

Don’t Block, Suspend to the Scheduler

Slide 103

Slide 103 text

Example!

Slide 104

Slide 104 text

require 'celluloid' class Person include Celluloid def name self.class.to_s end def greet(interested_party) "Hello #{interested_party.name}, I'm #{name}" end end class Joe < Person; end class Mike < Person def greet(other) super << "\n" << other.greet(current_actor) end end mike = Mike.new joe = Joe.new puts mike.greet(joe)

Slide 105

Slide 105 text

Hello Joe, I'm Mike Hello Mike, I'm Joe Output

Slide 106

Slide 106 text

No content

Slide 107

Slide 107 text

But it is a cool story!

Slide 108

Slide 108 text

Circular Call Graph 0LNH -RH JUHHW QDPH

Slide 109

Slide 109 text

Communicating Sequential Processes Do one thing at a time

Slide 110

Slide 110 text

DEADLOCK!

Slide 111

Slide 111 text

require 'celluloid' class Person include Celluloid def name self.class.to_s end def greet(interested_party) "Hello #{interested_party.name}, I'm #{name}" end end class Joe < Person; end class Mike < Person def greet(other) super << "\n" << other.greet(current_actor) end end mike = Mike.new joe = Joe.new puts mike.greet(joe)

Slide 112

Slide 112 text

0LNH -RH 0LNHJUHHW -RHJUHHW 0LNHQDPH J U H H W + H OO R 0 L N H J U H H W 0 L N H 6XVSHQGHG Multitasking Fibers

Slide 113

Slide 113 text

Waiting tasks suspend themselves so ready tasks can run

Slide 114

Slide 114 text

Every method call creates a Fiber

Slide 115

Slide 115 text

No content

Slide 116

Slide 116 text

Slow?

Slide 117

Slide 117 text

Call Benchmark Core i7 2.0GHz (OS X 10.7.3) 16815/s (60µs) - JRuby 1.6.7 20899/s (50µs) - JRuby HEAD

Slide 118

Slide 118 text

No content

Slide 119

Slide 119 text

JRuby fibers are threads :(

Slide 120

Slide 120 text

Kilim Fast coroutines and actors for the JVM

Slide 121

Slide 121 text

Kilim Fibers •JRuby GSoC project by Miloš Hadžić •“Weave” the JRuby runtime, JIT •Fast, cheap Fibers on JRuby! •50% chance of success :|

Slide 122

Slide 122 text

What if a cell crashes?

Slide 123

Slide 123 text

No content

Slide 124

Slide 124 text

No content

Slide 125

Slide 125 text

Fault Tolerance •Supervisors & Supervision Trees •“Fail early”, restart in a clean state •Do what Erlang does •No seriously, do what Erlang does

Slide 126

Slide 126 text

Distributed Celluloid over 0MQ http://github.com/celluloid/dcell

Slide 127

Slide 127 text

Cells are services

Slide 128

Slide 128 text

DCell exposes them to the network

Slide 129

Slide 129 text

Built on 0MQ •Fast, brokerless message queue •DCell uses push/pull sockets •Built on Celluloid::ZMQ/ffi-rzmq

Slide 130

Slide 130 text

•Distributed process orchestration (e.g. Chef, Puppet) •Multi-tier Web Applications •Asynchronous background jobs Use Cases •Distributed process orchestration (e.g. Chef, Puppet) •Multi-tier Web Applications •Asynchronous background jobs

Slide 131

Slide 131 text

Why do this? )URQW(QG )URQW(QG )URQW(QG 5(67 &OLHQW 5(67 &OLHQW 5(67 &OLHQW 5(67 6HUYLFH 5(67 6HUYLFH 5(67 6HUYLFH 'RPDLQ 2EMHFW 'RPDLQ 2EMHFW 'RPDLQ 2EMHFW 'RPDLQ 2EMHFW 'RPDLQ 2EMHFW 'RPDLQ 2EMHFW 'RPDLQ 2EMHFW 'RPDLQ 2EMHFW 'RPDLQ 2EMHFW

Slide 132

Slide 132 text

Instead of this? )URQW(QG )URQW(QG )URQW(QG 'RPDLQ 2EMHFW 'RPDLQ 2EMHFW 'RPDLQ 2EMHFW 'RPDLQ 2EMHFW 'RPDLQ 2EMHFW 'RPDLQ 2EMHFW 'RPDLQ 2EMHFW 'RPDLQ 2EMHFW 'RPDLQ 2EMHFW

Slide 133

Slide 133 text

"Objects can message objects transparently that live on other machines over the network, and you don't have to worry about the networking gunk, and you don't have to worry about finding them, and you don't have to worry about anything. It's just as if you messaged an object that's right next door." --Steve Jobs describing NeXT Portable Distributed Objects

Slide 134

Slide 134 text

Distributed objects have mostly been a failure

Slide 135

Slide 135 text

Distributed Object Failures •CORBA •SOAP •PDO •RMI •DRB

Slide 136

Slide 136 text

Why?

Slide 137

Slide 137 text

Not asynchronous Huge problem in distributed systems

Slide 138

Slide 138 text

Not built on the Actor Model

Slide 139

Slide 139 text

Actor Model is AWESOME

Slide 140

Slide 140 text

Unifying abstraction for both concurrency and distribution

Slide 141

Slide 141 text

Success!

Slide 142

Slide 142 text

Example

Slide 143

Slide 143 text

Two Node Cluster •Node #1 is “itchy” •Node #2 is “scratchy”

Slide 144

Slide 144 text

“itchy” commands >> require 'dcell' => true >> DCell.start :id => 'itchy', :addr => 'tcp:// 127.0.0.1:7777' I, [2012-05-09T10:20:46.999000 #52416] INFO -- : Connected to itchy => # Note itchy is on port 7777

Slide 145

Slide 145 text

“scratchy” commands >> require 'dcell' => true >> DCell.start :id => 'scratchy', :addr => 'tcp:// 127.0.0.1:7778', :directory => {:id => 'itchy', :addr => 'tcp://127.0.0.1:7777'} I, [2012-05-09T10:26:42.322000 #52555] INFO -- : Connected to itchy I, [2012-05-09T10:26:42.331000 #52555] INFO -- : Connected to scratchy => # Note scratchy is on port 7778

Slide 146

Slide 146 text

itchy isn’t a “server” It’s an entry point

Slide 147

Slide 147 text

Cluster coordination •Gossip protocol (multiple entry points coming soon!) •Paxos (coming soon!) •Zookeeper (coming soon... again!)

Slide 148

Slide 148 text

Finding nodes •DCell::Node[‘itchy’] •DCell::Node.all •DCell.me

Slide 149

Slide 149 text

Finding Remote Cells DCell::Node[‘itchy’][:info]

Slide 150

Slide 150 text

>> info_service = DCell::Node['itchy'][:info] => # >> info_service.uptime => 42 >> info_service.load_averages => [1.08, 0.93, 0.84] >> info_service.distribution => "Mac OS X 10.7.3 (11D50b)" “scratchy” commands

Slide 151

Slide 151 text

Defining DCell services

Slide 152

Slide 152 text

require 'celluloid' class Greeter include Celluloid def hello "Hi" end end Example Cell

Slide 153

Slide 153 text

>> Celluloid::Actor[:greeter] = Greeter.new => # >> Celluloid::Actor[:greeter].hello => "Hi" Naming Cells

Slide 154

Slide 154 text

>> Greeter.supervise_as :greeter => # >> Celluloid::Actor[:greeter].hello => "Hi" Naming Cells

Slide 155

Slide 155 text

>> node = DCell::Node['itchy'] => # >> node[:greeter].hello => "Hi" Calling Cells

Slide 156

Slide 156 text

All Celluloid features supported •Synchronous calls •Asynchronous calls •Futures

Slide 157

Slide 157 text

Celluloid::IO-powered web server http://github.com/celluloid/reel

Slide 158

Slide 158 text

Hello World Benchmark # httperf --num-conns=50 --num-calls=1000 Ruby Version Throughput Latency ------------ ---------- ------- JRuby HEAD 5650 reqs/s (0.2 ms/req) Ruby 1.9.3 5263 reqs/s (0.2 ms/req) JRuby 1.6.7 4303 reqs/s (0.2 ms/req) rbx HEAD 2288 reqs/s (0.4 ms/req)

Slide 159

Slide 159 text

Hello World Comparison Web Server Throughput Latency ---------- ---------- ------- Goliath (0.9.4) 2058 reqs/s (0.5 ms/req) Thin (1.2.11) 7502 reqs/s (0.1 ms/req) Node.js (0.6.5) 11735 reqs/s (0.1 ms/req) Ruby servers on 1.9.3

Slide 160

Slide 160 text

Websockets coming soon!

Slide 161

Slide 161 text

Celluloid-powered Web Framework http://github.com/celluloid/lattice

Slide 162

Slide 162 text

Vaporware!

Slide 163

Slide 163 text

Goals •Built out of parts of Rails •Webmachine for resources •Multithreaded development mode •Easy scatter/gather for SOA

Slide 164

Slide 164 text

That’s all, folks!

Slide 165

Slide 165 text

Twitter: @bascule Celluloid: celluloid.io Blog: unlimitednovelty.com

Slide 166

Slide 166 text

Links •http://github.com/celluloid •http://twitter.com/bascule •http://unlimitednovelty.com/