Who changes the title registry, and how does the caller know the change happened? In examples/src/bin/ep12.rs, the registry() task owns titles. main() sends Message::Add values through a bounded channel. Each message includes a one-use reply sender.
This example uses a channel to route requests to one owner. Arc would address shared ownership of an allocation. A mutex would coordinate access to protected state. Keep those responsibilities separate while tracing the actual message flow.
Predict the acknowledgement for the first added title, then the second. After both replies arrive, identify which sender must be dropped before the registry can finish.
This lesson covers three tools for state that more than one part of a program wants to change: Arc for shared ownership, a mutex for guarded access, and a channel that gives the state one owner and sends it messages. The example uses the channel. It leaves out persistence; the registry lives in memory. It assumes Tutorials 7 and 11. If you're coming from Laravel, Tutorial 9 noted that singleton and scoped bindings have different reuse behavior, and that a long-running worker makes the difference more consequential; this lesson asks who is allowed to change a value like that.
Take a look at Example 1.
Example 1. Complete example (examples/src/bin/ep12.rs)
use tokio::sync::{mpsc, oneshot};
enum Message {
Add { title: String, reply: oneshot::Sender<usize> },
}
async fn registry(mut inbox: mpsc::Receiver<Message>) {
let mut titles = Vec::new();
while let Some(message) = inbox.recv().await {
match message {
Message::Add { title, reply } => {
titles.push(title);
// The caller may have stopped waiting; keep serving others.
let _ = reply.send(titles.len());
}
}
}
assert_eq!(titles, vec!["tests", "format"]);
}
#[tokio::main(flavor = "current_thread")]
async fn main() {
let (sender, inbox) = mpsc::channel(2);
let worker = tokio::spawn(registry(inbox));
for (index, title) in ["tests", "format"].into_iter().enumerate() {
let (reply, response) = oneshot::channel();
sender.send(Message::Add {
title: title.into(), reply,
}).await.expect("registry should be alive");
assert_eq!(response.await.expect("acknowledgement"), index + 1);
}
drop(sender);
worker.await.expect("registry task should finish");
println!("two acknowledged changes, then clean shutdown");
}
Make the predictions above before you run it. When both acknowledgements match and the registry shuts down, it prints:
cargo run --quiet --bin ep12
two acknowledged changes, then clean shutdownThe vector with one owner
The vector titles was declared inside registry and let nothing else touch it. It had no Arc around it and no lock. main wanted two titles in it all the same, tests and format, and had no way to reach it. So main put each title into a Message::Add with a oneshot reply sender inside, the way a letter goes out with a return envelope folded into it, sent the message through the one mpsc sender it held, and waited. The registry pushed each title itself and sent back a count: 1, then 2.
Sometimes two parts of a program need to change the same thing, and the useful question isn't where the value can be found but who changes it and how the caller knows the change happened. Thankfully, a pair of channels can answer both: one carries each request to a single owner, and one carries the answer back. Take another look at Example 1.
There are four pieces. Message::Add carries a title and a oneshot::Sender<usize> for the reply. registry() creates titles and loops on inbox.recv().await. main() creates a bounded mpsc::channel(2), spawns the registry, and for each title sends a message and awaits its acknowledgement. Then drop(sender) closes the channel and worker.await waits for the registry to finish.
Inside the loop, matching a Message::Add provides its owned title and reply. titles.push(title) stores the string, and reply.send(titles.len()) reports the resulting count to that message's caller. So the first acknowledgement is 1 and the second is 2, which is what the assert_eq! against index + 1 checks.
What does the acknowledgement say?
It says this in-memory operation reached the update. It does not mean anything was written to disk, and it does not promise that the data will survive a crash. If durable acceptance is part of the product, the reply must correspond to the appropriate persisted boundary.
mpsc::channel(2) limits the number of buffered messages. If the buffer is full while the receiver remains open, sender.send(...).await waits for room. This program waits for each reply before sending the next message, so its two requests do not demonstrate a full buffer. A real caller needs a policy for excessive waiting.¹
oneshot::channel() creates reply and response for one request. main() puts reply in Message::Add and awaits response. If the caller drops response, the registry's reply send can fail, and let _ = reply.send(...) deliberately discards that failure so the registry can continue. The comment above that line says so.
The mutation has already happened before the reply is attempted, which means a caller that timed out cannot, whatever its own error handling concluded and however natural it seems after a timeout to read no answer as no change, safely assume that nothing happened, and the title is already in the vector.
Retrying a state-changing request may therefore require an idempotency key or a queryable operation identifier. Rust can prevent invalid access to the vector. It cannot infer that a retry should be deduplicated, or that a lost acknowledgement means the user needs a particular message. Those contracts are ours to design.
How does it stop?
After the second acknowledgement, drop(sender) removes the last producer in main(). Once the closed channel has drained, inbox.recv().await returns None and the while let loop ends. The registry checks its two stored titles, worker.await observes task completion, and the terminal prints two acknowledged changes, then clean shutdown. That answers the last prediction above: the sender in main() is the one that has to go.
That is why the ownership of senders is part of shutdown design. "We use channels" is not a complete lifecycle explanation. Identify who can still produce work, when producers stop, how the receiver drains, and who waits for completion.²
Where Arc and Mutex fit
Sometimes a short shared critical section is simpler, and you can also share the state directly. Arc can keep one state allocation alive for several owners, and a mutex can grant coordinated access to its contents. Arc alone does not make arbitrary inner data safe to mutate concurrently; its thread-safety behavior depends on the inner type's bounds.
When you use a synchronous mutex in async code, keep the protected work short and do not hold the guard across an .await. If waiting while holding an async lock is truly necessary, understand what it does to scheduling and contention. An async mutex changes how waiting is handled, and a long critical section stays long.
The capstone in Tutorial 15 uses a short mutex-protected insertion, because that is enough for its tiny registry. This tutorial uses a message owner to show a different arrangement. Neither approach is universally more advanced. If you're unsure, I'd pick the arrangement that makes the invariant and the lifecycle easiest to demonstrate.
So both changes are acknowledged and the registry shuts down. Now take one singleton in a long-running worker of yours. Who is allowed to change it? If a change is acknowledged and the reply is lost, what does the caller do next? And what tells that worker to stop?
Testing
Keep a clone of sender alive until after worker.await. Before you run that variation, predict whether inbox.recv().await can finish once the original sender is dropped.
Then compare. The extra sender keeps the channel open, so the registry can remain waiting and worker.await cannot finish. Drop every producer before awaiting the drain.
Two more cases, each on its own. Drop a oneshot response receiver before the reply, and, separately, send after the registry's receiver has closed. The first tests abandoned acknowledgements; the second tests an unavailable consumer.
TL;DR
The lifecycle in Example 1 runs in order: send a message, receive it, store its title, return the count, close all producers, then await the drain. One task owns the vector, and callers reach it only through messages. The acknowledgement follows an in-memory mutation and does not establish persistence, and the registry's loop ends once every sender is gone and the channel has drained. Arc keeps one allocation alive for several owners and a mutex coordinates access to its contents; the capstone in Tutorial 15 uses a short mutex-protected update instead of a message owner.
¹ There is no universal ideal capacity. Choose from the work involved and the acceptable backlog, then observe it under realistic load.
² The example uses expect for conditions the demonstration itself establishes. A production boundary should report unexpected channel closure as an error appropriate to the caller. Panic messages are not a user-facing availability strategy.