Patterns and pitfalls
This chapter collects what running psync on real projects taught us: the shapes it handles well, the ones it deliberately leaves alone, and the ways overlap can hurt.
Shapes psync handles well
The audit of 35 popular Rust repositories sorted missed concurrency into patterns. psync covers the async ones:
| Pattern | Example | What psync does |
|---|---|---|
| P1 independent awaits | two RPCs in a row that share nothing | one level, several chains |
| P2 await in a loop | for key in keys { store.head(key).await? } | prefetch, bounded |
| P3 per-item chains | per shard: list, then fetch, then read the manifest | chain fusion, so each item proceeds on its own |
| P4 late start | a download that needs only the config, written after a long chain | moves into the first level |
Sixteen real-world shapes shows one function per pattern from real repositories, with timings.
Things that stay in place on purpose
- Locks, permits and transactions. An awaited
lock,read,write,acquireortransactionwhose guard outlives the statement is a barrier. If the guard is dropped inside the statement’s own block, the statement may still move. The critical section stays exclusive either way. - Sleeps and ticks.
sleep,sleep_until,tick,yield_nowanddelay_forare barriers. A retry backoff must wait for the failure before it. - Clock reads.
now(),elapsed()andduration_since()measure the waits around them. Before clock reads were made barriers, kube’sdynamic_apiexample timed its discovery as 0 ms: the clock was read before the requests it was meant to time. - Ordered channel and stream calls.
send,recv,next,write,flush,execute,commit, … keep their order per receiver.
&mut in two branches does not compile
psync tracks &mut handles and mut bindings, and keeps their uses in order. It does not see
types, though, so a &mut returned by a method slips through:
pub struct Pool { conn: Conn }
impl Pool {
pub fn conn(&mut self) -> &mut Conn { &mut self.conn }
}
impl Conn {
pub async fn query(&mut self, q: u32) -> u32 { /* .. */ }
}
#[psync::graph]
pub async fn two_queries(pool: &mut Pool) -> u32 {
let conn = pool.conn(); // a `&mut Conn`, but nothing in the tokens says so
let a = conn.query(1).await;
let b = conn.query(2).await;
a + b
}
query is a read verb, so psync takes the two calls for reads of conn, and reads never
conflict:
region 0:
n0: conn = pool . conn ()
n1: a = query() [await] {read `conn` `1` (query)}
n2: b = query() [await] {read `conn` `2` (query)}
n0 -> n1 (reads `conn`)
n0 -> n2 (reads `conn`)
level 0: n0
level 1: n1 || n2
The two queries go into two concurrent chains. Both chains now need conn mutably at once, and
rustc rejects the generated code:
error[E0524]: two closures require unique access to `*conn` at the same time
--> src/lib.rs:10:1
|
10 | #[psync::graph]
| ^^^^^^^^^^^^^^^
| |
| closures are constructed here in different iterations of loop
| first borrow later captured here by closure
...
13 | let a = conn.query(1).await;
| ---- first borrow occurs due to use of `*conn` in coroutine
14 | let b = conn.query(2).await;
| ---- second borrow occurs due to use of `*conn` in coroutine
(The “different iterations of loop” is rustc describing the generated join. There is no loop in
your code. Other shapes give E0499: cannot borrow .. as mutable more than once. Both mean the
same thing.)
That is the intended failure mode: a missed dependency becomes a compile error, not a race. Two fixes:
-
#[psync::seq]on the second query keeps it in place. This always works, and here it is the right fix: the two queries share one connection, so they could not overlap anyway.let a = conn.query(1).await; #[psync::seq] let b = conn.query(2).await; -
#[psync::fresh]onlet conn = ..gives each branch its own connection, by running the initializer once per branch. It works only when the initializer itself can run twice at once. Here it cannot: each branch would callpool.conn(), which borrowspoolmutably, and the error moves topool(two closures require unique access to `*pool`).freshis for initializers likecontext.pool()that hand out a new value from a shared reference, as in Hints.
In the audit, one finding could not be done at all, because it needs &mut self in both branches.
Other attribute macros: #[async_trait], #[instrument], #[tokio::main]
Attribute macros run from the outside in: the attribute written first (highest) sees the
function as you wrote it and rewrites it, then the next one sees that result. So the order
matters, and the rule is short: put #[psync::graph] above every other attribute on the
function, so it reads your code rather than another macro’s output.
#[async_trait]
impl Loader for L1 {
#[psync::graph] // on the method, inside the #[async_trait] impl
async fn load(&self, api: &Api) -> u32 {
let a = api.get_a().await;
let b = api.get_b().await;
a + b
}
}
#[psync::graph] // above #[instrument]
#[tracing::instrument(skip(api))]
async fn traced(api: &Api) -> u32 { /* ... */ }
#[psync::graph] // above #[tokio::main]
#[tokio::main]
async fn main() { /* ... */ }
#[async_trait]goes on the trait and theimpl, which are outside the method, so it runs first. It turnsasync fn loadinto a plainfnreturningPin<Box<dyn Future>>, with your body in anasync moveblock.#[psync::graph]on an ordinaryfnrewrites the async blocks inside it, so it still finds both awaits:loadtakes one 100 ms wait instead of two.#[tracing::instrument]works on either side. Below#[psync::graph], psync sees your body and the report is clean. Above it, psync sees the bodytracinggenerated, and still finds the region, but the report gains abarrier: line 0: the block's valueline for each wrapper statement. Spans psync’s chains run in are those of the function, so events inside a chain are still recorded under the function’s span.#[tokio::main]turnsasync fn maininto a plainfn mainthat blocks on a runtime, so psync must run before it (Comparing builds).
These three were checked on a small crate with async-trait 0.1, tracing 0.1 and tokio 1: each
function took 100 ms with psync, where its two 100 ms waits take 200 ms in sequence.
Send futures
A function whose future must be Send (because it is tokio::spawned, say) stays Send after
the rewrite when every branch is Send. One trap was found in DataFusion and fixed. rustc cannot
prove Send for an iterator adapter, or a generic helper’s future, over items like
Box<dyn Trait + Send>. So prefetched loops now create each item’s future inline, before the
await. The prefetched_trait_objects_stay_send test keeps it that way.
Nested loops multiply their bounds
Each prefetched loop has its own bound. An outer loop over tables (bound 16) whose body has an inner loop over files (bound 8) can hold 16 × 8 = 128 requests in flight from one client.
In the heavy-load run, 32 DataFusion clients refreshing their catalogs offered about 3,600 concurrent requests to one storage node behind one TLS terminator. The node’s throughput fell from 813 to 538 requests/s. The median request took 1.6 s instead of 50 ms. psync made that scenario 0.76× per client (0.54× fleet throughput). At 8 clients, by contrast, the DataFusion fleet still completed 1.7× more operations per second with psync.
What to do:
-
set a process-wide budget once at start-up:
fn main() { psync::set_in_flight_budget(32); // about what the server or the connection pool accepts // ... }Every prefetched loop item beyond the first one of its loop then needs a token from one budget shared by the whole process. The first item of each loop is free, so every loop always makes progress, and nested loops cannot deadlock, even with a budget of 0 (every loop then runs one item at a time). The cap is therefore the budget plus one item per loop running at that moment: with a budget of 3, the 4 × 4 nested loops of
tests/budget.rshold at most 4 requests, where they hold 16 without it. A loop refused a token tries again when one of its own items finishes, and a cancelled loop gives its tokens back.psync::in_flight_beyond_first()reports the tokens in use. The default is unlimited, so nothing changes until you call it. Concurrent statements outside loops are not counted: the code fixes how many there are. -
give inner loops a smaller
bound, or annotate only one level; -
use a client that multiplexes (HTTP/2), so extra requests in flight do not each cost a new connection.
The budget has not yet been measured on the 32-client DataFusion run; the test shows the cap, not the speedup it buys.
Overlap moves the bottleneck to the CPU
psync joins concurrent work inside one task. Once the waits overlap, whatever CPU work follows
them runs on one core. kube-rs’s dynamic_api (a kubectl get all) spends 98–99% of its
sequential run in the loop psync rewrites. From that loop’s own speedup, Amdahl’s law predicts
10.4–11.5× end to end. It measured 5.0–9.2×. With every response arriving at once, parsing and printing thousands of objects
became the bottleneck, and all of it ran on one core.
The fix is to spawn each iteration onto the runtime’s worker threads when its future is Send. That
would be a change inside psync, not in your code, and it is not built yet.
Many new connections at once
With no network latency at all, one scenario got slower. kube-rs’s legacy discovery at startup ran at 0.86×: each request took under a millisecond, and psync opened 23 TLS connections at once instead of reusing one. Warm re-discovery, with a pooled connection, was 4.0× faster on the same setup. Overlap is cheap when waiting dominates, and not free when connection setup does.
Servers push back
At 32 concurrent clients, the Kubernetes API server’s flow control queued psync’s requests, and rejected 467 of them with HTTP 429. kube-rs retried every one, and no run failed. Fleet throughput was then the same in both builds (1.03×). psync creates no work. It only turns waiting into overlap, and a saturated server has no waiting left to overlap.
Memory
Prefetched loops buffer every item’s prefix result until the rest of the body runs. kube-rs’s
dynamic_api went from 32 to 66 MB peak RSS, and from 118 to 262 MB on the 5× cluster.
bound does not change this. It limits how many prefixes are in flight, but the generated code
creates every item’s future before the first one starts, and keeps every result until the join
ends. Peak memory grows with the number of items, whatever the bound. For a very long loop over
large results, split the input into batches yourself and loop over the batches, or keep the loop
sequential with #[psync::seq].
Exercises
- Add
#[psync::seq]to the second query intwo_queries. What does the report say, and is the function changed at all? - A command spends 90% of its sequential run in one loop. psync makes that loop 10× faster. What end-to-end speedup does Amdahl’s law predict? What might make the measured speedup smaller?
- An outer loop with
#[psync::graph(bound = 4)]has an inner loop over files that is also prefetched. How many requests can be in flight at once? How would you cap it at 16? - A prefetched loop runs over 100,000 keys with
bound = 8, and each prefix returns about 50 KB. Roughly how much memory do the buffered results take at the peak?
Answers
barrier: line 5: `# [psync :: seq] let b = conn . query (2) . await ;`: marked #[psync::seq], andchangedisfalse. The marked statement is a barrier that splits the block. The region before it holds one await, and the region after it none, so there is nothing to overlap. The output is the function as written, which compiles.- 1 / (0.1 + 0.9 / 10) = 1 / 0.19 ≈ 5.3×. It is less when the work after the waits is CPU-bound: once all the responses arrive at once, parsing them runs on one core (Overlap moves the bottleneck to the CPU). New connections, server limits and memory can cost more too.
- Each loop has its own bound, and the function’s
bound = 4applies to both, so 4 × 4 = 16 are already the cap. With the default of 16 it would be 256. To cap a nested pair at N, give the function a bound of about √N, or leave one loop sequential with#[psync::seq]and give the other the full N. Or callpsync::set_in_flight_budget(15): the outer loop’s first item and each inner loop’s first request are free, and every other request or row takes one of the 15 tokens, so at most 16 requests are in flight. The budget also counts the loops of every other function running at the same time. - About 100,000 × 50 KB = 5 GB.
boundlimits the requests in flight, not the results: every result is kept until the rest of the body runs (Memory). Batch the keys.