Design Patterns for Complex Apps?

Hello everyone! I've look at a lot of the rust design patterns blogs and github collections of best practices, but I'm looking to get my head around something a bit bigger.

In my scenario, I need to build a server that will be doing a bunch of work with workers. And the data for each worker needs to be read and written to a database. And the server will also have a web API so GUIs can ask about status, and issue commands, etc. What is the best architecture for that?

In the Python world, I would create a class that holds the state of things and holds on to each worker. I would pass that instantiated object by reference into the web server so it took could ask that object about the state of things and ask that object to deliver messages to the workers. Is this similar to what I would want to do with Rust?

Designing software is more an art than it is a science. You have to go with the flow, learn by trial and error, and be prepared to code and recode parts of the program as you progress, like an artist would. Regardless, I would recommend using an asyncrhonous design coupled with Senders and Receivers. Having an event loop to poll the state of certain data types would help too.

1 Like

Python-like design could work, but you need to be careful that what Rust calls a "reference" has a very specific and very narrow use in Rust, and it is generally inappropriate for "holding a reference to a server" in Pythonic sense. A Python-like reference is not & in Rust, but rather a type like Arc<Mutex>. Python's hidden reference counting and GIL is in-your-face explicit in Rust.

Consider using channels to send data from the server to workers that handle the database, etc.

1 Like

If you're looking for something more frameworky, Rocket is the place to start.

A somewhat common pattern you'll see that may help with your workers, it's the passing an Enum containing a "command" through a mpsc channel to a worker. The worker can take the commands and handle them using async/await in a loop. This works a lot like a traditional single threaded worker model, but because it never blocks, there is more parallelism.

1 Like

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.