Storing connection pools in hashmap

I want to create a multi tenant application using Rust. How would I go about storing connection pools in a hashmap where the keys are tenant ids and the values connection pools to different databases?

I want to pass this hashmap as state for an actix-web or rocket application.
Should I wrap the hashmap with Arc and Mutex? How would this work?

Yes, you'd need Arc to share the hashmap between actix's threads. And Mutex (or RwLock) if you need to add new items to it after it's been created, and then you'll also need to make each value in the hashmap also wrapped in an Arc, so that you can clone it while holding the mutex, and release the lock as soon as possible.

Arc<HashMap<Identifier, Database>>, // or
Arc<RwLock<HashMap<Identifier, Arc<Database>>>
1 Like

Is Arc</Database/> necessary? I believe that only the outer Arc is necessary

Yes, it absolutely is.

Otherwise you will be forced to keep the lock open for the entire duration of your usage of Database, which will serialize every access to the hash map, and make every user of it behave like a single-threaded program, and make the whole pooling entirely pointless.

You could alternatively .remove() the object from the HashMap, release the lock, and when you're done with the db, lock again and put it back. But that doubles amount of locking, and is error prone unless you write an appropriate scope guard for this.

3 Likes

Thank you for the detailed explanation. I have done it the way you explained.

Thank you for the help!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.