Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 37 ยท Async and Concurrency

MailboxProcessor and Agents

Learn F# agents with MailboxProcessor: posting messages, receive loops, replying with PostAndReply, keeping state without locks, error handling, and a safe counter and cache example.

Locks protect shared state, but they are hard to get right: forget one and you have a race, take two in the wrong order and you have a deadlock. A different model removes the problem by design: give the state to one worker, and let everybody else talk to it by sending messages. The worker handles one message at a time, so its state is never touched by two threads at once. This is the actor or agent model, and F# has it in the standard library as MailboxProcessor.

A first agent

FSHARP
type Message =
    | Add of int
    | Reset

let counter =
    MailboxProcessor.Start(fun inbox ->
        let rec loop total =
            async {
                let! msg = inbox.Receive()
                match msg with
                | Add n ->
                    let newTotal = total + n
                    printfn "total = %d" newTotal
                    return! loop newTotal
                | Reset ->
                    printfn "reset"
                    return! loop 0
            }
        loop 0)

counter.Post (Add 5)
counter.Post (Add 10)
counter.Post Reset

Read this in three parts.

  1. Messages are a discriminated union (Discriminated Unions) describing everything the agent understands.
  2. The body receives an inbox. inbox.Receive() waits asynchronously for the next message and releases the thread while waiting.
  3. The loop is a recursive async function whose parameter is the state. Handling a message ends with return! loop newState, which carries the new state into the next iteration. No variable is mutated anywhere.

Post is fire-and-forget: it queues the message and returns immediately. The queue is unbounded and ordered, so messages from one sender are processed in the order they were sent.

C# C# stand-in: an agent built on System.Threading.Channels

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Asking questions: PostAndReply

Often the sender needs an answer. Include a reply channel in the message and use PostAndAsyncReply:

FSHARP
type CounterMsg =
    | Increment
    | Get of AsyncReplyChannel<int>

let agent =
    MailboxProcessor.Start(fun inbox ->
        let rec loop n =
            async {
                match! inbox.Receive() with
                | Increment -> return! loop (n + 1)
                | Get reply ->
                    reply.Reply n
                    return! loop n
            }
        loop 0)

agent.Post Increment
agent.Post Increment
let value = agent.PostAndAsyncReply Get |> Async.RunSynchronously
printfn "%d" value    // 2

match! is shorthand for let! followed by match. PostAndAsyncReply takes a function from the reply channel to a message (Get is exactly that, since the case constructor is a function), sends it and waits for reply.Reply. The synchronous PostAndReply blocks a thread, so prefer the async form. Both accept an optional timeout.

A thread-safe cache

Agents make small shared services easy and race-free:

FSHARP
type CacheMsg<'K, 'V when 'K: comparison> =
    | Put of 'K * 'V
    | TryGet of 'K * AsyncReplyChannel<'V option>

let makeCache<'K, 'V when 'K: comparison> () =
    MailboxProcessor.Start(fun inbox ->
        let rec loop (store: Map<'K, 'V>) =
            async {
                match! inbox.Receive() with
                | Put (k, v) -> return! loop (Map.add k v store)
                | TryGet (k, reply) ->
                    reply.Reply (Map.tryFind k store)
                    return! loop store
            }
        loop Map.empty)

The state is an immutable Map; each Put builds a new map and passes it to the next loop. Any number of threads can call Post and PostAndAsyncReply concurrently.

sequenceDiagram
    participant A as Caller A
    participant B as Caller B
    participant Q as Mailbox queue
    participant L as Agent loop
    A->>Q: Put(a, 1)
    B->>Q: TryGet(a)
    Q->>L: Put(a, 1)
    Note over L: state now holds a = 1
    Q->>L: TryGet(a)
    L-->>B: Some 1

Callers only touch the queue. The loop reads messages one at a time, so the state needs no lock.

Errors, scan and limits

  • Exceptions inside the loop stop that agent silently unless you handle them. The agent exposes an Error event (agent.Error.Add (fun ex -> printfn "%s" ex.Message)) and you should always subscribe, or wrap the body in try/with.
  • inbox.Scan and inbox.TryReceive let you pick messages selectively or time out, for example when waiting for a specific reply.
  • The queue is unbounded, so a fast producer and slow consumer grow memory. For back-pressure use bounded channels (System.Threading.Channels) from a task { }.
  • An agent is a single thread of control. If handling one message takes seconds, all others wait behind it. Keep the handler short or hand slow work to a separate async.

Agents are not a replacement for everything. They shine for owning one piece of state (a counter, a cache, a connection, a game-room list). For pure data-parallel work, use Array.Parallel (Tasks and Parallel Code).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How does a MailboxProcessor avoid race conditions on its state?

    Only the agent's loop touches the state, and it handles one message at a time.
  2. 2. What does return! loop newState do?

    The recursive call carries the new state into the next iteration, with no mutation.
  3. 3. How does a caller get an answer from an agent?

    The message carries a reply channel; the agent calls reply.Reply to answer.
  4. 4. What is a risk of an unbounded mailbox?

    There is no built-in back-pressure; use bounded channels when producers can outrun the consumer.

Summary

  • A MailboxProcessor is an agent: a private state, a queue of messages and a recursive async loop.
  • Messages are a union; state is the loop parameter, so nothing is mutated or locked.
  • Post is fire-and-forget; PostAndAsyncReply with an AsyncReplyChannel gets an answer.
  • Subscribe to Error, keep handlers short and remember the queue is unbounded.
  • Good for owning one piece of shared state; use parallel functions for data-parallel work.

Next: Interop with C# and .NET