Learning Rust by Contributing to Blixt

Reading time:2284 words, 12 min read
Last edited:
Learning Rust by Contributing to Blixt

Between 2024 and 2025 I made four contributions to Blixt, a Kubernetes project written in Rust. It was an interesting, albeit doomed, project, and it's where I first wrote Rust in a real codebase. This post goes back through what I worked on, the Rust patterns I picked up, and the mistakes I can see now that I couldn't see then.

What Blixt was

Blixt was a layer 4 load balancer for Kubernetes. Its control plane used Gateway API, the newer Kubernetes API for routing traffic into a cluster, through the kube-rs libraries. Its data plane used eBPF, through Aya, so packets were steered in the kernel. "Blixt" is Swedish for lightning.

It started in Kubernetes SIG Network in 2022, when eBPF was the hot thing in Kubernetes networking and people wanted to try it. The README was clear about what it was: an experiment that "intentionally does not have end-users" and "a safe place to learn, break stuff and have fun." The goals while I was there were to support Gateway, GatewayClass, TCPRoute and UDPRoute, and the control plane was being rewritten from Go to Rust.

It was archived in 2025. The archive note calls it "the first official Kubernetes project in Rust," and says its goals "never really stuck."

Why I was drawn to it

I wanted to learn Rust in a real codebase, not by working through toy examples. And I wanted to go deeper on networking and Kubernetes. I'd spent a lot of my time deploying applications to Kubernetes, designing networks or debugging them, and writing "cloud native" reference architectures for government clients. I knew both well enough to use them. I didn't know them well enough to build them, and I felt they were areas where I could and should know more.

Also, I'm a sicko who would rather work on developer-facing infrastructure than user-facing product.

A sandbox with no users suited all of that. Nobody's production depended on it, so reviewers could teach instead of guarding the door.

What I worked on

Not much, honestly, but there was a lot of learning happening behind the code. Four PRs over about a year:

  1. #217, March 2024: cargo fmt and clippy in CI. I borrowed the workflow from bpfman. Clippy had complaints about the eBPF code, and I followed its suggestions verbatim, then asked the reviewers to check I hadn't done something dumb. I also learned we shouldn't rebuild the protobuf bindings on every build.
  2. #227, April to May 2024: one Cargo workspace. Every crate moved into a single workspace except the eBPF one. That crate is no_std and defines its own panic handler, and inside a workspace that collides with the standard library's: error[E0152]: found duplicate lang item panic_impl. There was also a short debate about Dockerfile.x versus Containerfile.x. Containerfile won ("I love being vendor agnostic").
  3. #280, September to December 2024: mTLS for the data plane's gRPC API. My main contribution: 12 commits, 23 reviews and three months.
  4. #360, February 2025: the GatewayClass controller in Rust. It went stale, and a maintainer rebased and merged it in June 2025, not long before the archive.

What the reviews taught me

Enums instead of optional fields

This is the lesson I'd keep if I could only keep one. Here's my first config for the gRPC server in #280, trimmed:

#[derive(Debug, Parser, Clone)]
pub struct GrpcConfig {
    #[clap(long, default_value = "false")]
    pub enable_tls: bool,
    #[clap(long, default_value = "false")]
    pub enable_mtls: bool,
    pub certificate_authority_root_path: Option<PathBuf>,
    pub server_certificate_path: Option<PathBuf>,
    pub server_private_key_path: Option<PathBuf>,
    pub client_certificate_authority_root_path: Option<PathBuf>,
    pub client_certificate_path: Option<PathBuf>,
    pub client_private_key_path: Option<PathBuf>,
}

impl GrpcConfig {
    pub fn validate(&self) -> Result<(), String> {
        // ...check that the right Options are Some for the flags that are set
    }
}

Two booleans and six optional paths can take 256 shapes. There are three real states: no TLS, TLS, or mutual TLS. The validate() method was there to police the other 253.

The review comment put it better than I would have. These fields aren't really optional. They're optional depending on the values of other fields, which means there are a few different variants of a TLS config. Here's what merged:

#[derive(Debug, Subcommand)]
pub enum TLSConfig {
    TLS(ServerOnlyTLSConfig),
    MutualTLS(MutualTLSConfig),
}

#[derive(Debug, Parser, Clone)]
pub struct MutualTLSConfig {
    #[clap(short, long)]
    pub server_certificate_path: PathBuf,
    #[clap(short, long)]
    pub server_private_key_path: PathBuf,
    #[clap(short, long)]
    pub client_certificate_authority_root_path: PathBuf,
}

With Option<TLSConfig> standing for "no TLS," the type has exactly three shapes. clap parses the command line straight into it, validate() disappeared, and the code that uses the config is a match. I knew the phrase "make invalid states unrepresentable" before this PR. This is where I understood it.

It's also John Ousterhout's "define errors out of existence," from A Philosophy of Software Design. My validate() was error handling for a mistake the design invited. Every caller had to remember to call it, and every new field meant another rule in it. The enum doesn't handle the error better. It makes the error impossible to write, so there's nothing to handle. I'll take a compiler that refuses bad input over a runtime check I have to remember every time.

Traits

The second thing I'm glad I got to use was traits. In #360, the Gateway controller and the new GatewayClass controller both needed to set status conditions on their objects. One trait, two implementations and one generic function covered both:

pub trait HasConditions {
    fn get_conditions_mut(&mut self) -> &mut Option<Vec<metav1::Condition>>;
}

impl HasConditions for Gateway {
    fn get_conditions_mut(&mut self) -> &mut Option<Vec<metav1::Condition>> {
        &mut self.status.as_mut().unwrap().conditions
    }
}

impl HasConditions for GatewayClass { /* same */ }

pub fn set_condition<T: HasConditions>(obj: &mut T, new_cond: metav1::Condition) {
    if let Some(ref mut conditions) = obj.get_conditions_mut() {
        for condition in conditions.iter_mut() {
            if condition.type_ == new_cond.type_ {
                if condition.status == new_cond.status {
                    condition.observed_generation = new_cond.observed_generation;
                    return;
                }
                *condition = new_cond;
                return;
            }
        }
        conditions.push(new_cond);
    } else {
        obj.get_conditions_mut().replace(vec![new_cond]);
    }
}

The interesting part is that Gateway and GatewayClass aren't Blixt's types. They come from the gateway_api crate. Rust let me implement my trait for someone else's types, which is one of Rust's many unique and endearing traits (no pun intended).

I think interfaces are the most foundational thing in software. The ability to build and maintain robust software systems rides or dies with your interfaces, whether they're the APIs between your services, the module interfaces inside your services, or even class and function interfaces. Each one either amplifies or hides complexity; makes changing and testing the code either harder and riskier or easier and safer.

In fact, one of the things I've enjoyed most about working with AI is that because it cuts down implementation time so much, I can spend a lot more time getting my interfaces right, which improves the implementation as a byproduct of having cleanly defined I/O, roles and responsibilities. What I love about Rust is that it elevates interfaces to first-class citizens with traits. Diving into traits and why I love them is a post for another day. I digress.

The appendix compares how other languages handle adding behavior to a type you don't own.

Testing without mocks

In the mTLS PR I asked how to test setup_tls without mocking read_to_string, because every approach I'd read about cluttered the code with dependency injection. The answer was to use real files:

#[tokio::test]
async fn test_tls_missing_key() -> Result<()> {
    let temp_dir = tempdir()?;
    let cert = generate_simple_self_signed(vec!["localhost".into()])?;
    let cert_path = temp_dir.path().join("server.crt");
    fs::write(&cert_path, cert.serialize_pem()?)?;

    let tls_config = Some(TLSConfig::TLS(ServerOnlyTLSConfig {
        server_certificate_path: cert_path,
        server_private_key_path: temp_dir.path().join("missing_server.key"),
    }));

    assert!(setup_tls(Server::builder(), &tls_config).is_err());
    Ok(())
}

rcgen generates the certificate and tempfile gives a directory that cleans itself up. The test exercises the real function against a real filesystem, and the production code didn't change shape to make it testable.

Sharp edges

Going back through my own code, some of it hasn't aged well.

is_accepted checks the wrong condition

pub fn is_accepted(gateway_class: &GatewayClass) -> bool {
    let mut accepted = false;
    if let Some(status) = &gateway_class.status {
        if let Some(conditions) = &status.conditions {
            for condition in conditions {
                // overwritten on every iteration: the *last* condition wins
                accepted = condition.type_ == GatewayConditionType::Accepted.to_string()
                    && condition.status == "True"
            }
        }
    }
    accepted
}

The loop overwrites accepted on every pass, so the answer comes from whichever condition is last, not from the Accepted one. It works only while Accepted is the only condition. Add any other condition after it and an accepted GatewayClass reads as not accepted. What I should have written:

pub fn is_accepted(gateway_class: &GatewayClass) -> bool {
    gateway_class
        .status
        .as_ref()
        .and_then(|s| s.conditions.as_deref())
        .unwrap_or_default()
        .iter()
        .any(|c| c.type_ == GatewayConditionType::Accepted.to_string() && c.status == "True")
}

It's still on main in the archived repo.

HasConditions can panic

Both implementations call self.status.as_mut().unwrap(). They're safe only because the Gateway API CRDs give a new object a default status. Without the panic:

fn get_conditions_mut(&mut self) -> &mut Option<Vec<metav1::Condition>> {
    &mut self.status.get_or_insert_with(Default::default).conditions
}

A Gateway that never wakes up

If a Gateway's GatewayClass isn't accepted yet, the Gateway controller returns await_change() and stops. But nothing watches the GatewayClass, so when it's accepted later, nothing tells the Gateway. The reviewer caught this and pointed me at kube-rs's Controller::watches(). It never got fixed.

Duplication in setup_tls

The TLS and mTLS branches of setup_tls both read the server certificate and key, with the same code twice. Mutual TLS is TLS plus a client CA, and the type could have said so:

pub struct MutualTLSConfig {
    #[command(flatten)]
    pub server: ServerOnlyTLSConfig,
    #[clap(short, long)]
    pub client_certificate_authority_root_path: PathBuf,
}

fn server_identity(cfg: &ServerOnlyTLSConfig) -> Result<Identity> { /* read cert + key once */ }

pub fn setup_tls(builder: Server, tls_config: &Option<TLSConfig>) -> Result<Server> {
    let tls = match tls_config {
        None => return Ok(builder),
        Some(TLSConfig::TLS(cfg)) => ServerTlsConfig::new().identity(server_identity(cfg)?),
        Some(TLSConfig::MutualTLS(cfg)) => ServerTlsConfig::new()
            .identity(server_identity(&cfg.server)?)
            .client_ca_root(read_ca(&cfg.client_certificate_authority_root_path)?),
    };
    Ok(builder.tls_config(tls)?)
}

That's a sketch, not compiled against the tonic and clap versions Blixt used.

The duplication is the small problem. The bigger one is that "mTLS is TLS plus a client CA" was a fact about the design that lived nowhere in the code. Two near-identical branches were the symptom. Ousterhout would call it a red flag for repetition. I'd call it a type that didn't say what it meant.

Why I stopped

#360 was my last PR. The project was already entering zombie mode when I joined. I was also doing a lot of background learning between each commit: kube-rs, Gateway API's primitives, Kubernetes controllers in general. The Gateway-watch bug shows why. Knowing that a Gateway should be re-checked when its class changes is Gateway API knowledge. Knowing how to wire that up is kube-rs knowledge. I had to go learn both.

What I took from it

  • Code review from experienced maintainers taught me more Rust than anything else. The enum review alone was worth the PR.
  • Volunteer projects move at volunteer speed. #280 took three months, and #360 was merged by a maintainer in an attempt to keep momentum up.
  • A project with no users is a great place to learn, and it's also why Blixt ended. Having a reason to exist is a good way to motivate learning and attract new maintainers, too. Nothing like a deadline and an external commitment to keep you going.

Thanks

Thank you to Blixt's maintainers, Shane Utt, Andrew Stoycos and Sanskar Jaiswal. You were gracious with your time, and you're great stewards and champions for Kubernetes SIG Network. It's the most welcoming group of intelligent people I've met, working on hard problems that make Kubernetes better for everyone.

Appendix: adding behavior to a type you don't own

HasConditions works because Rust let Blixt implement its own trait for types from another crate. Can you make someone else's type satisfy your interface? Most languages say no, or say yes in a way that hurts later:

Language Can you make someone else's type satisfy your interface?
Go No. Methods can only be declared on types in the same package. Interfaces are satisfied implicitly, which is nice, but only by methods the type already has. You write a wrapper.
Python Only at runtime. You can monkeypatch a method onto a class, but it's global, invisible to type checkers and breaks quietly. typing.Protocol checks shape but can't add behavior. functools.singledispatch is the closest thing to a trait.
TypeScript Sort of. Module augmentation can declare a method on another library's type, and you patch the prototype to back it up. Like Python, that's global and easy to get wrong.
Java No. A class lists its interfaces when it's declared. You write an adapter.
C# and Kotlin Extension methods add callable methods, but the type still doesn't implement your interface, so you can't pass it to code that expects one.
Swift Yes. Extensions can add protocol conformance to an existing type.
Haskell and Scala Yes. Type classes are where traits come from.
Rust Yes, checked at compile time and scoped: callers need the trait in scope.

In Go, the same idea needs a wrapper:

// Can't write `func (g *gatewayv1.Gateway) Conditions() ...` here:
// methods must live in the type's own package.
type gatewayWithConditions struct{ *gatewayv1.Gateway }

func (g gatewayWithConditions) Conditions() *[]metav1.Condition {
    return &g.Status.Conditions
}

In Python, the closest equivalent is single dispatch:

from functools import singledispatch

@singledispatch
def conditions(obj):
    raise NotImplementedError(type(obj))

@conditions.register
def _(obj: Gateway):
    return obj.status.conditions

Rust has one limit, called the orphan rule. You can implement your trait for their type, or their trait for your type, but not their trait for their type:

impl HasConditions for Gateway { /* fine: my trait, their type */ }

impl std::fmt::Display for Gateway { /* error[E0117]: their trait, their type */ }

struct MyGateway(Gateway); // a newtype gets around it
impl std::fmt::Display for MyGateway { /* fine */ }

The rule exists so two crates can't each write a conflicting implementation of the same trait for the same type. What you get is behavior that lives with the code that needs it, nothing mutated globally, and a compiler that checks all of it.