Share E-Book

Beginning Axum Learning Modern Web Development With Rust (Indo Yoon)(Z-Library)

Author

Rating 3.5 AI initial rating

Log in to rate

Rust
Language English

Learn the basics of web development using Axum, the popular Rust-based web development framework, and build a chatting app which is ready to deploy. This book will be an invaluable introduction to Axum and how to use it develop the backend and server along with a wide range of associated tools like WebSocket and SeaORM. The book begins with an introduction to the Rust programming language and server development and then goes on to explore the basics of Axum. This is followed by detailed instructions on how to set up a server using Axum. The book then guides you through connecting to a database using SeaORM. After you have connected your backend to a database, you will learn about Tower Middleware and how to use it to create a JWT authentication layer for your application. The next portion of the book will instruct you in the use of WebSocket and how to implement concurrent WebSocket connections. The final chapter ties all the theories and examples of the preceding chapters together and helps you in building the capstone project of your own chatting app, putting all the skills you have learnt through the book to the test. This book is the book you will need if you want to get started on Axum. It is packed full of useful tips and step-by-step instructions. In addition to the theoretical information, the chapters are supplemented by real-life examples of the use of the concepts as well as quizzes that you can use to test your understanding. By the end of the book you will not only have gained competence in Axum, but you will have gained confidence in using it for actual projects. You Will Learn To: • Use Axum to create the backend server for your own applications • How to use SeaORM, which is also written in Rust, and Postgres for database layer of the server application • Implement Axum in real-world scenarios This Book is For Beginners with a basic grasp of Rust or intermediate web developers interested in expanding their knowledge of Axum

Format PDF
Size 12.1 MB
(First 20 pages)

Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

Page 1
Beginning Axum Learning Modern Web Development With Rust — Indo Yoon
Page 2
Beginning Axum Learning Modern Web Development With Rust Indo Yoon
Page 3
Beginning Axum: Learning Modern Web Development With Rust ISBN-13 (pbk): 979-8-8688-2630-6 ISBN-13 (electronic): 979-8-8688-2631-3 https://doi.org/10.1007/979-8-8688-2631-3 Copyright © 2026 by Indo Yoon This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed. Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights. While the advice and information in this book are believed to be true and accurate at the date of publication, neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or omissions that may be made. The publisher makes no warranty, express or implied, with respect to the material contained herein. Managing Director, Apress Media LLC: Welmoed Spahr Acquisitions Editor: Anandadeep Roy Editorial Assistant: Jessica Vakili Cover designed by eStudioCalamar Cover image designed by Freepik (www.freepik.com) Distributed to the book trade worldwide by Springer Science+Business Media New York, 1 New York Plaza, New York, NY 10004. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail orders-ny@springer-sbm.com, or visit www.springeronline.com. Apress Media, LLC is a Delaware LLC and the sole member (owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation. For information on translations, please e-mail booktranslations@springernature.com; for reprint, paperback, or audio rights, please e-mail bookpermissions@springernature.com. Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook versions and licenses are also available for most titles. For more information, reference our Print and eBook Bulk Sales web page at http://www.apress.com/bulk-sales. Any source code or other supplementary material referenced by the author in this book is available to readers on GitHub. For more detailed information, please visit https://www.apress.com/gp/services/ source-code. If disposing of this product, please recycle the paper Indo Yoon Seoul, Korea (Republic of)
Page 4
iii Table of Contents About the Author vii About the Technical Reviewer ix Acknowledgments xi Introduction xiii About This Bookxv Chapter 1: Rust and Server Development 1 1.1. Why Rust? .............................................................................................................................. 1 1.1.1. Advantages of Rust ........................................................................................................ 1 1.1.2. Advantages of Developing Backends with Rust ............................................................ 2 1.2. Rust Server Development Case Studies................................................................................. 2 1.2.1. Figma ............................................................................................................................. 3 1.2.2. Discord .......................................................................................................................... 3 1.2.3. Dropbox ......................................................................................................................... 4 1.2.4. npm ............................................................................................................................... 4 1.3. Comparing Rust Backend Frameworks .................................................................................. 4 1.3.1. Why You Should Use Axum ............................................................................................ 5 1.4. Setting Up the Development Environment ............................................................................. 7 1.4.1. Installing the Rust Toolchain .......................................................................................... 7 1.4.2. Installing and Setting Up Visual Studio Code ................................................................. 8 1.4.3. Creating a Project ........................................................................................................ 10 1.4.4. Installing the PostgreSQL Database ............................................................................ 10 1.4.5. Installing DBeaver ....................................................................................................... 14 1.4.6. Installing API Testing Tools ........................................................................................... 16 1.5. Reviewing Rust Core Concepts ............................................................................................ 24 1.5.1. Ownership ................................................................................................................... 24
Page 5
iv 1.5.2. Ownership of Values .................................................................................................... 25 1.5.3. Returning Ownership ................................................................................................... 26 1.5.4. References and Borrowing Ownership ........................................................................ 27 1.5.5. Mutable References .................................................................................................... 28 1.5.6. Crates .......................................................................................................................... 31 1.5.7. Modules ....................................................................................................................... 32 1.5.8. Using Modules ............................................................................................................. 33 1.5.9. Packages ..................................................................................................................... 36 1.5.10. Traits .......................................................................................................................... 37 1.5.11. Multithreading and Asynchronous Programming ...................................................... 41 1.6. Review ................................................................................................................................. 41 1.7. Quiz ...................................................................................................................................... 42 References .................................................................................................................................. 42 Chapter 2: Exploring Axum Fundamentals 43 2.1. HTTP Fundamentals ............................................................................................................. 43 2.2. Creating an Axum Project ..................................................................................................... 45 2.3. Routers and Handlers .......................................................................................................... 49 2.3.1. Defining Routers .......................................................................................................... 50 2.3.2. Defining Handlers ........................................................................................................ 52 2.3.3. Sending Responses from Handlers ............................................................................. 70 2.3.4. Status Codes and Headers .......................................................................................... 73 2.4. State Management ............................................................................................................... 79 2.4.1. State ............................................................................................................................ 80 2.4.2. Extension ..................................................................................................................... 89 2.5. Handler Debugging .............................................................................................................. 90 2.6. Example: Creating a Proxy Server ........................................................................................ 93 2.7. Review ................................................................................................................................. 99 Table of ConTenTs
Page 6
v Chapter 3: Database Integration with SeaORM 101 3.1. What Is ORM? ..................................................................................................................... 101 3.1.1. What Is SeaORM? ...................................................................................................... 102 3.2. Creating Schemas and Models .......................................................................................... 103 3.2.1. Defining Database Schema ....................................................................................... 103 3.2.2. Installing Dependencies ............................................................................................ 104 3.2.3. Migration ................................................................................................................... 104 3.3. SeaQuery............................................................................................................................ 113 3.3.1. Query Builder ............................................................................................................. 113 3.3.2. Identifiers and Iden .................................................................................................... 114 3.3.3. Database Connection ................................................................................................. 116 3.3.4. SELECT ...................................................................................................................... 116 3.3.5. INSERT ....................................................................................................................... 118 3.3.6. UPDATE ...................................................................................................................... 121 3.3.7. DELETE ...................................................................................................................... 121 3.3.8. Error Handling ........................................................................................................... 122 3.4. Connecting Users Table to HTTP Requests......................................................................... 124 3.5. Database Connection ......................................................................................................... 127 3.5.1. Connection Pool ......................................................................................................... 128 3.5.2. Connection Options ................................................................................................... 128 3.6. Modularization ................................................................................................................... 129 3.6.1. Separating the DB Module ......................................................................................... 130 3.6.2. API Module Separation .............................................................................................. 133 3.7. Completing Remaining Endpoints ...................................................................................... 142 3.7.1. Category .................................................................................................................... 142 3.7.2. Product ...................................................................................................................... 144 3.7.3. Routing ...................................................................................................................... 149 3.8. Trying DBeaver ................................................................................................................... 150 3.9. Review ............................................................................................................................... 157 Reference .................................................................................................................................. 157 Table of ConTenTs
Page 7
vi Chapter 4: Tower Middleware 159 4.1. What Is Middleware? .......................................................................................................... 159 4.2. Adding Middleware Layers ................................................................................................. 161 4.2.1. Timeout Layer ............................................................................................................ 162 4.2.2. Logging Layer ............................................................................................................ 163 4.2.3. Compression Layer .................................................................................................... 166 4.3. Example: Creating a JWT Authentication Layer ................................................................. 173 4.4. Review ............................................................................................................................... 186 Chapter 5: WebSocket 187 5.1. Exploring WebSocket ......................................................................................................... 187 5.2. Using WebSocket ............................................................................................................... 189 5.3. Concurrent WebSocket Connections .................................................................................. 198 5.4. Authentication Headers ...................................................................................................... 207 5.5. Review ............................................................................................................................... 213 Chapter 6: Project: Building a Chat Service 215 6.1. Project Overview ................................................................................................................ 215 6.1.1. What Is SSE? ............................................................................................................. 217 6.1.2. Code Repository ........................................................................................................ 218 6.2. Hands-on............................................................................................................................ 218 6.2.1. Project Setup ............................................................................................................. 219 6.2.2. Creating SSE Endpoints ............................................................................................. 221 6.2.3. Configuration Management and Database Connection ............................................. 227 6.2.4. Creating REST API Endpoints ..................................................................................... 237 6.2.5. Building the Frontend ................................................................................................ 245 6.2.6. Automated Testing ..................................................................................................... 247 6.2.7. Production Readiness and Deployment ..................................................................... 251 6.3. Review ............................................................................................................................... 255 6.4. Closing ............................................................................................................................... 255 Index 257 Table of ConTenTs
Page 8
vii About the Author Indo Yoon is a software engineer at SAP Labs Korea specializing in Python, Rust, and Go. A Seoul National University alumnus, he extends his impact beyond code as a frequent speaker and technical author. With a strong focus on web services, Indo is dedicated to advancing the developer community through his lectures and written works.
Page 9
ix About the Technical Reviewer Joshua Mo is a software engineer and technical writer specializing in Rust, AI infrastructure, and web development. He is currently the project lead for Rig, an open-source Rust framework for building agentic and AI-driven systems, where he focuses on system design, reliability, and developer ergonomics. Previously, Joshua worked at Shuttle, where he wrote many articles on using Axum, helped drive Rust adoption across companies, and supported developers learning async Rust and modern Rust web frameworks. He is known for translating real-world engineering experience into practical, production-focused guidance.
Page 10
xi Acknowledgments I am deeply grateful to my wife for her unwavering support and patience throughout the writing of this book. The countless late nights and weekends I spent at my desk were made possible only by her understanding, encouragement, and the extra responsibilities she quietly shouldered at home. This book would not exist without her.
Page 11
xiii Introduction This book introduces Axum, a modern Rust web framework. Through practical code examples, you'll learn to build production-ready backend applications—from basic routing and database integration to middleware and real-time WebSocket communication. Whether you're new to Rust or an experienced developer exploring new frameworks, this book provides a hands-on path to mastering Axum.
Page 12
xv About This Book This book covers Axum, a Rust backend framework. Axum is developed by the Tokio project, Rust’s most prominent project, and is the fastest-growing Rust framework. Currently, no books specifically focus on the Axum framework, either domestically or internationally. We wrote this book to promote Axum, which has tremendous growth potential, and to help more people adopt it. We explain Axum’s unique user-friendly approach through actual code examples. We’ve focused on features essential in real-world development and structured the book so you can build a complete backend application simply by following along. We provide concise explanations of Rust programming basics and backend technologies while covering each functional component in detail, helping you naturally understand Axum’s architecture. Through this book, we hope you’ll fully experience the appeal of Rust and Axum, and we look forward to seeing many more projects adopt this powerful combination. Target Audience This book will be especially helpful for the following readers. Readers Who Want to Learn Rust If you want to learn Rust through this book, you’ll master core concepts and important syntax in each chapter. We cover many examples where you can actually apply each concept, giving you an opportunity to learn Rust quickly. Readers Who Want to Try a New Project If you’ve learned Rust and want to create your own project, especially web-related projects, this book is ideal. Since Axum actively utilizes Rust’s strength in asynchronous programming, you’ll get an opportunity to learn new things while reviewing Rust’s core concepts.
Page 13
xvi Readers Who Want to Write a High-Performance Web Server This book covers various practical techniques including database configuration, middleware construction, and implementing Server-Sent Event (SSE) endpoints. Whether you’re building high-performance servers for work or side projects, this book will help you achieve your goals more quickly. Prerequisites We recommend having some background knowledge of Rust to read this book, though it’s not required. For readers encountering this content for the first time, we’ve included brief background information and related explanations at the beginning of each chapter. For Rust basics, familiarity with the following concepts is helpful. If you’re new to Rust, we recommend first studying Learning Rust by Comparing with Python (J-Pub, 2024), which clearly explains Rust’s fundamental syntax and concepts. • Ownership: Ownership transfer/borrowing, references • Asynchronous programming: Arc, Mutex, async/await (tokio knowledge is helpful but not required) • Other: Structs, closures For backend server fundamentals, understanding the following is helpful. Don’t worry if you’re unfamiliar—we’ve included plenty of examples and detailed explanations to help you understand easily. • Relational Database Management System (RDBMS): This book uses PostgreSQL. Experience with other relational databases (MySQL, MariaDB, etc.) transfers easily. • SQL: Basic queries for table definition, data retrieval, and modification. • HTTP: Concepts like query parameters, path parameters, and request bodies needed for REST API design. abouT This book
Page 14
xvii Book Structure Each chapter covers the following: • Chapter 1: Introduces Rust backend development characteristics and performs environment setup for practice exercises. • Chapter 2: Examines Axum’s core components—routing HTTP requests, processing query parameters and JSON bodies through Extractors, and sharing state across the app through State. • Chapter 3: Integrates PostgreSQL with SeaORM, explores schema and migration management, completes all necessary endpoints, and modularizes the project. • Chapter 4: Examines tower middleware essentials like logging, timeouts, and authentication and applies them to the application. • Chapter 5: Explores WebSocket, a protocol for real-time bidirectional communication between clients and servers, and implements single- connection and multi-connection WebSocket handlers. • Chapter 6: Builds a complete chat service project with SSE-based real-time messaging, a React frontend, automated testing, and Docker deployment. The book is structured for easy follow-along with code and screenshots. All code is available on GitHub. If you encounter problems or have questions, please use the repository’s Discussion section. Example code can be found at • REST API example: https://github.com/Indosaram/axum- book-code • Chat service example: https://github.com/Indosaram/axum- react-chat-app The Docker image built in Chapter 6 is available at https://hub.docker.com/ repository/docker/indosaram/axum-chat-app/general. abouT This book
Page 15
1 © Indo Yoon 2026 I. Yoon, Beginning Axum, https://doi.org/10.1007/979-8-8688-2631-3_1 CHAPTER 1 Rust and Server Development Backend servers are the core of web applications. They connect frontends to databases, process and deliver data, and handle essential service operations like security, logging, and monitoring. Today, companies use many different programming languages and frameworks for backend development. What makes Rust stand out among them? Which companies are actually using Rust for their production backends? Learning Points • Why Rust excels at backend development • Real-world case studies of Rust backends in production • Essential components for Rust server development 1.1. Why Rust? To understand why Rust excels at server development, we need to first examine what makes Rust itself so powerful. 1.1.1. Advantages of Rust Rust is a modern programming language that makes it easy to build fast, reliable programs. It delivers performance nearly identical to C/C++ (about 99%), but catches memory leaks and thread race conditions at compile time—problems that have plagued
Page 16
2 C/C++ developers for decades. This combination of high performance and high safety has made Rust the most desired language among developers for eight consecutive years in Stack Overflow’s global developer surveys [1]. Beyond performance and safety, Rust’s popularity stems from its excellent developer experience. As a modern language, it features elegant syntax and clear style guidelines that help you write correct code. Features like pattern matching and closures let you express complex logic concisely and efficiently. The compiler acts like a pair programmer—it not only identifies problems but also suggests solutions, helping you write the code you want faster. Rust also provides a convenient toolchain. A single toolchain called cargo handles everything from building and deploying to installing and updating dependencies. Additionally, rust-analyzer analyzes your source code in real time and provides immediate feedback as you write. It provides code completion, references to the code, type hints, and inline error messages in IDEs such as Visual Studio Code. Detailed instructions will be covered later. 1.1.2. Advantages of Developing Backends with Rust The advantage of developing backend servers with Rust is that you can easily build servers with both high performance and safety. For example, developing servers with JavaScript or Python often means hitting language-imposed performance limitations or spending significant time resolving thread race conditions and other concurrency issues. Even Java, widely used in Korea, can experience delays in server response times due to garbage collection pauses. In short, Rust is the ideal language for developing large-scale servers that require heavy CPU computation. 1.2. Rust Server Development Case Studies Leading tech companies like Microsoft, Cloudflare, Facebook, and Amazon are already actively adopting Rust for their backends. In Korea, companies like Kakao and Korbit have also adopted Rust as their backend language. Let’s examine some famous cases where companies used Rust to solve problems like concurrency limitations and performance degradation from garbage collection. Chapter 1 rust and server development
Page 17
3 1.2.1. Figma Figma is a browser-based UI prototyping tool. Reflecting design shapes and functionality to users in real time is crucial. However, as the service grew, increased user load caused the existing TypeScript server’s CPU and memory usage to spike, leading to longer response times. To solve this, they decided to rewrite the server in Rust. The results were dramatic: compared to the TypeScript server, memory usage improved by up to 3.8x and response times improved by up to 16.4x [2]. 1.2.2. Discord Discord is a messenger service for text and video chat. As the service grew, they discovered periodic performance drops in their existing Go-based backend server. In the graph in Figure 1-1, the sections with periodic spikes represent the original server written in Go. You can see CPU usage spiking periodically, temporarily overloading the server and causing response times to increase cyclically. This was caused by Go’s garbage collector—while it periodically removes unused objects from memory, all other operations must pause. After rewriting the server in Rust, CPU usage stabilized and response times became much shorter. Figure 1-1. Discord Server Performance Chapter 1 rust and server development
Page 18
4 1.2.3. Dropbox Dropbox is a leading cloud storage service with millions of users worldwide. One of Dropbox’s core features is rapidly synchronizing files and folders on local computers with remote storage. However, as the service scaled, they faced difficulties maintaining and improving the C++-based synchronization logic. To solve this problem, Dropbox decided to rewrite the synchronization logic in Rust. This enabled the Dropbox team to develop high-performance concurrent programs more productively. 1.2.4. npm npm is the package repository for Node.js, a JavaScript runtime environment. Developers can easily install and manage libraries and tools through npm. However, as more users and packages were registered, npm faced performance degradation and stability issues. To resolve server bottlenecks, the development team considered various programming languages and even attempted actual implementations. Node.js, Go, and Java were candidates, but Rust was ultimately chosen. With the introduction of Rust, both server performance and stability improved significantly. 1.3. Comparing Rust Backend Frameworks Thanks to Rust’s many advantages, many people have become interested in Rust server development. As a result, numerous Rust backend frameworks are being developed. Since each framework has its own philosophy, design patterns, and coding approach, you should choose a framework appropriate for your environment. Especially in production, it’s advisable to select a popular, well-maintained framework. The following are the four most widely used among famous Rust frameworks: • Rocket: Rocket is often used with Diesel ORM. It’s designed with a focus on safety, flexibility, and security, but may not be suitable for large-scale or high-performance projects. It’s developed by individual developers and has a history of development pauses. Chapter 1 rust and server development
Page 19
5 • Actix-web: Actix-web has the highest performance among Rust frameworks. However, since most functionality must be handled within the framework, it has a high barrier to entry and requires implementing many features yourself. It’s well-suited for small-scale web apps like microservices. • Axum: Axum focuses on both usability and performance. It uses Rust asynchronous programming patterns and has high compatibility with third-party crates, making it relatively simple to build high- performance servers with various features. • Warp: Warp is known for its filter system. It’s relatively less popular than the other frameworks. Looking at various benchmarks, Axum, Actix-web, and Warp show no significant performance differences. Rocket is slower in some cases, but overall shows similar performance to the other frameworks. Therefore, when choosing a Rust backend framework, usability should be prioritized over performance. 1.3.1. Why You Should Use Axum 1.3.1.1. Good Flexibility and Scalability Rust doesn’t provide an async runtime at the language level. An async runtime is what executes and manages asynchronous functions. For Rust, you must choose between tokio and smol. Each runtime has slightly different purposes and implementations, so you can choose one appropriate for your situation, but generally you should use tokio, which supports everything from embedded systems to large-scale programs. Chapter 1 rust and server development
Page 20
6 Figure 1-2. Tokio Ecosystem The Tokio project to which tokio belongs forms one massive ecosystem built from libraries for creating fast and reliable network applications. It includes many libraries such as tokio for creating async runtimes, tracing for logging systems, and hyper for HTTP servers. Axum is a server framework created specifically to properly use tokio and hyper, so it integrates smoothly with other libraries in the Tokio ecosystem. In particular, it integrates very conveniently with tower, a middleware crate that’s widely used in other frameworks and has various middleware functionality pre-implemented. For these reasons, Axum is the most suitable choice if you want to easily integrate and use the various features provided by the Tokio ecosystem. Chapter 1 rust and server development
The above is a preview of the first 20 pages. Register to read the complete e-book.

Recommended for You

Loading recommended books...
Failed to load, please try again later

Tip the Site

Scan the WeChat Pay or Alipay code to tip. No login required.

WeChat Pay
Alipay
← Back to List