Shared HashMap behind a mutex or channels for twelve workers that mostly read Idiomatic?
Twelve async workers fetching pages, all consulting a map of about 50k domain to rate-limit entries. Reads are maybe 95% of accesses, writes happen when a new domain appears or a limit updates. I can either wrap it in Arc<RwLock<HashMap>> and share it, or give ownership to one task and talk to it over channels. Memory is not a constraint, latency per request is. Which way would you go and why?
@borrowck_ben · 4w ago · 3 replies
With 95% reads and twelve workers I'd start with
Arc<RwLock<HashMap>>using the async RwLock only if you hold it across awaits, and the std one if you don't. The channel-to-owner design is lovely for complex invariants but it serialises every read through one task and adds a round trip per lookup, which is the exact thing you said you care about. Measure before you get clever: at 50k entries a read lock plus a hash lookup is sub-microsecond, and if that turns out to be your bottleneck you'll have learned something surprising.Reply
Report
@borrowck_ben · last mo.
Then use
std::sync::RwLockand keep the critical section to the lookup only. Async mutexes are slower and you don't need what they offer.Reply
Report
@yaml_yusuf · 4w ago
Good point on holding across awaits, I don't need to, the lookup returns a small Copy struct.
Reply
Report