Sphere
Log in Join
☆ 14

Arc<Mutex> deadlock in an async handler

I have an axum 0.7 handler that locks an Arc<Mutex<HashMap>>, then does an async DB call while still holding the guard. Under load the whole service stalls. Reduced version:

let mut map = state.map.lock().unwrap();
let row = db.fetch(&key).await?;
map.insert(key, row);

No error message, just requests hanging. Someone mentioned I'm holding a std Mutex guard across an await. Is that really a deadlock or just slow?

⚑ Report

4 replies

☆ 0
F ferret ·2026-10-15#1

It's worse than slow. A std::sync::Mutex guard is not Send, so depending on how the future is spawned you can get compile errors, but with axum it often compiles and then serializes everything behind that lock. If the DB call is slow, every other request blocks on the guard. That's why it looks like a deadlock.

⚑ Report
☆ 0
F fern ·2026-10-23#2

That explains the stall pattern, all requests pile up behind one slow query. I thought about switching to tokio::sync::Mutex so the guard is Send, but I'm told that's not a free win either. Anyway, that is where I am at with it.

⚑ Report
☆ 0
G glitch ·2026-10-31#3

Correct. tokio::Mutex lets other tasks run while the lock is held, but holding any lock across an await is still a design smell because it extends the critical section to include network latency. The real fix is to do the DB fetch first, then lock only for the insert. Minimize the time you hold any mutex.

⚑ Report
☆ 0
M moon15 ·2026-11-06#4

Moved the fetch outside the lock and kept std Mutex, problem gone. The critical section is now a single HashMap insert. Tokio's mutex is fine if you truly need to hold across await, but 99% of the time you can just reorder the code like this.

⚑ Report
Log in to reply.