How to Build a Web Application using Rust — Part III

Dhruva Sagar
Tarka Labs Blog
Published in
2 min readOct 24, 2021

--

Earlier this year, I created a Youtube series on building a web application with Rust, while keeping a strong emphasis on best practices. If you’ve missed my introductory videos, you can check out Part I here and Part II here.

In Part III, I share more on how to build an asynchronous Database Manager module with the help of tokio, that allows us to execute database queries asynchronously.

You can find the video here :

The Code

You can find the source code I am building in this series over at github. Here’s the database manager module along with how we’re using it.

The Gist

The DB::Manager module usestokio::mpscchannel under the hood and allows us to asynchronously query for data. We make use of message passing to represent different database actions we want to perform, such as, getting all or single or creating, updating or deleting UrlMap data. We embed a tokio::oneshot channel within this message which the manager uses to send back the results of the action to the caller.

We usetokio::mpsc channel to allow multiple queries to be run simultaneously, typically this would happen when such queries are run from within multiple http request handlers serving multiple users. This allows us to scale our database manager linearly over all the cores of the CPU for maximum efficiency.

Conclusion

In Part III of this series, you’ll learn how to leverage tokio asynchronous runtime for Rust to do the following:

  • Usetokio::mpsc channel to communicate with the database manager to execute multiple queries asynchronously.
  • Usetokio::oneshot channels within the message sent through the tokio::mpsc channel for receiving back the results of the queries.
  • Use Rust macros to simplify error handling.

Hello Montreal! We’ll be at the Startupfest ’22 all three days, so drop by and say hi. We’d love to see what you’re building, and early birds get a free (limited) design audit or tech consultation. DM us on Twitter (@tarkalabs) and let’s talk.

--

--

hacker. loves to code, lives inside terminals, vim advocate, open source enthusiast.