Distributed Computing
local graph
Chapter 20 — Distributed Computing
Section titled “Chapter 20 — Distributed Computing”20 Distributed Computing
Section titled “20 Distributed Computing”This is the final chapter. Because we have covered so much in the book, this chapter will not cover many new concepts, but will teach you how to arrange these concepts for distributed computing. Our system in this chapter will post compute tasks onto a queue to be processed by workers that can be on other computers if needed. As this is the last chapter, we will skim over most of the concepts as they will have already been covered previously in the book. It must also be noted that distributed computing requires a lot of moving parts. When writing this book, I have tried to keep the pace interesting with intermittent rewards where you get to see your code run. However, in this chapter, all these different moving parts need to talk to each other for you to see something new. Therefore, you will have to stick with this chapter right through to the end before seeing it run. This chapter is essentially the final boss of the book and covers the following:
- Introduction to queuing
- Defining the layout of the queuing system
- Building our kernel
- Building our compute unit
- Building our worker
- Building our server
- Building our client
- Running our queuing system
By the end of this chapter, you will be able to implement a queuing system where the tasks can be distributed across multiple computers to be processed using Redis.
Technical requirements
Section titled “Technical requirements”You can download the example project and code for this book by following the instructions in the Download the example code files section in the Preface of this book.
This chapter’s code files are included in the downloadable code bundle.
Introduction to queuing
Section titled “Introduction to queuing”As web applications progress, our demands on them increase. For instance, I have worked on web applications that train machine learning models when a certain network request is made. The training of a machine learning model can take minutes to hours to days, depending on a range of factors. If the client had to wait for the machine learning model to finish training, the connection would time out. The solution is to have a queue in a database. The client can then make a request to the server. The server then puts the long-running task in a queue and responds to the client, stating that the task has been posted into the queue. We then have a worker that pulls the task from the queue and processes it. We can see this outline in Figure 20.1:
Figure 20.1 – A basic web worker queue
Queuing can act as a buffer for our system. If we have a burst of requests, we can offload them to a queue to be processed in our own time. Scaling is also simple. All we need to do is increase the number of workers that have access to the queue. We can also distribute the workers over multiple regions to reduce the risk of an area outage disrupting workflow. We can also distribute our servers over different regions with load balancing.
Being able to utilize queues is a powerful tool. But knowing when to apply queuing as a solution is also part of the battle. The following is a non-exhaustive list of when queues are useful:
- Background task processing: Queues are perfect for offloading long-running or computationally intensive tasks from the main web application to prevent blocking requests.
- Use case: Sending emails or push notifications.
- Example: A user signs up, and a worker sends a welcome email.
- Use case: Generating reports.
- Example: A user requests a monthly analytics report, which is queued and processed by a worker.
- Use case: Video or image processing.
- Example: A user uploads a video, and a worker processes it for different resolutions or formats.
- Use case: Sending emails or push notifications.
[figure outside: Figure 20.1]
Rate-limited or scheduled tasks: Queues enable task scheduling or throttling to avoid overwhelming external systems.
Use case: API rate limiting.
Example: Sending SMS messages through a third-party provider with a limit of 100 requests per minute.
Use case: Scheduled actions.
Example: Scheduling reminders for users, such as payment or appointment notifications.
Decoupling services: Queues can act as intermediaries between services, allowing for asynchronous communication.
Use case: Decoupling microservices.
Example: An order management service queues messages for a billing service to process payments asynchronously.
Use case: Logging and auditing.
Example: A web application logs events such as user actions to a queue, which are then processed by a logging service.
High throughput systems: Queues handle high volumes of incoming requests by balancing workloads across workers.
Use case: Chat systems.
Example: Messages sent in a chat application are queued and processed for delivery to recipients.
Use case: Order processing in e-commerce.
Example: Processing thousands of online orders and payments without overwhelming the main application.
Real-time systems: Queues are useful for handling real-time data streams that require processing.
Use case: Data pipelines.
Example: A system collects logs or metrics and queues them for workers to process and store in a database.
Use case: Gaming leaderboards.
Example: Player scores are queued and updated asynchronously in real time.
Failure recovery and retries: Queues provide mechanisms for retries and managing failures without losing tasks.
-
Use case: Payment gateways.
- Example: Failed payment transactions are re-queued for retries with exponential backoff.
-
Use case: Third-party integrations.
- Example: A worker retries failed API calls without blocking the main application.
-
Load balancing: Queues distribute tasks evenly among workers, ensuring optimal resource utilization.
- Use case: Resource-intensive computations.
- Example: Workers compute large mathematical models or simulations for a web application.
- Use case: Parallel processing.
- Example: Workers process batches of data uploaded by users for faster performance.
- Use case: Resource-intensive computations.
-
User-initiated batch jobs: For tasks initiated by users that involve multiple sub-tasks, a queue helps ensure orderly processing.
- Use case: Bulk email sending.
- Example: A user uploads a CSV of email addresses, and workers send emails to each address.
- Use case: Bulk email sending.
-
Use case: Batch file processing.
- Example: Users upload ZIP files containing images, and workers process each image individually.
-
Notifications and alerts: Queues help ensure notifications are delivered promptly without overloading the system.
- Use case: Real-time alerts.
- Example: Workers process and send alerts for monitoring systems when thresholds are breached.
- Use case: Real-time alerts.
-
Use case: Social media updates.
- Example: A worker queues and delivers notifications for new comments, likes, or follows.
-
Database or cache preloading: Queues help with preloading or maintaining cache and database consistency.
- Use case: Precomputing data.
- Example: Workers precompute search indexes or summaries when data changes.
- Use case: Precomputing data.
-
Use case: Cache invalidation. Example: Workers invalidate or update cached items asynchronously after database changes.
Now that we know what a web queuing system consists of and when to use it, we can move on to defining the layout of our queuing system.
Defining the layout of the queuing system
Section titled “Defining the layout of the queuing system”Our queuing system has the following workspaces:
- Client
- Compute unit and kernel
- Server and worker
- Other configurations
Let’s look at them in detail ahead.
Client
Section titled “Client”The client sends data to the server to schedule the task on the queue. The file structure of our client takes the following form:
└─ client ├── Cargo.toml ├── compute_unit.wasm └─ src └─ main.rs
Here, we can see a .wasm file. This is because our queuing system will send a WASM compute unit to the server, which will then place the WASM compute unit on a queue to be processed by a worker.
Why are we using WASM?
The simplest way to distribute a compute task is to build a struct with the compute function in a kernel. The client can take the struct from the kernel, populate the fields, serialize the struct, and send the serialized struct to the server. The server then puts the serialized struct onto the queue for the worker to take and deserialize. Once the worker has the deserialized struct, the worker can then run functions associated with that struct. In this chapter, instead of taking that simple approach, we are sending WASM binaries to the server to be put onto the queue to be processed by the worker. This is harder and takes extra steps. However, we can compile different languages such as Python, Golang, Zig, JavaScript, or Rust into WASM, enabling our queuing system to run multiple languages. Being able to run multiple different languages on your queuing system is flexible; however, it does come with some drawbacks. WASM binaries are going to be larger as the entire program is compiled into the binary as opposed to just the data needed. At the time of writing this book, async calls and network calls need to be done outside of the WASM binary. For a learning exercise, if you can carry out the WASM example, you will also be able to implement Rust computation tasks on a queue. Distributed Computing
Compute unit and kernel
Section titled “Compute unit and kernel”The compute unit is where we define the task to be put on the Redis queue. In the compute unit workspace, we will build the WASM binary and copy the WASM binary over to the client to be sent to the server. Our kernel workspace is where we build structs that are used by multiple workspaces. The kernel workspace will house the struct for a JSON body to be sent to the server. Again, our kernel would also house compute units that are pure Rust. Both the compute unit and kernel workspaces have the following layout:
| ├─ compute-unit | │ ├─ Cargo.toml | │ │ src | │ │ └─ lib.rs | │ └─ kernel | │ │ ├─ Cargo.toml | │ │ │ src | │ │ └─ lib.rs
Server and worker
Section titled “Server and worker”Our server and worker workspaces are processes that run continuously. The server must listen to incoming network requests, and our worker must listen to tasks pushed onto the Redis queue. Both server and worker workspaces have the following outline:
| ├─ server | │ ├─ Cargo.toml | │ │ src | │ │ └─ main.rs | │ └─ worker | │ │ ├─ Cargo.toml | │ │ │ src | │ │ └─ main.rs
Other configurations
Section titled “Other configurations”At the root of our project, next to all our Rust workspaces, we have the following files:
| ├─ Cargo.toml | │ ├─ docker-compose.yml | │ ├─ scripts | │ │ └─ build_wasm.sh
Inside our Cargo.toml file, we define our workspaces with the following code:
# File: Cargo.toml
[workspace]members = [ "client", "compute-unit", "kernel", "server", "worker"]Our docker-compose.yml file needs to run a Redis container, which is achieved with the following code:
File: docker-compose.yml
Section titled “File: docker-compose.yml”version: ‘3.9’
services: redis: image: redis:latest container_name: redis_server ports: - “6379:6379” restart: always
And finally, we define our WASM build script with the following code:
#!/usr/bin/env bash
# navigate to directorySCRIPTPATH="$( cd "$(dirname "$0")" ; pwd -P )"cd $SCRIPTPATHcd ..cargo build -p compute-unit --target wasm32-wasi --releaseif [ -f ./client/compute_unit.wasm ]; then echo “remove computing unit in worker” rm ./client/compute_unit.wasm fi
cp target/wasm32-wasi/release/compute_unit.wasm \./client/compute_unit.wasmAt this point in the book, you will have seen this Bash code several times. Here, we navigate to the directory, build the compute unit for a WASM target, remove the old WASM file if the old WASM file is in the target, and then move the new WASM file into the client workspace. With this, our system is complete, and we can move on to building our kernel.
Building our kernel
Section titled “Building our kernel”Our kernel just houses the struct for the JSON body. Seeing as the JSON body is used to send the WASM compute unit to the server and put the WASM compute unit onto the Redis queue, all client, server, and worker Rust workspaces will need to reference this struct that supports JSON serialization. Considering our JSON dependency, the kernel’s Cargo.toml file takes the following form:
## kernel/Cargo.toml[package] name = "kernel" version = "0.1.0" edition = "2021"
[dependencies] serde = { version = "1.0", features = ["derive"] }Now that we have defined our dependencies, we can build our JSON payload struct with the following code:
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]pub struct Payload { pub memory: Vec<u8>, pub contract: Vec<u8>,}For our payload struct, we store the WASM compute unit in the contract field. We can then load the WASM compute unit as a WASM module and run it. We also have the memory of the WASM compute unit stored in the memory field. Storing the memory enables us to treat our payloads as coroutines. This means we can perform a computation, update the memory, store the memory and WASM binary back into the payload, and put the payload back on the queue to be computed again. Now that we can transport and store our compute unit, we can build our compute unit.
Building our compute unit
Section titled “Building our compute unit”Our compute unit is a WASM binary. However, we must create the WASM binary from Rust code. To build the WASM binary, our compute unit needs the following Cargo.toml file:
[package] name = "compute-unit" version = "0.1.0"edition = “2021”
[dependencies]
[lib]crate-type = ["cdylib"]Here, cdylib means that the compute unit produces the dynamic library that is compatible with C-style linking, which is needed for the WASM compilation. Now that we have defined the Cargo.toml file, we can write a WASM compute unit with the following imports:
extern crate alloc;use std::thread::sleep;use std::time::Duration;use core::alloc::Layout;You may have seen alloc and Layout before. We use them in our memory allocation function, which takes the following form:
#[no_mangle]pub unsafe extern "C" fn ns_malloc( size: u32, alignment: u32) ->*mut u8 { let layout = Layout::from_size_align_unchecked( size as usize, alignment as usize ); alloc::alloc::alloc(layout) }Looking at the function in the preceding code, the Layout struct is the layout of a block of memory. We want to get a slice of memory that we can write to, so we pass into the from_size_align_unchecked function the size of the memory block that we need. The alignment is the segment within the big block of memory. For instance, if we were just storing 4-byte integers in the memory, then the alignment would be 4. We would be able to store different sizes, but this could affect performance. Once we have Layout defined, we pass the Layout struct into the alloc::alloc::alloc function to allocate the memory and get a pointer. This pointer will point to the start of the memory block. Once we call the ns_malloc function, we can use the pointer returned to access the memory. This allocation function will enable us to load the state into the compute unit before running it. To run our main compute unit, we need the following function outline:
#[no_mangle]pub extern "C" fn run_compute(ptr: i32, len: i32) -> i32 { ...}Before we write any of the function, let us understand what we want to simulate. We want to essentially create a coroutine, where the state is persistent between each execution of the WASM program. The simplest example we can use is a counter that increases the count by one every time. If the count exceeds the highest number defined when creating the task, the compute unit is finished. This directly mimics the behavior of a simple async task being polled. However, it is written in WASM, and the queue and polling are distributed across multiple computers.
For us to be able to facilitate coroutine behavior in the run_compute function, we first must load the memory with the following code:
let memory = unsafe { std::slice::from_raw_parts_mut(ptr as *mut u8, len as usize)};if memory.len() < 8 { panic!("Memory size too small!");}The loading of the memory is unsafe because we are using a raw pointer to directly access the memory. For our coroutine to work, we need two integers: the current count of the coroutine and the maximum number. These are two 4-byte integers, so the total amount of memory needed is 8 bytes. Therefore, we must check that we have at least 8 bytes in our memory; otherwise, we are going to overflow into another part of memory when accessing our data.
Now that we have our raw data, we get the first 4 bytes and convert them into an integer for the highest number, and the next 4 bytes are converted into the current number with the following code:
let highest_num = i32::from_le_bytes([ memory[0], memory[1], memory[2], memory[3],]);let mut current_num = i32::from_le_bytes([ memory[4], memory[5],]);memory[6], memory[7],
]);We now have our data, so we can increase the counter by one, sleep for two seconds to simulate some work, and then write the new number to the memory with the following code:
current_num += 1;sleep(Duration::from_secs(2));let new_bytes = current_num.to_le_bytes();for i in 0..4 { memory[4 + i] = new_bytes[i];}Finally, we print out the memory just for demonstration purposes so we can see it in the terminal when we run our system. We then check to see whether the number is big enough to finish the coroutine and return a number with the following code:
println!("{:?}", memory);if current_num >= highest_num { return 1}return 0}Like the enum of async tasks, where it is either Ready or Pending, we return a 1 if the compute unit is ready, and a 0 if the compute unit is pending. Therefore, the worker can take the number and handle the compute unit depending on the outcome. Now that we have defined our compute unit, we can build our worker to see how we handle this WASM coroutine.
Building our worker
Section titled “Building our worker”Our worker runs on a loop, consuming tasks from the Redis queue and loading these tasks into a WASM runtime. We then put the WASM task back on the queue if the task is not completed. For our worker, we need the following dependencies:
File: worker/Cargo.toml
Section titled “File: worker/Cargo.toml”[package] name = “worker” version = “0.1.0” edition = “2021”
[dependencies]wasmtime = "27.0.0"wasmtime-wasi = { version = "27.0.0", features = ["preview1"]}tokio = { version = "1.37.0", features = ["full"] }redis = { version = "0.24", features = ["aio", "tokio-comp"] }serde = { version = "1.0", features = ["derive"] }serde_json = "1.0"kernel = { path = "../kernel" }At this point in the book, you should be able to understand where all the dependencies will slot in. For our main function, we have the following outline:
use wasmtime::{Result, Engine, Linker, Module, Store, Config};use wasmtime_wasi::preview1::{self, WasiP1Ctx};use wasmtime_wasi::WasiCtxBuilder;use redis::{AsyncCommands, Client};use tokio::task;use kernel::Payload;use std::io;
#[tokio::main]async fn main() { let redis_client = Client::open( "redis://127.0.0.1/" ).expect("Failed to connect to Redis");
let redis_task = task::spawn(async move { worker(redis_client).await; }); let _ = redis_task.await;}Here, we make a connection to Redis, spawn a task running a worker function, and then wait on that task, which will not finish because the worker function is a loop. Multiple workers
We can have multiple workers by spawning multiple tasks and then just waiting on one task, as in the following code:
let one = task::spawn(async move {worker(redis_client).await;});
let two = task::spawn(async move {worker(redis_client).await;});
let three = task::spawn(async move {worker(redis_client).await;});
let four = task::spawn(async move {worker(redis_client).await;});
let _ = one.await;All the workers will be looping and consuming tasks. None of the workers will finish due to the loop. So, awaiting one task will keep the entire program running.
The outline of our worker function takes the following form:
async fn worker(client: Client) { let mut connection = client .get_async_connection() .await .expect("Failed to connect to Redis"); loop { ... }}Inside the loop, we wait for messages on payload_queue with no timeout with the following code:
match connection.blpop::<&str, Option<(String, String)>>( "payload_queue", 0.0) .await { 0k(Some((_queue_name, payload))) => {...}Ok(None) => { println!("No payload found. Waiting...");}Err(err) => { eprintln!("Error reading from Redis: {}", err);}}We now have a loop that is listening to a queue, pulling tasks as JSON strings to process. To deserialize the JSON string and run the WASM program, we use the following code:
match serde_json::from_str::<Payload>(&payload) { Ok(parsed_payload) => { let (updated_payload, outcome) = match run_worker( parsed_payload).await { Ok(result) => result, Err(err) => { eprintln!("Failed to run worker: {}", err); continue; } }; if outcome == 1 { println!("task completed"); } else { let payload_json: String = serde_json::to_string( &updated_payload ).unwrap(); let _: () = connection .rpush::<_, _, ()>( "payload_queue", payload_json ) .await.unwrap(); println!("task not completed"); } } Err(err) => { eprintln!("Failed to deserialize JSON: {}", err); } }}Here, we try and deserialize the JSON string to a PayLoad struct to be processed. We then run the worker by calling a run_worker function, which we will define next. Once the outcome has been computed, we just print that the task is completed if we get a 1. If the task is not completed, we push the updated payload back onto the Redis queue so the task can be executed again with the updated memory.
We can see that our run_worker function must return a number to signal the result of the computation and the updated payload. So, our function has the following outline:
async fn run_worker(payload: Payload) -> Result<(Payload, wasmtime::Error)> { ... }Inside our run_worker function, we first need to load the WASM module and define permissions, such as standard I/O, so we can print to the console with the following code:
let mut config = Config::new();config.async_support(true);let engine = Engine::new(&config)?;let module = Module::new(&engine, &payload.contract)?;let mut linker: Linker<WasiP1Ctx> = Linker::new(&engine);preview1::add_to_linker_async(&mut linker, |t| t)?;let pre = linker.instantiate_pre(&module)?;let wasi_ctx = WasiCtxBuilder::new() .inherit_stdio() .inherit_env() .build_p1();If these concepts are baffling to you, it is advised that you go back and read Chapter 8, which covers how to handle WASM modules using wasmtime in Rust.
Now that our module is defined, we can allocate the memory and inject the memory from the payload into the loaded WASM module with the following code:
let mut store = Store::new(&engine, wasi_ctx);let instance = pre.instantiate_async(&mut store).await?;let malloc = instance.get_typed_func::<(i32, i32), i32>>(&mut store, "ns_malloc")?;let input_data_ptr = malloc.call_async( &mut store, (payload.memory.len() as i32, 0)).await?;let memory = match instance.get_memory(&mut store, "memory") { Some(memory) => memory, None => return Err( wasmtime::Error::new( io::Error::new( io::ErrorKind::Other, "failed to get memory" ) ) ),};memory.write(&mut store, input_data_ptr as usize, &payload.memory)?;We now have our memory from our payload written into the memory of the WASM module. It must be noted that payload.memory.len() is passed into our memory allocation function, so any WASM module with any memory length will have its memory loaded into the function.
Our WASM module is loaded and ready with the memory we want. Therefore, we can call the run_compute function and read the memory after the compute with the following code:
let entry_point = instance.get_typed_func::<(i32, i32), i32>>(&mut store, "run_compute")?;let ret = entry_point.call_async( &mut store, (input_data_ptr, payload.memory.len() as i32)).await?;let mut updated_memory = vec![0u8; payload.memory.len()];memory.read( &mut store, input_data_ptr as usize, &mut updated_memory)?;We now have the updated memory and the result of the compute. The result and updated memory can then be returned with the following code:
let return_package = Payload { memory: updated_memory, contract: payload.contract,};Ok((return_package, ret))And with this, our worker is complete. As the worker will be waiting on tasks, we need somewhere to post tasks onto the Redis queue. This is where our server comes in.
Building our server
Section titled “Building our server”Our server accepts an HTTP request and posts the task from this request onto a Redis queue. For our server to run, we need the following dependencies:
## File: server/Cargo.toml[package]name = "server"version = "0.1.0"edition = "2021"
[dependencies]redis = { version = "0.27.5", features = ["aio", "tokio-comp"] }axum = "0.7.9"serde = { version = "1.0", features = ["derive"] }tokio = { version = "1", features = ["full"] }serde_json = "1.0"kernel = { path = "../kernel" }At this stage in the book, we have been using Actix to build a server, so in this chapter, we are going to explore the Axum web framework.
In our main file, we have the following imports:
use axum::{ extract::State, routing::post, Json, Router,};use redis::{AsyncCommands, Client};use std::net::SocketAddr;use std::sync::Arc;use kernel::Payload;
#[derive(Clone)]struct AppState { redis_client: Client,}By now, you should be able to understand handlers, routers, JSON utilities, and socket addresses. If you have looked at the Axum, Hyper, and Rocket examples throughout the book, you will have realized that the differences between frameworks are superficial. The one thing you might not have come across is the app state. This is a struct that we wrap in an Arc. This struct can then be accessed by the handlers processing incoming HTTP requests. For our app state, we house the Redis database connection. For our main function, we connect to the Redis database, create an app state for the database connection, define a router, and mount this router to a TCP listener with the following code:
#[tokio::main]async fn main() { let redis_client = Client::open( "redis://127.0.0.1" ).expect("Failed to connect to Redis"); let app_state = Arc::new(AppState { redis_client }); let app = Router::new() .route("/submit", post(write_to_redis)) .with_state(app_state); let addr = SocketAddr::from((127, 0, 0, 1], 3000)); let listener = tokio::net::TcpListener::bind( addr ).await.unwrap(); axum::serve(listener, app).await.unwrap();}We can see from the main function that we only have one endpoint, and this endpoint is the write_to_redis function, which takes the following signature:
async fn write_to_redis( State(state): State<Arc<AppState>>, Json(payload): Json<Payload>,) -> Result<&'static str, (axum::http::StatusCode, String)> { ... Ok("Payload submitted to Redis queue")}Inside our write_to_redis function, we initially get the Redis connection with the following code:
let mut connection = state .redis_client .get_multiplexed_async_connection() .await .map_err(|err| { ( axum::http::StatusCode::INTERNAL_SERVER_ERROR, err.to_string(), ) })?;The multiplexed connection means that the Redis connection is a single connection, but this single connection can handle multiple concurrent requests. Now that we have our Redis connection, we serialize our payload with the following code:
let payload_json: String = serde_json::to_string(&payload) .map_err(|err| { ( axum::http::StatusCode::INTERNAL_SERVER_ERROR, err.to_string(), ) })?;Finally, we push our serialized payload onto the Redis queue with the following code:
let _: () = connection .lpush::<_, _, ()>("payload_queue", payload_json) .await .map_err(|err| { ( axum::http::StatusCode::INTERNAL_SERVER_ERROR, err.to_string(), ) })?;And with this, we now have a working server that will receive a task, then post this onto the Redis queue. The only thing we have left to do is build the client.
Building our client
Section titled “Building our client”At this stage in the book, we have covered HTTP requests a lot, and we have built the compilation Bash script that copies the WASM file into the directory of the client. Now, it is a good time for you to try and build the client yourself with the following dependencies:
[package]name = "client"version = "0.1.0"edition = "2021"[dependencies]kernel = { path = "../kernel" }tokio = { version = "1", features = ["full"] }serde = { version = "1.0", features = ["derive"] }reqwest = { version = "0.12.9", features = ["json"] }If you attempted to build the client yourself, your main function could have the following signature:
use reqwest::Client;use kernel::Payload;use std::fs::File;use std::io::Read;
#[tokio::main]async fn main() -> Result<(), Box<dyn std::error::Error>> { ... Ok(())}Inside our main function, we load the .wasm file and define the memory with the following code:
let mut file = File::open("./compute_unit.wasm")?;let mut wasm = Vec::new();file.read_to_end(&mut wasm)?;let mut memory = [0; 8];let high_num: i32 = 4;let new_bytes = high_num.to_le_bytes();for i in 0..4 { memory[i] = new_bytes[i];}let payload = Payload { memory: memory.to_vec(), contract: wasm,};Here, we can see that we define a high number and write it to the memory. Now that we have our payload defined, we set the client and loop through, making multiple calls with the following code:
let server_url = "http://127.0.0.1:3000/submit";let client = Client::new();for _ in 0..3 { ...}Inside the loop, we just make the HTTP call and print out the response with the following code:
let response = client.post(server_url).json(&payload).send().await;match response {Ok(res) if res.status().is_success() => {let text = res.text().await.unwrap_or_else(|_|"No response body".to_string());println!("Server response: {}", text);}Ok(res) => {eprintln!("Request failed with status: {}",res.status());if let Ok(text) = res.text().await {eprintln!("Response body: {}", text);}}Err(err) => {eprintln!("Failed to send request: {}", err);}}And with this, our entire queuing system is complete. We can now run it.
Running our queuing system
Section titled “Running our queuing system”When it comes to running our system, we need to run the following commands in this order in dif-ferent terminals:
docker-compose upNow that our Redis queue is available, we can start the server posting to the Redis queue with the following command:
cargo run -p serverOur system can now accept tasks as requests and post them onto the Redis queue, but there are no workers to process the tasks. For this, we need to run our worker with the following command:
cargo run -p workerWe are now ready to run our client with the following command:
cargo run -p clientOnce we have run our client, we can look at our worker terminal, and we should have the following printout:
Worker started. Listening for messages on ‘payload_queue’…
[4, 0, 0, 0, 1, 0, 0, 0] task not completed [4, 0, 0, 0, 1, 0, 0, 0] task not completed [4, 0, 0, 0, 1, 0, 0, 0] task not completed [4, 0, 0, 0, 2, 0, 0, 0] task not completed [4, 0, 0, 0, 2, 0, 0, 0] task not completed [4, 0, 0, 0, 3, 0, 0, 0] task not completed [4, 0, 0, 0, 3, 0, 0, 0] task not completed [4, 0, 0, 0, 4, 0, 0, 0] task completed [4, 0, 0, 0, 4, 0, 0, 0] task completed [4, 0, 0, 0, 4, 0, 0, 0] task completed
It is a lengthy printout, but it is important to see how our system is working. We can see the entire memory being printed, which is in the WASM binary. This shows that our standard I/O is working for our WASM module. We can also see that our number is increasing every time we run the WASM module. Because we can see the memory, these tasks are being polled and then put back on the queue for another task to be polled. We have essentially created async WASM compute units that are distributed across multiple computers and can run on any operating system, chip, and even the browser! For this example, printing the memory helped us understand how the tasks are progressing. However, it is not advised to print out the memory normally, as the byte arrays for WASM modules can grow in size and will just fill up your terminal. Our basic implementation does not tell the client when the task is finished. If you need to do this, you need a WebSocket. We covered WebSockets in Chapter 19. All major web frameworks support the option to upgrade the connection to a WebSocket. Remember that HTTP is a protocol transported over a TCP connection. For Axum, there is a WebSocketUpgrade utility. This keeps hold of the TCP connection and converts the protocol to WebSocket, meaning that we can transfer messages back and forth between client and server. This pathway is defined in Figure 20.2:
Figure 20.2 – Callback mechanism for queue updates
In Figure 20.2, the straight lines are pathways from the initial request. The dashed lines are the result of the worker pulling the task from the queue. Here, you would have two Payload struct types. One would be the request that the client sent, and the other would be the same, but with a unique ID. You then pass the WebSocket connection to the actor with the unique ID. The actor can then listen to the queue of the unique ID. If the task is completed by the worker, then the worker can push to that UUID queue. The actor can then update the client.
When it comes to writing books, there comes a point where we must stop; otherwise, we will be writ-ing forever, and the book will never end. When looking at the components needed to perform the callback, we have covered all the components needed. A little googling of the WebSocket extractor for your choice of web framework is the only outstanding knowledge gap. We have also covered extractors and middleware in this book. Look back at Figure 20.2. This is a complex web system that distributes tasks to other processes and updates the client on the progress, and you have all the tools to build this. The aim of this book is to enable you to build a range of solutions for your web programming needs, and now you are ready to go out into the world and start solving problems.
[figure outside: Figure 20.2]
Summary
Section titled “Summary”In this chapter, we went through the basics of queuing and managed to get a server pushing WASM tasks onto a queue to be processed by workers. A lot of the concepts were already covered in previous chapters, but we did introduce how to push to and pull from queues using Redis. As pointed out in the chapter, this is a sign that we have come to the end of our journey. The training wheels are ready to come off, and I am excited about what you will build.
Throughout my coding career, I have embarked on many side projects, and a general rule of thumb is that roughly 80% of the people involved in the project drop off and never really finish it. If you have made it this far and read through the book, you are one of the few. I think you are awesome. In the world of LLMs and snappy online videos, you have chosen to sit down and read this book. The tech industry needs people like you. It has been an exciting journey. We have gone from building a single local Rust server to deploying our system on a server on AWS. Our deployments have been monolithic microservices. It’s been a pleasure and honor to write this book, and I do love hearing from people who have gone on to build things.
Questions
Section titled “Questions”- How could we refactor our system so we do not need WASM?
- How are our tasks in the queue like async tasks?
- How do we load the memory of the task?
- How do we update the memory of the WASM module inside the WASM module?
Answers
Section titled “Answers”- We still put JSON into the Redis queue, but the JSON would just have the parameters and the name of the function that is going to execute the parameters. This function and JSON struct can be housed in the kernel so all the other workspaces can execute tasks.
- Our tasks in the queue are coroutines just like Rust async tasks. They have a state that gets updated when the task is executed, but the task can also be suspended and executed again with the state still intact. Our task had two outcomes, pending and ready, which are like the async tasks in Rust.
- The memory is part of the payload JSON struct and is an array of bytes. We then write the array of bytes to the memory of the loaded WASM module.
- We directly write bytes to the byte array that represents the memory.
Learn more on Discord
Section titled “Learn more on Discord”To join the Discord community for this book – where you can share feedback, ask questions to the author, and learn about new releases – follow this QR code: https://packt.link/EaKXL
Your copy of this book includes the following exclusive benefits:
Complete Code Bundle Download the full source code for this book’s examples and projects.
DRM-Free PDF Version Download DRM-free PDF and ePub copies of this book.
7-Day Packt Library Access Get 7-day unlimited access to 8,000+ books and videos. No credit card required. Available for first-time Packt+ trial users only.
Next-Gen Reader Access Read this book on Packt Reader with progress sync, dark mode and note-taking. Unlock Your Exclusive Benefits
Follow the guide below to unlock them. The process takes only a few minutes and needs to be completed once.
Unlock this Book’s Free Benefits in 3 Easy Steps
Section titled “Unlock this Book’s Free Benefits in 3 Easy Steps”Step 1
Section titled “Step 1”Keep your purchase invoice ready for Step 3. If you have a physical copy, scan it using your phone and save it as a PDF, JPG, or PNG.
For more help on finding your invoice, visit https://www.packtpub.com/en-us/unlock?step=1.
Note: If you bought this book directly from Packt, no invoice is required. After Step 2, you can access your exclusive content right away.
Step 2
Section titled “Step 2”Scan the QR code or go to packtpub.com/unlock.
On the page that opens (similar to Figure 21.1 on desktop), search for this book by name and select the correct edition.
Unlock Your Book’s Free Benefits
Section titled “Unlock Your Book’s Free Benefits”Bought a Packt book from Amazon or one of our channel partners? Unlock your free benefits in 3 easy steps.
Figure 21.1: Packt unlock landing page on desktop
[figure outside: Figure 21.1]