SlideShare a Scribd company logo
1 of 29
Concurrent programming with Agents
Tomáš Petříček
http://tomasp.net/blog
http://twitter.com/tomaspetricek
Introducing agents
Inside agent’s brain
Inter-agent communication
Reusable agents
Intelligence networks
Sequential programs
Task based parallelism
Agent-based concurrency
Agent-based concurrency
Programs compose from agents
Instead of functions or objects
Agents exchange messages
Receive message and react
Reactive system
Handle inputs while running
Emit results while running
Example
Introducing agents
Simple chat room
Functional loop with single state
Single state
Same reaction to all messages
Implemented using recursive loop
What if reaction depends on the state?
What if agent cannot handle some message?
Immutable state
Maintained as parameter of recursive function
Can use mutable collections for performance
Hiding agent’s brain
Accessing agent directly
Exposes implementation details
Users can call wrong methods (e.g. Receive)
Encapsulating agent
Agent as a private filed
Add methods for all (public) messages
Expose asynchronous calls first
Example
Encapsulating agent into an object
Exposing chat room via HTTP
Hiding agent’s brain
 Asynchronous calls from F#
 Synchronous calls from F# (optional)
 Asynchronous calls from C# (task based)
member x.AsyncGetContent(?timeout) =
agent.PostAndAsyncReply(GetContent, ?timeout=timeout)
member x.GetContent(?timeout) =
agent.PostAndReply(GetContent, ?timeout=timeout)
member x.GetContentAsync() =
Async.StartAsTask(agent.PostAndAsyncReply(GetContent))
member x.GetContentAsync(cancellationToken) =
Async.StartAsTask(agent.PostAndAsyncReply(GetContent),
cancellationToken=cancellationToken)
Introducing agents
Inside agent’s brain
Inter-agent communication
Reusable agents
Intelligence networks
Inside agent’s brain
Single state
Accept and react
to all messages
Example: Twitter status agent with pause
Resume
Pause
d
Running
Resume Status
Pause
Multiple states
Agent implements a
state machine
Example
Reading statuses from Twitter
Pausing the stream using blocking agent
State and state transitions
Accepting all messages
Asynchronously Receive and use pattern matching
Waiting for specific message
Other messages stay in the queue
Writing message handling using Scan
let rec state = agent.Scan(function
| Message -> Some <| async {
handleMessage()
return! newState }
| _ -> None )
Introducing agents
Inside agent’s brain
Inter-agent communication
Reusable agents
Intelligence networks
Inter-agent communication
Direct links between agents
Complicates reusability and reconfiguration
Decoupling using events
Expose event instead of sending message
We used events in the previous example!
Types of agent’s members
Send message to the agent
Members of type: 'T -> unit
Notifications from the agent
Exposed as events or observables: IObservable<'T>
No synchronization and no thread guarantees
Send and wait for a reply
Uses asynchronous reply channels from F# library
Takes arguments and returns result: 'T -> Async<'R>
Connecting agents
Sending message in response to notification
Alternatively, Observable.subscribe supports removal
Connecting agents with asynchronous actions
Create and start asynchronous workflow
source.Notification |> Observable.add target.Action
async { while true do
let! value = source.AsyncAction()
do! target.Action(value) }
|> Async.Start
Introducing agents
Inside agent’s brain
Inter-agent communication
Reusable agents
Intelligence networks
Reusable agents I.
Aggregating messages into bulks
Bulk specified number of messages
Emit bulk after timeout
Uses of bulking agent
Grouping data for further processing
Writing live data to a database
new BulkingAgent : int -> int -> BulkingAgent
member Enqueue : 'T -> unit
member BulkProduced : Event<'T[]>
Example
Bulk processing of Twitter statuses
A look at the BulkingAgent implementation
Reusable agents II.
Blocking queue with limited size
Block reader when queue is empty
Block adder when queue is full
Uses of blocking queue agent
The producer consumer pattern
Immediate buffer in pipeline processing
new BlockingQueueAgent : int -> BlockingQueueAgent
member AsyncGet : unit -> Async<'T>
member AsyncAdd : 'T -> Async<unit>
Introducing agents
Inside agent’s brain
Inter-agent communication
Reusable agents
Intelligence networks
Managing intelligence network
 Lots of things going on!
How to keep a big picture?
Using loosely coupled connections
Agents don’t reference each other directly
Common ways of organizing agents
Worker agent – Single agent does all the work
Layered network – Agent uses agents from lower level
Pipeline processing – Step-by-step processing
Pipeline processing
Values processed in multiple steps
Worker takes value, processes it, and sends it
Worker is blocked when source is empty
Worker is blocked when target is full
Steps of the pipeline run in parallel
Example
Pipeline image processing
Summary
Why use agent-based concurrency?
Easy to understand reactive applications
Elegant implementation of concurrent patterns
How to write an agent-based application?
State machine using recursive functions
Encapsulate and provide communication points
(send and send & reply methods and notifications)
Use reusable agents for recurring patterns
Questions?
Email: tomas@tomasp.net
Blog: http://tomasp.net/blog
Twitter: http://twitter.com/tomaspetricek
My book: http://functional-programming.net

More Related Content

Similar to Concurrent programming with Agents

Oop2011 actor presentation_stal
Oop2011 actor presentation_stalOop2011 actor presentation_stal
Oop2011 actor presentation_stalMichael Stal
 
Architectural Patterns - Interactive and Event Handling Patterns
Architectural Patterns  - Interactive and Event Handling PatternsArchitectural Patterns  - Interactive and Event Handling Patterns
Architectural Patterns - Interactive and Event Handling Patternsassinha
 
Web Services 8
Web Services 8Web Services 8
Web Services 8pradeepfdo
 
Delegates and events
Delegates and eventsDelegates and events
Delegates and eventsIblesoft
 
Design patterns - ICIN 2010
Design patterns - ICIN 2010Design patterns - ICIN 2010
Design patterns - ICIN 2010steccami
 
Restate: Event-driven Asynchronous Services, Easy as Synchronous RPC
Restate: Event-driven Asynchronous Services, Easy as Synchronous RPCRestate: Event-driven Asynchronous Services, Easy as Synchronous RPC
Restate: Event-driven Asynchronous Services, Easy as Synchronous RPCHostedbyConfluent
 
Design Pattern with Actionscript
Design Pattern with ActionscriptDesign Pattern with Actionscript
Design Pattern with ActionscriptDaniel Swid
 
Android 101 Session @thejunction32
Android 101 Session @thejunction32Android 101 Session @thejunction32
Android 101 Session @thejunction32Eden Shochat
 
Distributed Objects and Remote Invocation
Distributed Objects and Remote InvocationDistributed Objects and Remote Invocation
Distributed Objects and Remote InvocationMedicaps University
 
Task communication
Task communicationTask communication
Task communication1jayanti
 
Ddd melbourne 2011 C# async ctp
Ddd melbourne 2011  C# async ctpDdd melbourne 2011  C# async ctp
Ddd melbourne 2011 C# async ctpPratik Khasnabis
 
Intention Oriented Model Interaction
Intention Oriented Model InteractionIntention Oriented Model Interaction
Intention Oriented Model InteractionYasir Karam
 

Similar to Concurrent programming with Agents (20)

Oop2011 actor presentation_stal
Oop2011 actor presentation_stalOop2011 actor presentation_stal
Oop2011 actor presentation_stal
 
Architectural Patterns - Interactive and Event Handling Patterns
Architectural Patterns  - Interactive and Event Handling PatternsArchitectural Patterns  - Interactive and Event Handling Patterns
Architectural Patterns - Interactive and Event Handling Patterns
 
Web Services 8
Web Services 8Web Services 8
Web Services 8
 
IoT in salsa Serverless
IoT in salsa ServerlessIoT in salsa Serverless
IoT in salsa Serverless
 
Akka framework
Akka frameworkAkka framework
Akka framework
 
Delegates and events
Delegates and eventsDelegates and events
Delegates and events
 
Windows 8 BootCamp
Windows 8 BootCampWindows 8 BootCamp
Windows 8 BootCamp
 
Design patterns - ICIN 2010
Design patterns - ICIN 2010Design patterns - ICIN 2010
Design patterns - ICIN 2010
 
Event driven systems
Event driven systems Event driven systems
Event driven systems
 
Sysprog 10
Sysprog 10Sysprog 10
Sysprog 10
 
Sysprog 10
Sysprog 10Sysprog 10
Sysprog 10
 
Restate: Event-driven Asynchronous Services, Easy as Synchronous RPC
Restate: Event-driven Asynchronous Services, Easy as Synchronous RPCRestate: Event-driven Asynchronous Services, Easy as Synchronous RPC
Restate: Event-driven Asynchronous Services, Easy as Synchronous RPC
 
Design Pattern with Actionscript
Design Pattern with ActionscriptDesign Pattern with Actionscript
Design Pattern with Actionscript
 
Distributed System
Distributed System Distributed System
Distributed System
 
Android 101 Session @thejunction32
Android 101 Session @thejunction32Android 101 Session @thejunction32
Android 101 Session @thejunction32
 
Asynchronyin net
Asynchronyin netAsynchronyin net
Asynchronyin net
 
Distributed Objects and Remote Invocation
Distributed Objects and Remote InvocationDistributed Objects and Remote Invocation
Distributed Objects and Remote Invocation
 
Task communication
Task communicationTask communication
Task communication
 
Ddd melbourne 2011 C# async ctp
Ddd melbourne 2011  C# async ctpDdd melbourne 2011  C# async ctp
Ddd melbourne 2011 C# async ctp
 
Intention Oriented Model Interaction
Intention Oriented Model InteractionIntention Oriented Model Interaction
Intention Oriented Model Interaction
 

More from Tomas Petricek

Coeffects: A Calculus of Context-Dependent Computation
Coeffects: A Calculus of Context-Dependent ComputationCoeffects: A Calculus of Context-Dependent Computation
Coeffects: A Calculus of Context-Dependent ComputationTomas Petricek
 
Domain Specific Languages: The Functional Way
Domain Specific Languages: The Functional WayDomain Specific Languages: The Functional Way
Domain Specific Languages: The Functional WayTomas Petricek
 
F# Data: Making structured data first class citizens
F# Data: Making structured data first class citizensF# Data: Making structured data first class citizens
F# Data: Making structured data first class citizensTomas Petricek
 
Doing data science with F# (BuildStuff)
Doing data science with F# (BuildStuff)Doing data science with F# (BuildStuff)
Doing data science with F# (BuildStuff)Tomas Petricek
 
Doing data science with F#
Doing data science with F#Doing data science with F#
Doing data science with F#Tomas Petricek
 
F# and Financial Data Making Data Analysis Simple
F# and Financial Data Making Data Analysis SimpleF# and Financial Data Making Data Analysis Simple
F# and Financial Data Making Data Analysis SimpleTomas Petricek
 
Creating Domain Specific Languages in F#
Creating Domain Specific Languages in F#Creating Domain Specific Languages in F#
Creating Domain Specific Languages in F#Tomas Petricek
 
How F# Learned to Stop Worrying and Love the Data
How F# Learned to Stop Worrying and Love the DataHow F# Learned to Stop Worrying and Love the Data
How F# Learned to Stop Worrying and Love the DataTomas Petricek
 
Information-rich programming in F# (ML Workshop 2012)
Information-rich programming in F# (ML Workshop 2012)Information-rich programming in F# (ML Workshop 2012)
Information-rich programming in F# (ML Workshop 2012)Tomas Petricek
 
F# Type Providers in Depth
F# Type Providers in DepthF# Type Providers in Depth
F# Type Providers in DepthTomas Petricek
 
Asynchronous programming in F# (QCon 2012)
Asynchronous programming in F# (QCon 2012)Asynchronous programming in F# (QCon 2012)
Asynchronous programming in F# (QCon 2012)Tomas Petricek
 
Queries in general purpose languages
Queries in general purpose languagesQueries in general purpose languages
Queries in general purpose languagesTomas Petricek
 
Docase notation for Haskell
Docase notation for HaskellDocase notation for Haskell
Docase notation for HaskellTomas Petricek
 
Accessing loosely structured data from F# and C#
Accessing loosely structured data from F# and C#Accessing loosely structured data from F# and C#
Accessing loosely structured data from F# and C#Tomas Petricek
 

More from Tomas Petricek (19)

Coeffects: A Calculus of Context-Dependent Computation
Coeffects: A Calculus of Context-Dependent ComputationCoeffects: A Calculus of Context-Dependent Computation
Coeffects: A Calculus of Context-Dependent Computation
 
Domain Specific Languages: The Functional Way
Domain Specific Languages: The Functional WayDomain Specific Languages: The Functional Way
Domain Specific Languages: The Functional Way
 
F# Data: Making structured data first class citizens
F# Data: Making structured data first class citizensF# Data: Making structured data first class citizens
F# Data: Making structured data first class citizens
 
Doing data science with F# (BuildStuff)
Doing data science with F# (BuildStuff)Doing data science with F# (BuildStuff)
Doing data science with F# (BuildStuff)
 
Doing data science with F#
Doing data science with F#Doing data science with F#
Doing data science with F#
 
F# and Financial Data Making Data Analysis Simple
F# and Financial Data Making Data Analysis SimpleF# and Financial Data Making Data Analysis Simple
F# and Financial Data Making Data Analysis Simple
 
Creating Domain Specific Languages in F#
Creating Domain Specific Languages in F#Creating Domain Specific Languages in F#
Creating Domain Specific Languages in F#
 
How F# Learned to Stop Worrying and Love the Data
How F# Learned to Stop Worrying and Love the DataHow F# Learned to Stop Worrying and Love the Data
How F# Learned to Stop Worrying and Love the Data
 
Information-rich programming in F# (ML Workshop 2012)
Information-rich programming in F# (ML Workshop 2012)Information-rich programming in F# (ML Workshop 2012)
Information-rich programming in F# (ML Workshop 2012)
 
F# Type Providers in Depth
F# Type Providers in DepthF# Type Providers in Depth
F# Type Providers in Depth
 
Asynchronous programming in F# (QCon 2012)
Asynchronous programming in F# (QCon 2012)Asynchronous programming in F# (QCon 2012)
Asynchronous programming in F# (QCon 2012)
 
Queries in general purpose languages
Queries in general purpose languagesQueries in general purpose languages
Queries in general purpose languages
 
Docase notation for Haskell
Docase notation for HaskellDocase notation for Haskell
Docase notation for Haskell
 
Accessing loosely structured data from F# and C#
Accessing loosely structured data from F# and C#Accessing loosely structured data from F# and C#
Accessing loosely structured data from F# and C#
 
F# on the Server-Side
F# on the Server-SideF# on the Server-Side
F# on the Server-Side
 
F# Tutorial @ QCon
F# Tutorial @ QConF# Tutorial @ QCon
F# Tutorial @ QCon
 
Teaching F#
Teaching F#Teaching F#
Teaching F#
 
F# in MonoDevelop
F# in MonoDevelopF# in MonoDevelop
F# in MonoDevelop
 
Academia
AcademiaAcademia
Academia
 

Recently uploaded

The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 

Recently uploaded (20)

The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 

Concurrent programming with Agents

  • 1. Concurrent programming with Agents Tomáš Petříček http://tomasp.net/blog http://twitter.com/tomaspetricek
  • 2. Introducing agents Inside agent’s brain Inter-agent communication Reusable agents Intelligence networks
  • 6. Agent-based concurrency Programs compose from agents Instead of functions or objects Agents exchange messages Receive message and react Reactive system Handle inputs while running Emit results while running
  • 8. Functional loop with single state Single state Same reaction to all messages Implemented using recursive loop What if reaction depends on the state? What if agent cannot handle some message? Immutable state Maintained as parameter of recursive function Can use mutable collections for performance
  • 9. Hiding agent’s brain Accessing agent directly Exposes implementation details Users can call wrong methods (e.g. Receive) Encapsulating agent Agent as a private filed Add methods for all (public) messages Expose asynchronous calls first
  • 10. Example Encapsulating agent into an object Exposing chat room via HTTP
  • 11. Hiding agent’s brain  Asynchronous calls from F#  Synchronous calls from F# (optional)  Asynchronous calls from C# (task based) member x.AsyncGetContent(?timeout) = agent.PostAndAsyncReply(GetContent, ?timeout=timeout) member x.GetContent(?timeout) = agent.PostAndReply(GetContent, ?timeout=timeout) member x.GetContentAsync() = Async.StartAsTask(agent.PostAndAsyncReply(GetContent)) member x.GetContentAsync(cancellationToken) = Async.StartAsTask(agent.PostAndAsyncReply(GetContent), cancellationToken=cancellationToken)
  • 12. Introducing agents Inside agent’s brain Inter-agent communication Reusable agents Intelligence networks
  • 13. Inside agent’s brain Single state Accept and react to all messages Example: Twitter status agent with pause Resume Pause d Running Resume Status Pause Multiple states Agent implements a state machine
  • 14. Example Reading statuses from Twitter Pausing the stream using blocking agent
  • 15. State and state transitions Accepting all messages Asynchronously Receive and use pattern matching Waiting for specific message Other messages stay in the queue Writing message handling using Scan let rec state = agent.Scan(function | Message -> Some <| async { handleMessage() return! newState } | _ -> None )
  • 16. Introducing agents Inside agent’s brain Inter-agent communication Reusable agents Intelligence networks
  • 17. Inter-agent communication Direct links between agents Complicates reusability and reconfiguration Decoupling using events Expose event instead of sending message We used events in the previous example!
  • 18. Types of agent’s members Send message to the agent Members of type: 'T -> unit Notifications from the agent Exposed as events or observables: IObservable<'T> No synchronization and no thread guarantees Send and wait for a reply Uses asynchronous reply channels from F# library Takes arguments and returns result: 'T -> Async<'R>
  • 19. Connecting agents Sending message in response to notification Alternatively, Observable.subscribe supports removal Connecting agents with asynchronous actions Create and start asynchronous workflow source.Notification |> Observable.add target.Action async { while true do let! value = source.AsyncAction() do! target.Action(value) } |> Async.Start
  • 20. Introducing agents Inside agent’s brain Inter-agent communication Reusable agents Intelligence networks
  • 21. Reusable agents I. Aggregating messages into bulks Bulk specified number of messages Emit bulk after timeout Uses of bulking agent Grouping data for further processing Writing live data to a database new BulkingAgent : int -> int -> BulkingAgent member Enqueue : 'T -> unit member BulkProduced : Event<'T[]>
  • 22. Example Bulk processing of Twitter statuses A look at the BulkingAgent implementation
  • 23. Reusable agents II. Blocking queue with limited size Block reader when queue is empty Block adder when queue is full Uses of blocking queue agent The producer consumer pattern Immediate buffer in pipeline processing new BlockingQueueAgent : int -> BlockingQueueAgent member AsyncGet : unit -> Async<'T> member AsyncAdd : 'T -> Async<unit>
  • 24. Introducing agents Inside agent’s brain Inter-agent communication Reusable agents Intelligence networks
  • 25. Managing intelligence network  Lots of things going on! How to keep a big picture? Using loosely coupled connections Agents don’t reference each other directly Common ways of organizing agents Worker agent – Single agent does all the work Layered network – Agent uses agents from lower level Pipeline processing – Step-by-step processing
  • 26. Pipeline processing Values processed in multiple steps Worker takes value, processes it, and sends it Worker is blocked when source is empty Worker is blocked when target is full Steps of the pipeline run in parallel
  • 28. Summary Why use agent-based concurrency? Easy to understand reactive applications Elegant implementation of concurrent patterns How to write an agent-based application? State machine using recursive functions Encapsulate and provide communication points (send and send & reply methods and notifications) Use reusable agents for recurring patterns
  • 29. Questions? Email: tomas@tomasp.net Blog: http://tomasp.net/blog Twitter: http://twitter.com/tomaspetricek My book: http://functional-programming.net