Search code examples
rustrust-tokiorust-rocket

Not using Async in Rocket 0.5+?


I read Rocket v0.5 now uses the Tokio runtime to support Async. I know Async can offer great scalability when we have lots of (like hundreds or thousands of) concurrent IO-bound requests. But many web/REST server apps simply don't fall into that category and in such cases, I feel like Async would only complicate stuff. Sorry if that sounds like a dumb question, but with Rocket 0.5+ will I still be able to write a traditional non-async code the same way as before? Does Async-support in Rocket 0.5+ mean that we will only get Async behaviour for async fn handlers? If so, will the Tokio runtime still play any role in non-async code?


Solution

  • Sure you can.

    Look at the first examples in the web page:

    #[get("/")]
    fn index() -> &'static str {
       "Hello, world!"
    }
    

    There is no async/await anywhere. The nicest thing of Rocket5 is that you can choose which views are sync are which are async, simply by making them so, and you can mix them together as you see fit.

    For example this will just work:

    #[get("/sync")]
    fn index1() -> &'static str {
       "Hello, sync!"
    }
    #[get("/async")]
    async fn index2() -> &'static str {
       "Hello, async!"
    }
    

    The Rocket runtime is all async under the hood, but that doesn't need to be exposed to your view handlers at all. When a non-async handler is run, it will be as if Rocket used spawn_blocking().