Practicalities of Using Microservices and Nanoservices
local graph
Chapter 18 — Practicalities of Using Microservices and Nanoservices
Section titled “Chapter 18 — Practicalities of Using Microservices and Nanoservices”18 Practicalities of Using Microservices and Nanoservices
Section titled “18 Practicalities of Using Microservices and Nanoservices”Throughout the book, we have been building our system in isolation. However, in real life, we know that we will not be building systems in isolation without any input from other developers. For most projects, you must coordinate with other developers and integrate with legacy systems. There are no black and white approaches, but trade-offs. In this chapter, we explore the positive and negative effects of microservices in relation to collaborating with other developers and managing a complex system. We will also highlight how nanoservices can help improve these trade-offs. We also cover some coding exercises in managing private code and distributing that code in builds and deployments, and how to directly integrate our Rust nanoservice into another language, such as Python. If you do not ever plan to code in Python, do not worry; the integration technique utilizes C interfaces that enable us to interact with other languages. Most other languages will also be able to interact with our Rust code using the same method. In this chapter, we cover the following:
- When to use nanoservices, microservices, and monoliths
- Managing private repositories with dockpack
- Integrating Rust nanoservices with other languages using C interfaces
By the end of this chapter, you will be able to understand the drawbacks of microservices. However, you will also understand the benefits and how to leverage the benefits of microservices and avoid the drawbacks by using our nanoservice approach. You will also be able to package and distribute private code files using Docker and integrate that Rust code with most other languages. These skills will help you tackle real-world projects, as opposed to simply claiming that you can code a Rust web application in isolation.
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. Practicalities of Using Microservices and Nanoservices
When to use nanoservices, microservices, and monoliths
Section titled “When to use nanoservices, microservices, and monoliths”If you go online to check whether microservices are a good idea, you will not have to go far to see extremely simplistic takes: microservices are either the future of web development or they are a complete sham and make your system worse. Of course, the truth is somewhere in between; microservices offer benefits and drawbacks.
The negative effects of microservices
Section titled “The negative effects of microservices”Microservices can seem appealing because of their small services that do one thing and are isolated. When I built my first Kubernetes cluster, I was excited by this very image. My coding days would be bliss because I could just focus on this one small service, test the service, and then deploy that service into the bigger system. We have all worked on big, sprawling code bases that were hard to navigate, but microservices also run the risk of providing a terrible developer experience. Let’s cover these pitfalls, starting with container orchestration.
Container orchestration
Section titled “Container orchestration”We started our journey with a simple to-do microservice and built an authentication microservice to handle the logging in and creation of users, giving us the layout in Figure 18.1:
Figure 18.1 - A basic microservice structure
Already, we have violated a rule of microservices. Microservices should be independent of each other. We could separate the microservices by putting all authentication data into a token, with things such as the user role, as well as the ID. However, being able to keep track of the session statistics in real time would require access to a service. Our requirements also evolve over time. What if we need even more data from the user account? It would not be unreasonable for users to be housed under organizations and departments. When a user creates a to-do list for a department, we would have to check that the user has the authority to do this and that the department exists before entering it into the database.
[figure outside: Figure 18.1]
On top of this, we will want emails sent if a user is added/removed from a group/department. If we get a login from a different device, we may also want a warning email, and we will want to use an email with a link and a UUID to prove that the user has access to the email they say they do when registering the account. It is also reasonable to email the user if they close a to-do list. Our structure has ballooned very quickly to what we see in Figure 18.2:
Figure 18.2 – More complex microservice structure
Here, we can see that they are all connected somehow. Maybe I have worked with the wrong people and practiced bad software engineering all my life, but in my experience, I have never seen a production system that solves real-world problems, where they have managed to keep all the microservices truly independent of each other.
Database for the email server?
It may seem strange to have a database for an email server. However, we must log sent emails and define rules around them. Sending emails generally consists of hitting a third-party API such as Mailchimp and sending emails. However, we must have control over how and when we send these emails. A simple example of this is rate-limiting the emails on the register user page. A simple hack is for a malicious actor to repeatedly copy and paste someone’s email address into the registration form and click register. They could do this all day, and the victim’s email address would be flooded, and would rack up massive bills with the email provider. If we have a register email endpoint in our email service, we could log the email address and the IP of the request. We could then check the email logs before sending an email. If there has been up to three within the hour, we could just not send the email to the email API. If the same IP address has spammed more than 5 emails within an hour, we could also put in cooldown measures.
[figure outside: Figure 18.2]
When it comes to local development, these services will end up, over time, having different dependencies and versions of those dependencies, so we are probably going to need to run these services in Docker. In theory, just pulling these services from Docker Hub and running them using docker-compose seems straightforward. However, this is unlikely to happen. We can demonstrate this by adding departments and teams to to-do lists. This will require, at the very least, the org service, auth service, and to-do service. We start with our org service. However, it would be naive to code the logic for our org service and just push it to Docker Hub because, as we are building the feature into our to-do service, we will likely realize that we need to go back and tweak the code of the org service. This back and forth between services, tweaking the code, can result in you sitting around waiting for Docker builds locally in different repos until the feature is consistent across all the services required. This can be mitigated with clear APIs and careful planning, but for a small team that just wants to build the feature, this is going to seriously tank your productivity.
This is where nanoservices helped me out. I was halfway through building a custom Docker tool that downloaded a microservice, scanned the downloaded microservice for other microservices that it was dependent on, and repeated the process until all the required services were downloaded. Builds were taking forever, and I would change the code in another service, need to do a release for that service, and then run the Docker builds again. Development time crawled to a snail’s pace, but we wanted to still have the isolated modular code without all the Docker builds, network setup, and debugging when trying to run the code I had just written. As we have discovered throughout this book, nanoservice builds are much quicker, and we do not have to worry about setting up and configuring networks between multiple servers with config variables to get our entire system running and talking together. But container orchestration was not the only problem. As our system grew along with the developer count, our services would essentially be flying blind.
Flying blind
Section titled “Flying blind”Let’s say that you are a developer who has been assigned the task of maintaining the organization’s service. You understand that one of the benefits of microservices is that they are isolated and flexible. You want to be able to keep your microservice as independent as possible. You have an endpoint that verifies that the user is associated with the correct department so that they can create a to-do item. However, you also need to have a certain role or tag associated with the user account to allow this. The to-do service may have checked the auth service, but there is no way for you to verify that it has actually happened. Also, what if the to-do service changes later and they stop checking? You do not want to be responsible for allowing unauthorized users to create that to-do item. What is more is that there might be other services wanting to perform the same check later. For instance, there might be a project management service that needs to check whether a user can write to a to-do list before assigning them to that project. You are a good developer. You do not know what the future will hold and what services will call your organization’s service. Other services may not do checks with the auth service. So, you check the department/team, and the auth service for the user role before approving the creation of a to-do. As we can see in Figure 18.3, we have ended up calling the auth service twice:
[figure outside: Figure 18.3]
Figure 18.3 – Flying blind resulting in multiple calls to the auth service
If the project management service also makes a call to the auth service, then we have two unnecessary calls to the auth service.
If you think I am trying to concoct a situation that would not happen as developers could just talk to each other, following is a link to an interview of a principal engineer on his experiences implementing microservices at DoorDash. Here, he reveals that the account service is called roughly 300 times when an order is placed, as all these services want to get information about the account:https://youtu.be/LcJKxPXYudE?si=MdszJ15fLz-bgfCR.
For our nanoservices, our networking layer can make a network request to get information from another service and pass the data from that service into the core function. If we compile our services into one binary, we can just get the account information once and pass it into whatever core functions are requesting account information when we call those core functions.
[figure outside: Figure 18.3]
Flying blind causes more than just excessive calls; it also makes us blind to circular dependencies. For instance, service A could depend on service B, which depends on service C. But then, service C depends on service A, as shown in Figure 18.4:
Figure 18.4 – Circular dependency in microservices
Now, if we were coding in modules, our compiler would recognize the circular dependency and refuse to compile. However, in microservices, our processes are isolated from each other and run in their own memory. Our compiler cannot pick this up, as our dependencies are satisfied by network calls. By compiling all our servers into one Rust binary, we at least get a sanity check that we do not get circular dependencies because the compiler would pick this up. We can still choose to deploy as microservices if we want. Network calls do not just increase the risk of flying blind; they also cost more.
Network calls are expensive
Section titled “Network calls are expensive”One last key drawback that we will cover is the latency of microservice systems. With a network call, we must serialize the data, send it over a network, and wait for its response. This is a lot slower than calling a function in memory. Compiling all our services in one binary will result in faster and less computationally expensive service calls and be less computationally expensive. To really demonstrate this, we can compare the steps between the two approaches. First, we can lay out the steps for a function call from a traditional monolith or a monolith constructed by nanoservices:
- Pass arguments into the function: The function is already part of the process, so it is already in memory. For the arguments, we pass in pointers to variables allocated in memory.
- Execute function: The CPU executes the function, accessing shared memory and resources, so no need for serialization.
- Return result: The result is returned and written to memory with minimal overhead.
[figure outside: Figure 18.4]
This process is usually measured in nanoseconds or microseconds, depending on the complexity of the function and system performance. For our network request, we must follow the following steps:
-
Serialize request data: This is where we format the request data into an acceptable format, such as JSON. This is essentially all the steps in our function call example in the first step.
-
Establish a network connection: This can vary depending on the network connection, but in general, packets of data are sent between the client and server as a handshake, multiple times, to establish that a connection is made. This involves multiple function calls and latency across the network.
-
Send data: We then send data over the network for the request. Due to packet loss, retransmissions are sometimes needed.
-
Receive data: There will be network latency, but once the response is received, we must deserialize the response data. Since networking can be unreliable, extra overhead of timeouts and retries is also involved when monitoring the connection.
Network calls are generally measured in milliseconds or more, depending on the network. This means that jumping from a function call to a network call can result in going from seconds to seconds. It is not surprising that AWS video streaming saved 90% on their server bills when they switched from microservices to a monolith, as seen at the following link: https://www.thestack.technology/amazon-prime-video-microservices-monolith/.
While it is important to be wary of the downsides of microservices, they also have some benefits. We can now move on to discussing the benefits of microservices.
The positive effects of microservices
Section titled “The positive effects of microservices”While there are plenty of drawbacks to microservices, there have been cases where I have been grateful that I have worked on a microservice system. We can start with the most obvious benefit, which is rolling out releases.
Rolling out releases
Section titled “Rolling out releases”When the team grows, working on monolithic code bases can be a nightmare. In an ideal world, the code in the monolith is well-structured with clear boundaries. However, I have rarely seen this be a reality. When there are seven or more developers working on the same monolithic repository, merging your code can grind to a halt. For instance, you are asked to add a feature, and your feature requires some account data from the auth module. This is fine; you call a function from the auth module to get the account data, then use it in your feature. You write some tests, they pass, then you push your code to the GitHub repository and make a pull request. However, another developer is working on a separate feature that also uses the account data. The developer realizes that they can make some tweaks to the function to require a slightly different parameter but less data, so they alter this function and every function call in the code base. They then merge before you into the monolithic code base. Suddenly, you have conflicts everywhere, and you must merge the latest changes into your branch and rewrite sections of your code to adapt to the new changes. In extreme examples, I’ve seen developers rewrite their feature up to six times before they are lucky enough to get the feature merged. Practicalities of Using Microservices and Nanoservices
If there is a tight deadline, then seniors are incentivized to tell other developers not to tidy and refactor code as they go along, as refactoring and tidying code can step on the toes of other developers trying to fix bugs or add features. This can lead to developers being unwilling to refactor and tidy code, for fear of getting in the way of others, which can lead to terrible ball-of-mud code bases.
Another problem is building times. As the system grows, the time you need to wait before a build and integration test is done will also grow. The speed of feedback is very important not only for development speed, but also for keeping in the mental flow of the problem that you are solving. Of course, unit tests rock for this. However, if you must wait 30 minutes for a build to finish, you must orchestrate your releases. Based on continuous integration pipelines and how much money you are willing to spend on them, you may also have to wait for other developers pushing to the repository, as their builds also need to pass. Basically, monoliths suffer from developer contribution congestion. With microservices, a small team can continue to push new features to a small service. They can quickly coordinate between themselves with minimal overhead. The team can also keep their APIs consistent with versioning, adding deprecation warnings to the old API versions, and coming up with a timeframe to phase out the old API endpoints. While microservices are slower with the network calls, the clearly enforced boundaries can increase the stability of the APIs and free up developer resources when trying to get new features out the door. While API isolation is important, code isolation has also been a massive win for microservices.
Isolation of code
Section titled “Isolation of code”When it comes to criticizing microservices, most people acknowledge that developers tend not to develop perfect microservice systems. However, the same can be said for monolithic code. Bad code is a bit like oil in water. We only need a bit of oil to contaminate the whole thing. Once bad code starts to creep in, there is a chance that it will continue to grow. Even if you have hard-working, driven developers trying to maintain the quality of the code, these developers are not everywhere all the time. Code can get rushed to meet deadlines for releases and features. I have personally gone on holiday, only to come back to code bleeding into an isolated module that I worked very hard to keep isolated with a clean interface. I worked overtime to rip out the offending code and have it interact with the module via the interface. Sadly, if the extent of the damage is big, it can make it hard to justify refactoring the coupled code to managers. This makes the damage more at risk of growing over time.
Microservices in their own GitHub repositories are more complex to orchestrate. However, they do isolate code. You could have a couple of bad, lazy, or rushed developers completely trash the structure of a microservice. Sure, it is not a fun experience, and you should try to implement systems where these developers do not degrade the quality of your system. However, the damage is isolated to that microservice. It did not bleed over into the entire system. The worst-case scenario is that you order a complete rewrite of that individual microservice. In fact, a good friend of mine who is a lead developer leans into microservices for the initial development phase. His philosophy is that the first application that you write will always need to be rewritten, because you do not know all the requirements yet. He has his team do quick iterations of the application in a series of microservices, quickly getting feedback, and rushing those features to get more quick feedback. Once he’s happy with the spec, he then has his team work through each microservice, rewriting each service one by one. He is a big fan of asking the question, “If you knew what you know now, how would you approach solving the problem?” The isolation of code via microservices has also led to the flexibility to experiment.
Flexibility to experiment
I was lucky enough to take complete ownership of a complex web system for the German government. Our system was initially a Python monolith. Then it grew to Python microservices. The system then moved over to Rust and formed the basis of this series of Rust and web programming books. We have the freedom to experiment with different approaches to Rust and web development in a bigger setting. However, we both acknowledge that microservices made the switch a possibility. Our system was being used by paying customers. It was not a toy project; we could not just go away and rewrite the entire system in Rust. Ongoing support is a thing, and new features needed to be added. Also, the system needed to keep running. Microservices made the switch to Rust a possibility.
If we had one large Python monolith and we wanted to replace that monolith with a Rust monolith, the rewrite would be massive. On top of this rewrite, the system was still live, so new features were being requested and patches were being pushed. Therefore, our monolith rewrite would be an ever-growing moving target. Large, growing moving targets are close to impossible to replace. However, because we had microservices, between adding features and patches, we could target a microservice that was not getting a new feature or patch for that sprint and rewrite it in Rust. While our system was live, and our customers were happy, we were replacing our Python servers with Rust servers seamlessly. Because we took the approach of nanoservices, we compiled a range of Rust services into one binary to make the deployment and container orchestration easier. But remember, these nanoservices are in their own repositories with their own layers. If we needed to revert one of the services back to Python, we could burst out the binary into their own microservices, swap the targeted server back to Python, and then compile all the other Rust servers back into one binary, making network calls to the Python service when needed.
We can conclude that microservices enable you to try a new web framework, coding approach, language, network protocol, or data storage method without too much commitment or disruption to the rest of the system in a new repository. Furthermore, rolling back to the previous repository if the experiment does not go to plan is simple, as the network protocols can facilitate communication between parts of the system. Your old service can just slot back in and start running if you have kept the API the same.
We have now covered enough about the positives and negatives of microservices to illustrate that there are some nasty pitfalls to them. Microservices bring their own problems. However, we can also see that it is not rational to jump onto the bandwagon of hating microservices, as microservices also reduce developer congestion and enforce code isolation. We can also see that nanoservices are the best of both worlds. They can keep the build in one binary if needed, reducing the cost of orchestration. However, they also maintain the isolation and developer flexibility that microservices offer. But what about accessing all these different repositories when running a build? It is unlikely that you are going to have all your repositories open source. To keep code isolated and flexible, we could either have different workspaces in a mono-repo, like what we have been doing throughout the book, or we could have multiple repositories pulled together for a build. Personally, I prefer multiple repositories because you can give certain people certain access to some repositories and not others. When collaborating with freelancers or other companies, giving these people access to 100% of your code because you have a mono-repo is never a good idea. But how does one repository access code from another repository? This is where dockpack comes in. Managing private repositories with dockpack
At the time of writing this, authenticating access to GitHub repositories can be surprisingly tricky when configuring continuous integration. Cargo builds can directly point to GitHub repositories, but I have found that there are clashes in the caching. Two workspaces pointing to the same repository, on the same branch, still ended up having clashes when trying to reference the same structs. Managing private crates was a nightmare until I used Docker to distribute our code files for builds. Using Docker to distribute files has the following benefits:
- Docker handles your authentication seamlessly in deployment systems and continuous integration pipelines
- Docker handles your version control and tagging
- Docker caches the layers of the image, meaning that if your new version only changes a couple of layers in the image, then those layers are the only ones that get pulled
- All major cloud providers support private Docker registries
We can distribute our private code files using a tool I built, called dockpack. We can install dockpack with the following command:
cargo install dockpackNow that we have dockpack installed, we can test it with the following command:
cargo install dockpackdockpack pull -i maxwellflitton/nan-one -d cacheThe -i argument is the Docker image that we are targeting, and the -d is the directory the Docker image is going to be unpacked into. Our command gives us the following file outline:
cache
├── Cargo.toml
├── src
│ └── lib.rs
└── tar
├── maxwellflitton_nan-one
│ ├── blobs
│ │ └── sha256
│ │ └──
[
{ "Config": "blobs/sha256/b26452 . . .", "RepoTags": [ "maxwellflitton/nan-one:latest" ], "Layers": [ "blobs/sha256/6c6797329a . . ." ] }]Here, we can see that the config is a blob file, and the layers are also blob files. Blob files are also TAR files. TAR files are essentially binaries that contain file content and metadata for the file content, such as relative path, permissions, and format. Because these files have the metadata in the binary header, we can have one binary that stores multiple files, and we can loop through the binary, unpacking the data for each file, and placing it in the right path in the right format due to the headers. The name of the TAR files is a hash value. This is so we can load the data from the binary TAR file and hash the data. If the data has not been compromised, then the hash will match the name. If we want to unpack the files inside the Docker image, then we loop through the Layers blob files, unpacking them and placing them where they need to be. If we want to know the commands and environment variables used to build the Docker image, we can open the blob file pointed to via the config key. The config file is not a binary, but a JSON file, which has the following contents:
{ "architecture": "amd64", "config": { "Env": [ "PATH=/usr/local/sbin:", "/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" ], "WorkingDir": "/", "OnBuild": null }, "created": "2024-04-24T13:12:25.567631648+01:00", "history": [ { "archived": "2024-04-24T13:12:25.567631648+01:00", "modified": "2024-04-24T13:12:25.567631648+01:00", "modified_time": "2024-04-24T13:12:25.567631648+01:00", "modified_by": "root@localhost:/home/root" ] }}"created":"2024-04-24T13:12:25.567631648+01:00","created_by":"COPY ./nan-one . # buildkit","comment":"buildkit.dockerfile.v0"}],"os":"linux","rootfs":{"type":"layers","diff_ids":["sha256:59aa253f0cd78e6605ba2cf335808d3983ca","4ad713f5bd7a9f4383445193860b"]}}A lot of it is self-explanatory at this stage in the book, as we have built our own images in previous chapters. However, if we look at the created_by key, we can see how our image was created. We just copied the files in a directory called nan-one into the Docker image. This leads us on to how we can package our own code. We can package our own code by using the scratch image, which essentially has nothing in it. We then copy the files of a directory into it using the following code:
FROM scratch
COPY ./some_dir .
We can then build our image and push it with the following command:
docker build . \--platform linux/amd64,linux/arm64,linux/arm/v7, \linux/arm/v6,linux/s390x, linux/ppc64le \-t <IMAGE_REPO> \--pushHere, we can see that we build the Docker image, tagging all the platforms to say that computers running on chips and operating systems can also run our Docker image, as we are just unpacking files. We then tag the build with the image repository that we are going to push to and then push to the Docker repository using the —push command. With this, you can now package your private code.
Being able to distribute your private code is essential for building most systems. But what if your Rust nanoservice wants to be integrated into another program written in another language? This is where we rely on C interfaces.
Integrating Rust nanoservices with other languages using C interfaces
Section titled “Integrating Rust nanoservices with other languages using C interfaces”At the time of writing this book, Rust does not have a stable application binary interface (ABI). This means that we cannot compile Rust binaries and interact with these Rust binaries using another language. However, C has a very stable ABI. C’s simplicity and maturity make C very portable. A programming language called Zig is attempting to replace C for portability. But at the time of writing this book, C seems like a good choice. However, we will keep an eye on Zig for future editions of this book.
For our example, we are going to build a basic Rust library that then gets compiled into a C library so it can be used by a simple Python program, as seen in Figure 18.5. It must be noted that, although we are using Python in the example, we can use C interfaces for most other programming languages.
Figure 18.5 – Layers to integrate Rust with a language such as Python
The diagram in Figure 18.5 looks like our nanoservices that we have been building throughout the book. The Rust Lib is our core, and the C Interface is like a networking layer, but for calling our Rust code from another language. If I were to place this C interface in our nanoservices system, it is essentially the same level as the networking layer, so I would either put the C interface in the networking directory or create another directory called binary_interfaces, as WASM might also go into the binary_interfaces directory if we were to support a WASM interface for our nanoservices.
For our exercise, we have the following file layout:
| ├─ Cargo.toml | | | | ├─ main.py | | | | ├─ to-do | | | | └─ Cargo.toml | | |
[figure outside: Figure 18.5]
| src | ||
|---|---|---|
| lib.rs | ||
| to-do-c | ||
| Cargo.toml | ||
| src | ||
| lib.rs |
Here, we can see the two Rust workspaces, which are the Rust library and the C interface. As the Python example is just going to be loading the Rust code via the C interface and using it, all our Python code is just going to be in the main.py file in the root of the project. We can start our project by creating our to-do library.
Creating our to-do Rust library
Section titled “Creating our to-do Rust library”For our Rust library, we are just going to have a to-do item, and that is it. At this stage in the book, you will be able to build this yourself, so we are just going to whiz through our setup. Our dependencies are the following code:
## to-do/Cargo.toml[package]name = "to-do"version = "0.1.0"edition = "2021"
[dependencies]serde = { version = "1.0.210", features = ["derive"] }In our library, we just define a basic to-do item with the following code:
//! to-do/src/lib.rsuse serde::{Deserialize, Serialize};
#[derive(Deserialize, Serialize)]pub struct Todo { pub title: String, pub status: String,}And that is it, our module is done. We are not trying to build anything comprehensive; we are just trying to get our Rust code interacting with other languages via C interfaces. Finally, our cargo file in the root of our system has the following layout:
## Cargo.toml[workspace]resolver = "2"members = [ "to-do/", "to-do-c/",]Now our system is ready to support our C interface.
Creating our C interface
Section titled “Creating our C interface”Our C interface essentially wraps our to-do library and compiles to a dynamic C library. For us to achieve this, our Cargo file has the following layout:
[package]name = "to-do-c"version = "0.1.0"edition = "2021"[dependencies]to-do = { path = "../to-do" }serde_json = "1.0.128"
[lib]crate-type = ["cdylib"]Here, we can see that we compile our to-do library into our interface. We also have a JSON dependency. This is because we will be using JSON to transfer our data between the C and Python interface. JSON will make our data transfer easier, as we will see when we build our interfaces. It also must be noted that we define crate-type as a cdylib. This means that we will compile our code as a dynamic C library. We will compile the library once, and then multiple applications can link to that library. This is the opposite of a static library, where the static library is compiled into the application. Our to-do library is a static library as it is being compiled into the to-do-c library. Static binaries are beneficial because they make the deployment easier due to the library being compiled into your binary, resulting in fewer moving parts. Static binaries also benefit from compiler optimization in relation to your program. However, dynamic libraries are also useful. Because dynamic libraries are not compiled into the program, other languages can link and use them. For instance, Python would not be able to compile our Rust code into it. Apart from being a different language, Python does not even compile its code. Dynamic libraries also reduce the binary size. For instance, if we have five applications relying on library A. If all the applications statically link to library A, then library A will be copied 5 times and compiled into each application. However, if the five applications all dynamically link to library A, then they just load the same library at runtime, and the five application binaries do not have library A in each binary. Dynamic libraries can also reduce the compile time. If you have a massive system, and you need to recompile a binary, if the recompilation does not need to compile loads of static libraries, then it will be quicker. Like everything else in engineering, there are always trade-offs. Now that we understand our build, we can move on to creating our C interface with the following imports:
//! to-do-c/src/lib.rsuse std::ffi::{CStr, CString};use std::os::raw::c_char;use to_do::Todo;For the first import, we are using the ffi crate in the standard library. FFI stands for foreign function interface, which is essentially an interface with C and C datatypes. We will be using FFI from the Python standard library to interface with our C interface when we write the Python code. Google FFI for any programming language that you are interested in, and I will honestly be shocked if the programming language cannot interface with C using FFI.
For our FFI imports, CStr is a borrowed C string. CString is a reference to CStr. CStr essentially converts the C string type to a string that is compatible with Rust. CString allows developers to get mutable access to the string. CString also takes ownership of the string, dropping the string from memory once it moves out of scope. Our c_char is the representation of a character in C, as the format is different to how Rust represents characters.
Now that we have these imports, we can define our API function signatures with the following code:
//! to-do-c/src/lib.rs . . . #[no_mangle] pub extern "C" fn create_todo_json(title: *const c_char) -> *mut c_char { . . . }
#[no_mangle] pub extern "C" fn mark_done_json(todo_json: *const c_char) -> *mut c_char { . . . }We can see that in both functions, we return a mutable reference to a character. This might seem strange as we are returning the JSON string of the entire to-do item. The pointer points to the start of the string. If we want to read the string, we can keep increasing our pointer by one byte, reading one character at a time. When we come across a \0, we know that this is the end of the string, and we stop. Now that we understand how the pointer is used, we can see why we also pass a pointer to a character into the functions. We can recall from our WASM chapter that #[no_mangle] prevents the compiler from optimizing the function to the point of not being recognized. Instead, the signature is maintained when compiling, so we can access the function when loading our binary. The extern “C” is telling the compiler that this is a C interface. You may be wondering why we are just using JSON strings. This is to simplify the transfer of data to another language. We can pack collections into JSON, and our signature will be the same. However, if we wanted to represent a vector of to-do items and pass that over to another language, we would have to allocate a chunk of memory, chunk that memory up, and manually move the pointer over the memory to access elements in the vector. To demonstrate this, the following is a link to a GitHub repository that implements a vector in C: https://github.com/juliuskoskela/c-vec.
We are already improving our latency by not having to make network calls. Implementing C-friendly data collections is not worth the time unless you really need to speed up optimization to the point where JSON serialization is too expensive.
We can now build our interface functions. Inside our create_todo_json function, we convert our pointer pointing to the initial character of a string into a Rust string with the following code:
//! to-do-c/src/lib.rslet c_str = unsafe { CStr::from_ptr(title) };let title = c_str.to_str().unwrap_or_default().to_string();let todo = Todo { title, status: "PENDING".to_string(),};We must use the unsafe tag because this is a pointer that was just passed in. It does not have the Rust guarantees. We then construct our to-do item with the title string we converted from the pointer. We then convert our to-do item into a JSON string, then into a C string, and return the pointer with the following code:
//! to-do-c/src/lib.rslet json = serde_json::to_string(&todo).unwrap_or_default();CString::new(json).unwrap().into_raw()We can see that the into_raw function exposes the raw pointer. Because we return the raw pointer, the language interfacing with our nanoservice can then take that pointer and load a function its own way.
For our mark_done_json function, we construct the string from the pointer, just like we did before, with the following code:
//! to-do-c/src/lib.rslet c_str = unsafe { CStr::from_ptr(todo_json) };let json = c_str.to_str().unwrap_or_default();We then create the JSON string and return the pointer, as we did before, with the following code:
//! to-do-c/src/lib.rslet updated_json = serde_json::to_string(&todo).unwrap_or_default();CString::new(updated_json).unwrap().into_raw()And with this, our C interface is complete. We can now interact with our Rust nanoservice with Python.
Interfacing with our Rust nanoservice with Python
Section titled “Interfacing with our Rust nanoservice with Python”In this section, we will interact with Python using raw C interfaces to learn how linking Rust works. However, if you want a stress-free way of building Python packages in Rust, use the PyO3 crate. In our Python file, we will load the dynamic C library, specify the input and output types, and then call these functions. First, we load our dynamic C library, depending on the system, with the following code:
## main.pyimport ctypesimport platformsystem = platform.system()
if system == "Linux": lib = ctypes.CDLL("./target/release/libto_do_c.so")elif system == "Darwin": lib = ctypes.CDLL("./target/release/libto_do_c.dylib")elif system == "Windows": lib = ctypes.CDLL("./target/release/to_do_c.dll")else: raise OSError("Unsupported platform: " + system)The file extension will be different depending on the operating system that we are using. We must remember to build our Cargo workspaces in release mode for our Python nanoservice to load the dynamic C library; otherwise, the dynamic C library binary will not be there.
Now that we have loaded our dynamic C library, we can define the inputs and outputs of our functions in the dynamic C library with the following code:
## main.pylib.create_todo_json.argtypes = [ctypes.c_char_p]lib.create_todo_json.restype = ctypes.c_char_plib.mark_done_json.argtypes = [ctypes.c_char_p]lib.mark_done_json.restype = ctypes.c_char_pNow, with the inputs and outputs defined, we can build some functions that interact with our dynamic C library files with the following code:
## main.pydef create_todo_json(title): todo_json = lib.create_todo_json( title.encode("utf-8") ) todo_py = todo_json.decode("utf-8") return todo_py
def mark_done_json(todo_json): updated_todo_json = lib.mark_done_json(todo_json.encode("utf-8"))updated_todo_py = updated_todo_json.decode("utf-8")return updated_todo_pyHere, we can see that we decode the C ASCII string into utf-8. utf-8 is a more modern representation but is also more complex. ASCII is essentially a subset of utf-8 meaning that ASCII can represent fewer characters. Python’s standard string format is utf-8. However, this is not a problem for us as we have a raw pointer to the bytes, and when we read them, we can just decode the bytes using utf-8. On our interface functions, we can see that we just call the dynamic C library functions and then serialize the strings. We can now test out functions by running them and printing out the results with the following code:
if __name__ == "__main__": todo_json = create_todo_json("Learn Rust") print(f"Todo JSON: {todo_json}") updated_todo_json = mark_done_json(todo_json) print(f"Updated Todo JSON: {updated_todo_json}")If we run the Python script using the python3 main.py command, we should get the following printout:
Todo JSON: {“title”:“Learn Rust”,“status”:“PENDING”} Updated Todo JSON: {“title”:“Learn Rust”,“status”:“DONE”}
And there we have it, our Rust nanoservice can directly interact with other nanoservices from other languages without needing to make network calls.
Summary
Section titled “Summary”From this chapter, we can conclude that microservices enable developers to keep producing code, patches, and features at a quick pace without stepping on each other’s toes. However, the increased complexity of the system can lead to systems that can get convoluted and hard to manage, deploy, and develop against. We can also see that nanoservices can have the benefit of isolating code, enabling experimentation with different languages through the foreign function interface, and enabling smaller teams to do their own releases. However, also understand the build benefits of monoliths. If a monolith build gets too big, slowing down releases, we can break our nanoservices out into microservices. However, if we still want to keep the benefits of the monolith, we can also break out the core of the nanoservice into a dynamic C library and have our nanoservices communicate through foreign function interfaces. This can reduce latency as we are not making network calls, and we do not have to worry about container orchestration. For the deployment, we only need to compile the one service binary that we are swapping out. However, this dynamic C lib approach can introduce the drawback of flying blind and missing out on compiler optimization across the entire system. Here, we can see that the topics that we covered in this chapter complement each other, enabling you to come up with your own systems, with their own trade-offs, to solve the problem you need solving.
In the next chapter, we will cover queuing mechanisms for distributing workloads. 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